,
			"Failed to release wait fences ret:%d fence ctx:%llu ts:%llu\n",
			ret, fence->context, fence->seqno);
	} else {
		if (hash_index)
			*hash_index = handle;
	}

	return ret;
}

bool kgsl_hw_fence_tx_slot_available(struct kgsl_device *device, u32 pending_hw_fence_count)
{
	void *ptr = kgsl_synx.mem_descriptor.vaddr;
	struct synx_hw_fence_hfi_queue_header *hdr = (struct synx_hw_fence_hfi_queue_header *)
		(ptr + sizeof(struct synx_hw_fence_hfi_queue_table_header));
	u32 queue_size_dwords = hdr->queue_size / sizeof(u32);
	u32 payload_size_dwords = hdr->pkt_size / sizeof(u32);
	u32 free_entries, write_idx = hdr->write_index, read_idx = hdr->read_index;

	free_entries = read_idx <= write_idx ?
		queue_size_dwords - (write_idx - read_idx) :
		read_idx - write_idx;

	free_entries /= payload_size_dwords;

	/* Ensure free_entries does not become negative */
	if (free_entries == 0)
		return false;

	free_entries -= 1;

	if (free_entries > pending_hw_fence_count)
		return true;

	return false;
}

void _hw_fence_destroy(struct kgsl_sync_fence *kfence)
{
	synx_release(kgsl_synx.handle, kfence->hw_fence_index);

	/*
	 * synx_release() doesn't have a way to get to the dma fence. Hence, the client must clear
	 * this bit from the dma fence flags.
	 */
	clear_bit(SYNX_HW_FENCE_FLAG_ENABLED_BIT, &kfence->fence.flags);
}

void kgsl_hw_fence_trigger_cpu(struct kgsl_device *device, struct kgsl_sync_fence *kfence)
{
	/* soccp should be powered on */
	WARN_RATELIMIT(!test_bit(GMU_SOCCP_VOTE_ON, &device->gmu_core.flags),
		"signaling hw fence via cpu without soccp powered up\n");

	synx_signal(kgsl_synx.handle, (u32)kfence->hw_fence_index, SYNX_STATE_SIGNALED_SUCCESS);
}

bool kgsl_hw_fence_signaled(struct dma_fence *fence)
{
	return test_bit(SYNX_HW_FENCE_FLAG_SIGNALED_BIT, &fence->flags);
}

static bool kgsl_is_input_hw_fence(struct dma_fence *fence)
{
	return test_bit(SYNX_HW_FENCE_FLAG_ENABLED_BIT, &fence->flags) ||
		test_bit(SYNX_NATIVE_FENCE_FLAG_ENABLED_BIT, &fence->flags) || is_kgsl_fence(fence);
}

static bool kgsl_is_output_hw_fence(struct dma_fence *fence)
{
	return test_bit(SYNX_HW_FENCE_FLAG_ENABLED_BIT, &fence->flags);
}

#else

#if (KERNEL_VERSION(6, 3, 0) <= LINUX_VERSION_CODE)
#include <msm_hw_fence.h>
#else
#include <linux/soc/qcom/msm_hw_fence.h>
#endif

static struct msm_hw_fence_descriptor {
	/** @handle: Handle for hardware fences */
	void *handle;
	/** @descriptor: Memory descriptor for hardware fences */
	struct msm_hw_fence_mem_addr mem_descriptor;
} kgsl_msm_hw_fence;

int kgsl_hw_fence_soccp_vote(bool pwr_on)
{
	return -EINVAL;
}

int kgsl_hw_fence_init(struct kgsl_device *device)
{
	kgsl_msm_hw_fence.handle = msm_hw_fence_register(HW_FENCE_CLIENT_ID_CTX0,
				&kgsl_msm_hw_fence.mem_descriptor);

	if (IS_ERR_OR_NULL(kgsl_msm_hw_fence.handle)) {
		dev_err(device->dev, "HW fences not supported: %d\n",
			PTR_ERR_OR_ZERO(kgsl_msm_hw_fence.handle));
		kgsl_msm_hw_fence.handle = NULL;
		return -EINVAL;
	}

	INIT_LIST_HEAD(&hw_fence_list);
	spin_lock_init(&hw_fence_list_lock);

	return 0;
}

void kgsl_hw_fence_close(struct kgsl_device *device)
{
	destroy_all_hw_fences();

	msm_hw_fence_deregister(kgsl_msm_hw_fence.handle);
}

void kgsl_hw_fence_populate_md(struct kgsl_device *device, struct kgsl_memdesc *md)
{
	md->physaddr = kgsl_msm_hw_fence.mem_descriptor.device_addr;
	md->size = kgsl_msm_hw_fence.mem_descriptor.size;
	md->hostptr = kgsl_msm_hw_fence.mem_descriptor.virtual_addr;
}

int kgsl_hw_fence_create(struct kgsl_device *device, struct kgsl_sync_fence *kfence)
{
	struct msm_hw_fence_create_params params = {0};
	int ret;

	params.fence = &kfence->fence;
	params.handle = &kfence->hw_fence_index;

	ret = msm_hw_fence_create(kgsl_msm_hw_fence.handle, &params);
	if ((ret || IS_ERR_OR_NULL(params.handle))) {
		if (__ratelimit(&_rs))
			dev_err(device->dev, "Failed to create ctx:%d ts:%d hardware fence:%d\n",
				kfence->context_id, kfence->timestamp, ret);
		return -EINVAL;
	}

	add_hw_fence(kfence);

	return 0;
}

int kgsl_hw_fence_add_waiter(struct kgsl_device *device, struct dma_fence *fence, u32 *hash_index)
{
	u64 handle = 0;
	int ret = msm_hw_fence_wait_update_v2(kgsl_msm_hw_fence.handle, &fence, &handle, NULL, 1,
			true);

	if (ret)
		dev_err_ratelimited(device->dev,
			"Failed to add GMU as waiter ret:%d fence ctx:%llu ts:%llu\n",
			ret, fence->context, fence->seqno);
	else {
		if (hash_index)
			*hash_index = (u32)handle;
	}

	return ret;
}

bool kgsl_hw_fence_tx_slot_available(struct kgsl_device *device, u32 pending_hw_fence_count)
{
	void *ptr = kgsl_msm_hw_fence.mem_descriptor.virtual_addr;
	struct msm_hw_fence_hfi_queue_header *hdr = (struct msm_hw_fence_hfi_queue_header *)
		(ptr + sizeof(struct msm_hw_fence_hfi_queue_table_header));
	u32 queue_size_dwords = hdr->queue_size / sizeof(u32);
	u32 payload_size_dwords = hdr->pkt_size / sizeof(u32);
	u32 free_entries, write_idx = hdr->write_index, read_idx = hdr->read_index;

	free_entries = read_idx <= write_idx ?
		queue_size_dwords - (write_idx - read_idx) :
		read_idx - write_idx;

	free_entries /= payload_size_dwords;

	/* Ensure free_entries does not become negative */
	if (free_entries == 0)
		return false;

	free_entries -= 1;

	if (free_entries > pending_hw_fence_count)
		return true;

	return false;
}

void _hw_fence_destroy(struct kgsl_sync_fence *kfence)
{
	msm_hw_fence_destroy(kgsl_msm_hw_fence.handle, &kfence->fence);
}

#define IPCC_GPU_PHYS_ID 4
void kgsl_hw_fence_trigger_cpu(struct kgsl_device *device, struct kgsl_sync_fence *kfence)
{
	int ret = msm_hw_fence_update_txq(kgsl_msm_hw_fence.handle, kfence->hw_fence_index,
				0, 0);
	if (ret) {
		dev_err_ratelimited(device->dev,
			"Failed to trigger hw fence via cpu: ctx:%d ts:%d ret:%d\n",
			kfence->context_id, kfence->timestamp, ret);
		return;
	}

	msm_hw_fence_trigger_signal(kgsl_msm_hw_fence.handle, IPCC_GPU_PHYS_ID,
		IPCC_CLIENT_APSS, 0);
}

bool kgsl_hw_fence_signaled(struct dma_fence *fence)
{
	return test_bit(MSM_HW_FENCE_FLAG_SIGNALED_BIT, &fence->flags);
}

static bool kgsl_is_output_hw_fence(struct dma_fence *fence)
{
	return test_bit(MSM_HW_FENCE_FLAG_ENABLED_BIT, &fence->flags);
}

static bool kgsl_is_input_hw_fence(struct dma_fence *fence)
{
	return test_bit(MSM_HW_FENCE_FLAG_ENABLED_BIT, &fence->flags);
}

#endif

static struct kgsl_sync_fence *kgsl_sync_fence_create(
					struct kgsl_context *context,
					unsigned int timestamp)
{
	struct kgsl_sync_fence *kfence;
	struct kgsl_sync_timeline *ktimeline = context->ktimeline;
	unsigned long flags;

	/* Get a refcount to the timeline. Put when released */
	if (!kref_get_unless_zero(&ktimeline->kref))
		return NULL;

	kfence = kzalloc(sizeof(*kfence), GFP_KERNEL);
	if (kfence == NULL) {
		kgsl_sync_timeline_put(ktimeline);
		return NULL;
	}

	kfence->parent = ktimeline;
	kfence->context_id = context->id;
	kfence->timestamp = timestamp;

	dma_fence_init(&kfence->fence, &kgsl_sync_fence_ops, &ktimeline->lock,
		ktimeline->fence_context, timestamp);

	/*
	 * sync_file_create() takes a refcount to the fence. This refcount is
	 * put when the fence is signaled.
	 */
	kfence->sync_file = sync_file_create(&kfence->fence);

	if (kfence->sync_file == NULL) {
		kgsl_sync_timeline_put(ktimeline);
		dev_err(context->device->dev, "Create sync_file failed\n");
		kfree(kfence);
		return NULL;
	}

	spin_lock_irqsave(&ktimeline->lock, flags);
	list_add_tail(&kfence->child_list, &ktimeline->child_list_head);
	spin_unlock_irqrestore(&ktimeline->lock, flags);

	return kfence;
}

static void kgsl_sync_fence_release(struct dma_fence *fence)
{
	struct kgsl_sync_fence *kfence = (struct kgsl_sync_fence *)fence;

	if (kgsl_is_output_hw_fence(fence))
		kgsl_hw_fence_destroy(kfence);

	kgsl_sync_timeline_put(kfence->parent);
	kfree(kfence);
}

/* Called with ktimeline->lock held */
static bool kgsl_sync_fence_has_signaled(struct dma_fence *fence)
{
	struct kgsl_sync_fence *kfence = (struct kgsl_sync_fence *)fence;
	struct kgsl_sync_timeline *ktimeline = kfence->parent;
	unsigned int ts = kfence->timestamp;

	return (timestamp_cmp(ktimeline->last_timestamp, ts) >= 0);
}

static bool kgsl_enable_signaling(struct dma_fence *fence)
{
	return !kgsl_sync_fence_has_signaled(fence);
}

struct kgsl_sync_fence_event_priv {
	struct kgsl_context *context;
	unsigned int timestamp;
};

/**
 * kgsl_sync_fence_event_cb - Event callback for a fence timestamp event
 * @device - The KGSL device that expired the timestamp
 * @context- Pointer to the context that owns the event
 * @priv: Private data for the callback
 * @result - Result of the event (retired or canceled)
 *
 * Signal a fence following the expiration of a timestamp
 */

static void kgsl_sync_fence_event_cb(struct kgsl_device *device,
		struct kgsl_event_group *group, void *priv, int result)
{
	struct kgsl_sync_fence_event_priv *ev = priv;

	kgsl_sync_timeline_signal(ev->context->ktimeline, ev->timestamp);
	kgsl_context_put(ev->context);
	kfree(ev);
}

static int _add_fence_event(struct kgsl_device *device,
	struct kgsl_context *context, unsigned int timestamp)
{
	struct kgsl_sync_fence_event_priv *event;
	int ret;

	event = kmalloc(sizeof(*event), GFP_KERNEL);
	if (event == NULL)
		return -ENOMEM;

	/*
	 * Increase the refcount for the context to keep it through the
	 * callback
	 */
	if (!_kgsl_context_get(context)) {
		kfree(event);
		return -ENOENT;
	}

	event->context = context;
	event->timestamp = timestamp;

	ret = kgsl_add_event(device, &context->events, timestamp,
		kgsl_sync_fence_event_cb, event);

	if (ret) {
		kgsl_context_put(context);
		kfree(event);
	}

	return ret;
}

/* Only to be used if creating a related event failed */
static void kgsl_sync_cancel(struct kgsl_sync_fence *kfence)
{
	spin_lock(&kfence->parent->lock);
	if (!list_empty(&kfence->child_list)) {
		list_del_init(&kfence->child_list);
		dma_fence_put(&kfence->fence);
	}
	spin_unlock(&kfence->parent->lock);
}

/**
 * kgsl_add_fence_event - Create a new fence event
 * @device - KGSL device to create the event on
 * @timestamp - Timestamp to trigger the event
 * @data - Return fence fd stored in struct kgsl_timestamp_event_fence
 * @len - length of the fence event
 * @owner - driver instance that owns this event
 * @returns 0 on success or error code on error
 *
 * Create a fence and register an event to signal the fence when
 * the timestamp expires
 */

int kgsl_add_fence_event(struct kgsl_device *device,
	u32 context_id, u32 timestamp, void __user *data, int len,
	struct kgsl_device_private *owner)
{
	struct kgsl_timestamp_event_fence priv;
	struct kgsl_context *context;
	struct kgsl_sync_fence *kfence = NULL;
	int ret = -EINVAL;
	unsigned int cur;
	bool retired = false;

	priv.fence_fd = -1;

	if (len != sizeof(priv))
		return -EINVAL;

	context = kgsl_context_get_owner(owner, context_id);

	if (context == NULL)
		return -EINVAL;

	if (test_bit(KGSL_CONTEXT_PRIV_INVALID, &context->priv))
		goto out;

	kfence = kgsl_sync_fence_create(context, timestamp);
	if (kfence == NULL) {
		ret = -ENOMEM;
		goto out;
	}

	priv.fence_fd = get_unused_fd_flags(0);
	if (priv.fence_fd < 0) {
		dev_crit_ratelimited(device->dev,
					"Unable to get a file descriptor: %d\n",
					priv.fence_fd);
		ret = priv.fence_fd;
		goto out;
	}

	/*
	 * If the timestamp hasn't expired yet create an event to trigger it.
	 * Otherwise, just signal the fence - there is no reason to go through
	 * the effort of creating a fence we don't need.
	 */

	kgsl_readtimestamp(device, context, KGSL_TIMESTAMP_RETIRED, &cur);

	retired = timestamp_cmp(cur, timestamp) >= 0;

	if (retired) {
		ret = 0;
		kgsl_sync_timeline_signal(context->ktimeline, cur);
	} else {
		ret = _add_fence_event(device, context, timestamp);
		if (ret)
			goto out;
	}

	if (copy_to_user(data, &priv, sizeof(priv))) {
		ret = -EFAULT;
		goto out;
	}

	if (!retired)
		device->ftbl->create_hw_fence(device, kfence);

	fd_install(priv.fence_fd, kfence->sync_file->file);

out:
	kgsl_context_put(context);
	if (ret) {
		if (priv.fence_fd >= 0)
			put_unused_fd(priv.fence_fd);

		if (kfence) {
			kgsl_sync_cancel(kfence);
			/*
			 * Put the refcount of sync file. This will release
			 * kfence->fence as well.
			 */
			fput(kfence->sync_file->file);
		}
	}
	return ret;
}

void kgsl_sync_timeline_value_str(struct dma_fence *fence, char *str, int size)
{
	struct kgsl_sync_fence *kfence = (struct kgsl_sync_fence *)fence;
	struct kgsl_sync_timeline *ktimeline = kfence->parent;
	struct kgsl_context *context = NULL;
	unsigned long flags;
	int ret = 0;

	unsigned int timestamp_retired;
	unsigned int timestamp_queued;

	if (fence->ops != &kgsl_sync_fence_ops)
		return;

	if (!kref_get_unless_zero(&ktimeline->kref))
		return;
	if (!ktimeline->device)
		goto put_timeline;

	spin_lock_irqsave(&ktimeline->lock, flags);
	ret = _kgsl_context_get(ktimeline->context);
	context = ret ? ktimeline->context : NULL;
	spin_unlock_irqrestore(&ktimeline->lock, flags);

	/* Get the last signaled timestamp if the context is not valid */
	timestamp_queued = ktimeline->last_timestamp;
	timestamp_retired = timestamp_queued;
	if (context) {
		kgsl_readtimestamp(ktimeline->device, context,
			KGSL_TIMESTAMP_RETIRED, &timestamp_retired);

		kgsl_readtimestamp(ktimeline->device, context,
			KGSL_TIMESTAMP_QUEUED, &timestamp_queued);

		kgsl_context_put(context);
	}

	snprintf(str, size, "%u queued:%u retired:%u",
		ktimeline->last_timestamp,
		timestamp_queued, timestamp_retired);

put_timeline:
	kgsl_sync_timeline_put(ktimeline);
}

static void kgsl_sync_fence_value_str(struct dma_fence *fence,
					char *str, int size)
{
	struct kgsl_sync_fence *kfence = (struct kgsl_sync_fence *)fence;

	snprintf(str, size, "%u", kfence->timestamp);
}

static const char *kgsl_sync_fence_driver_name(struct dma_fence *fence)
{
	return "kgsl-timeline";
}

static const char *kgsl_sync_timeline_name(struct dma_fence *fence)
{
	struct kgsl_sync_fence *kfence = (struct kgsl_sync_fence *)fence;
	struct kgsl_sync_timeline *ktimeline = kfence->parent;

	return ktimeline->name;
}

int kgsl_sync_timeline_create(struct kgsl_context *context)
{
	struct kgsl_sync_timeline *ktimeline;

	/* Put context at detach time */
	if (!_kgsl_context_get(context))
		return -ENOENT;

	ktimeline = kzalloc(sizeof(*ktimeline), GFP_KERNEL);
	if (ktimeline == NULL) {
		kgsl_context_put(context);
		return -ENOMEM;
	}

	kref_init(&ktimeline->kref);
	snprintf(ktimeline->name, sizeof(ktimeline->name),
		"%s_%u-%.15s(%d)-%.15s(%d)",
		context->device->name, context->id,
		current->group_leader->comm, current->group_leader->pid,
		current->comm, current->pid);

	ktimeline->fence_context = dma_fence_context_alloc(1);
	ktimeline->last_timestamp = 0;
	INIT_LIST_HEAD(&ktimeline->child_list_head);
	spin_lock_init(&ktimeline->lock);
	ktimeline->device = context->device;

	/*
	 * The context pointer is valid till detach time, where we put the
	 * refcount on the context
	 */
	ktimeline->context = context;

	context->ktimeline = ktimeline;

	return 0;
}

void kgsl_sync_timeline_signal(struct kgsl_sync_timeline *ktimeline,
					unsigned int timestamp)
{
	unsigned long flags;
	struct kgsl_sync_fence *kfence, *next;

	if (!kref_get_unless_zero(&ktimeline->kref))
		return;

	spin_lock_irqsave(&ktimeline->lock, flags);
	if (timestamp_cmp(timestamp, ktimeline->last_timestamp) > 0)
		ktimeline->last_timestamp = timestamp;

	list_for_each_entry_safe(kfence, next, &ktimeline->child_list_head,
				child_list) {
		if (dma_fence_is_signaled_locked(&kfence->fence)) {
			list_del_init(&kfence->child_list);
			dma_fence_put(&kfence->fence);
		}
	}

	spin_unlock_irqrestore(&ktimeline->lock, flags);
	kgsl_sync_timeline_put(ktimeline);
}

void kgsl_sync_timeline_detach(struct kgsl_sync_timeline *ktimeline)
{
	unsigned long flags;
	struct kgsl_context *context = ktimeline->context;

	/* Set context pointer to NULL and drop our refcount on the context */
	spin_lock_irqsave(&ktimeline->lock, flags);
	ktimeline->context = NULL;
	spin_unlock_irqrestore(&ktimeline->lock, flags);
	kgsl_context_put(context);
}

static void kgsl_sync_timeline_destroy(struct kref *kref)
{
	struct kgsl_sync_timeline *ktimeline =
		container_of(kref, struct kgsl_sync_timeline, kref);

	kfree(ktimeline);
}

void kgsl_sync_timeline_put(struct kgsl_sync_timeline *ktimeline)
{
	if (ktimeline)
		kref_put(&ktimeline->kref, kgsl_sync_timeline_destroy);
}

const struct dma_fence_ops kgsl_sync_fence_ops = {
	.get_driver_name = kgsl_sync_fence_driver_name,
	.get_timeline_name = kgsl_sync_timeline_name,
	.enable_signaling = kgsl_enable_signaling,
	.signaled = kgsl_sync_fence_has_signaled,
	.wait = dma_fence_default_wait,
	.release = kgsl_sync_fence_release,

#if (KERNEL_VERSION(6, 16, 0) > LINUX_VERSION_CODE)
	.fence_value_str = kgsl_sync_fence_value_str,
	.timeline_value_str = kgsl_sync_timeline_value_str,
#endif
};

static void kgsl_sync_fence_callback(struct dma_fence *fence,
					 struct dma_fence_cb *cb)
{
	struct kgsl_sync_fence_cb *kcb = (struct kgsl_sync_fence_cb *)cb;

	kcb->func(kcb->priv);
}

bool is_kgsl_fence(struct dma_fence *f)
{
	if (f->ops == &kgsl_sync_fence_ops)
		return true;

	return false;
}

void kgsl_hw_fence_destroy(struct kgsl_sync_fence *kfence)
{
	spin_lock(&hw_fence_list_lock);

	if (!list_empty(&kfence->hw_fence_list)) {
		_hw_fence_destroy(kfence);
		list_del_init(&kfence->hw_fence_list);
	}

	spin_unlock(&hw_fence_list_lock);
}

static void destroy_all_hw_fences(void)
{
	struct kgsl_sync_fence *kfence, *next;

	spin_lock(&hw_fence_list_lock);

	list_for_each_entry_safe(kfence, next, &hw_fence_list, hw_fence_list) {
		_hw_fence_destroy(kfence);
		list_del_init(&kfence->hw_fence_list);
	}

	spin_unlock(&hw_fence_list_lock);
}

static void kgsl_count_hw_fences(struct kgsl_drawobj_sync_event *event, struct dma_fence *fence)
{
	struct kgsl_drawobj_sync *syncobj = event->syncobj;
	u32 max_hw_fence = event->device->max_syncobj_hw_fence_count;

	if (test_bit(KGSL_SYNCOBJ_SW, &syncobj->flags))
		return;

	if (!kgsl_is_input_hw_fence(fence)) {
		/*
		 * Ignore software fences that are already signaled. Even one unsignaled sw-only
		 * fence in this sync object means we can't send this sync object to the hardware
		 */
		if (!dma_fence_is_signaled(fence))
			set_bit(KGSL_SYNCOBJ_SW, &syncobj->flags);
		return;
	}

	if (!syncobj->hw_fences) {
		syncobj->hw_fences = kcalloc(max_hw_fence, sizeof(*syncobj->hw_fences), GFP_KERNEL);
		if (!syncobj->hw_fences) {
			set_bit(KGSL_SYNCOBJ_SW, &syncobj->flags);
			return;
		}
	}

	if (syncobj->num_hw_fence < max_hw_fence)
		syncobj->hw_fences[syncobj->num_hw_fence++].fence = fence;
	else
		set_bit(KGSL_SYNCOBJ_SW, &syncobj->flags);
}

static void kgsl_syncsource_fence_value_str(struct dma_fence *fence, char *str, int size)
{
	/*
	 * Each fence is independent of the others on the same timeline.
	 * We use a different context for each of them.
	 */
	snprintf(str, size, "%llu", fence->context);
}

#if (KERNEL_VERSION(6, 16, 0) > LINUX_VERSION_CODE)
static int kgsl_get_fence_value_str(struct dma_fence *fence, char *buf, size_t size)
{
	int len = 0;

	if (!fence || !fence->ops || !buf)
		return 0;

	if (fence->ops->fence_value_str) {
		len += scnprintf(buf + len, size - len, ": ");
		fence->ops->fence_value_str(fence, buf + len, size - len);
	}

	return len;
}
#else
static int kgsl_get_fence_value_str(struct dma_fence *fence, char *buf, size_t size)
{
	int len = 0;

	if (!fence || !fence->ops || !buf)
		return 0;

	if (fence->ops == &kgsl_sync_fence_ops) {
		len += scnprintf(buf + len, size - len, ": ");
		kgsl_sync_fence_value_str(fence, buf + len, size - len);
	}

	if (fence->ops == &kgsl_syncsource_fence_ops) {
		len += scnprintf(buf + len, size - len, ": ");
		kgsl_syncsource_fence_value_str(fence, buf + len, size - len);
	}

	return len;
}
#endif

void kgsl_get_fence_name(struct dma_fence *f, char *name, u32 max_size)
{
	int len = scnprintf(name, max_size, "%s %s", f->ops->get_driver_name(f),
			f->ops->get_timeline_name(f));

	len += kgsl_get_fence_value_str(f, name + len, max_size - len);

}

void kgsl_get_fence_info(struct kgsl_drawobj_sync_event *event)
{
	unsigned int num_fences;
	struct dma_fence *fence, **fences;
	struct dma_fence_array *array;
	struct event_fence_info *info_ptr = event->priv;
	int i;

	fence = event->handle->fence;

	array = to_dma_fence_array(fence);
	if (array != NULL) {
		num_fences = array->num_fences;
		fences = array->fences;
	} else {
		num_fences = 1;
		fences = &fence;
	}

	if (!info_ptr)
		goto count;

	info_ptr->fences = kcalloc(num_fences, sizeof(struct fence_info),
			GFP_KERNEL);
	if (info_ptr->fences == NULL)
		goto count;

	info_ptr->num_fences = num_fences;

	for (i = 0; i < num_fences; i++) {
		struct dma_fence *f = fences[i];
		struct fence_info *fi = &info_ptr->fences[i];

		kgsl_get_fence_name(f, fi->name, sizeof(fi->name));

		kgsl_count_hw_fences(event, f);
	}

	return;
count:
	for (i = 0; i < num_fences; i++)
		kgsl_count_hw_fences(event, fences[i]);
}

struct kgsl_sync_fence_cb *kgsl_sync_fence_async_wait(int fd,
	bool (*func)(void *priv), void *priv)
{
	struct kgsl_sync_fence_cb *kcb;
	struct dma_fence *fence;
	int status;

	fence = sync_file_get_fence(fd);
	if (fence == NULL)
		return ERR_PTR(-EINVAL);

	/* create the callback */
	kcb = kzalloc(sizeof(*kcb), GFP_KERNEL);
	if (kcb == NULL) {
		dma_fence_put(fence);
		return ERR_PTR(-ENOMEM);
	}

	kcb->fence = fence;
	kcb->priv = priv;
	kcb->func = func;

	/* if status then error or signaled */
	status = dma_fence_add_callback(fence, &kcb->fence_cb,
				kgsl_sync_fence_callback);

	if (status) {
		kfree(kcb);
		if (!dma_fence_is_signaled(fence))
			kcb = ERR_PTR(status);
		else
			kcb = NULL;
		dma_fence_put(fence);
	}

	return kcb;
}

/*
 * Cancel the fence async callback.
 */
void kgsl_sync_fence_async_cancel(struct kgsl_sync_fence_cb *kcb)
{
	if (kcb == NULL)
		return;

	dma_fence_remove_callback(kcb->fence, &kcb->fence_cb);
}

struct kgsl_syncsource {
	struct kref refcount;
	char name[32];
	int id;
	struct kgsl_process_private *private;
	struct list_head child_list_head;
	spinlock_t lock;
};

struct kgsl_syncsource_fence {
	struct dma_fence fence;
	struct kgsl_syncsource *parent;
	struct list_head child_list;
};

long kgsl_ioctl_syncsource_create(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	struct kgsl_syncsource *syncsource = NULL;
	struct kgsl_syncsource_create *param = data;
	int ret = -EINVAL;
	int id = 0;
	struct kgsl_process_private *private = dev_priv->process_priv;

	if (!kgsl_process_private_get(private))
		return ret;

	syncsource = kzalloc(sizeof(*syncsource), GFP_KERNEL);
	if (syncsource == NULL) {
		ret = -ENOMEM;
		goto out;
	}

	kref_init(&syncsource->refcount);
	snprintf(syncsource->name, sizeof(syncsource->name),
		"kgsl-syncsource-pid-%d", current->group_leader->pid);
	syncsource->private = private;
	INIT_LIST_HEAD(&syncsource->child_list_head);
	spin_lock_init(&syncsource->lock);

	idr_preload(GFP_KERNEL);
	spin_lock(&private->syncsource_lock);
	id = idr_alloc(&private->syncsource_idr, syncsource, 1, 0, GFP_NOWAIT);
	if (id > 0) {
		syncsource->id = id;
		param->id = id;
		ret = 0;
	} else {
		ret = id;
	}

	spin_unlock(&private->syncsource_lock);
	idr_preload_end();

out:
	if (ret) {
		kgsl_process_private_put(private);
		kfree(syncsource);
	}

	return ret;
}

static struct kgsl_syncsource *
kgsl_syncsource_get(struct kgsl_process_private *private, int id)
{
	int result = 0;
	struct kgsl_syncsource *syncsource = NULL;

	spin_lock(&private->syncsource_lock);

	syncsource = idr_find(&private->syncsource_idr, id);
	if (syncsource)
		result = kref_get_unless_zero(&syncsource->refcount);

	spin_unlock(&private->syncsource_lock);

	return result ? syncsource : NULL;
}

static void kgsl_syncsource_destroy(struct kref *kref)
{
	struct kgsl_syncsource *syncsource = container_of(kref,
						struct kgsl_syncsource,
						refcount);

	struct kgsl_process_private *private = syncsource->private;

	/* Done with process private. Release the refcount */
	kgsl_process_private_put(private);

	kfree(syncsource);
}

void kgsl_syncsource_put(struct kgsl_syncsource *syncsource)
{
	if (syncsource)
		kref_put(&syncsource->refcount, kgsl_syncsource_destroy);
}

static void kgsl_syncsource_cleanup(struct kgsl_process_private *private,
				struct kgsl_syncsource *syncsource)
{
	struct kgsl_syncsource_fence *sfence, *next;
	unsigned long flags;

	/* Signal all fences to release any callbacks */
	spin_lock_irqsave(&syncsource->lock, flags);

	list_for_each_entry_safe(sfence, next, &syncsource->child_list_head,
				child_list) {
		dma_fence_signal_locked(&sfence->fence);
		list_del_init(&sfence->child_list);
	}

	spin_unlock_irqrestore(&syncsource->lock, flags);

	/* put reference from syncsource creation */
	kgsl_syncsource_put(syncsource);
}

long kgsl_ioctl_syncsource_destroy(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	struct kgsl_syncsource_destroy *param = data;
	struct kgsl_syncsource *syncsource = NULL;
	struct kgsl_process_private *private = dev_priv->process_priv;

	spin_lock(&private->syncsource_lock);
	syncsource = idr_find(&private->syncsource_idr, param->id);

	if (syncsource == NULL) {
		spin_unlock(&private->syncsource_lock);
		return -EINVAL;
	}

	if (syncsource->id != 0) {
		idr_remove(&private->syncsource_idr, syncsource->id);
		syncsource->id = 0;
	}
	spin_unlock(&private->syncsource_lock);

	kgsl_syncsource_cleanup(private, syncsource);
	return 0;
}

long kgsl_ioctl_syncsource_create_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	struct kgsl_syncsource_create_fence *param = data;
	struct kgsl_syncsource *syncsource = NULL;
	int ret = -EINVAL;
	struct kgsl_syncsource_fence *sfence = NULL;
	struct sync_file *sync_file = NULL;
	int fd = -1;
	unsigned long flags;

	/*
	 * Take a refcount that is released when the fence is released
	 * (or if fence can't be added to the syncsource).
	 */
	syncsource = kgsl_syncsource_get(dev_priv->process_priv,
					param->id);
	if (syncsource == NULL)
		goto out;

	sfence = kzalloc(sizeof(*sfence), GFP_KERNEL);
	if (sfence == NULL) {
		ret = -ENOMEM;
		goto out;
	}
	sfence->parent = syncsource;

	/* Use a new fence context for each fence */
	dma_fence_init(&sfence->fence, &kgsl_syncsource_fence_ops,
		&syncsource->lock, dma_fence_context_alloc(1), 1);

	sync_file = sync_file_create(&sfence->fence);

	if (sync_file == NULL) {
		dev_err(dev_priv->device->dev,
			     "Create sync_file failed\n");
		ret = -ENOMEM;
		goto out;
	}

	fd = get_unused_fd_flags(0);
	if (fd < 0) {
		ret = -EBADF;
		goto out;
	}
	ret = 0;

	fd_install(fd, sync_file->file);

	param->fence_fd = fd;

	spin_lock_irqsave(&syncsource->lock, flags);
	list_add_tail(&sfence->child_list, &syncsource->child_list_head);
	spin_unlock_irqrestore(&syncsource->lock, flags);
out:
	/*
	 * We're transferring ownership of the fence to the sync file.
	 * The sync file takes an extra refcount when it is created, so put
	 * our refcount.
	 */
	if (sync_file)
		dma_fence_put(&sfence->fence);

	if (ret) {
		if (sync_file)
			fput(sync_file->file);
		else if (sfence)
			dma_fence_put(&sfence->fence);
		else
			kgsl_syncsource_put(syncsource);
	}

	return ret;
}

static int kgsl_syncsource_signal(struct kgsl_syncsource *syncsource,
					struct dma_fence *fence)
{
	struct kgsl_syncsource_fence *sfence, *next;
	int ret = -EINVAL;
	unsigned long flags;

	spin_lock_irqsave(&syncsource->lock, flags);

	list_for_each_entry_safe(sfence, next, &syncsource->child_list_head,
				child_list) {
		if (fence == &sfence->fence) {
			dma_fence_signal_locked(fence);
			list_del_init(&sfence->child_list);

			ret = 0;
			break;
		}
	}

	spin_unlock_irqrestore(&syncsource->lock, flags);

	return ret;
}

long kgsl_ioctl_syncsource_signal_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	int ret = -EINVAL;
	struct kgsl_syncsource_signal_fence *param = data;
	struct kgsl_syncsource *syncsource = NULL;
	struct dma_fence *fence = NULL;

	syncsource = kgsl_syncsource_get(dev_priv->process_priv,
					param->id);
	if (syncsource == NULL)
		goto out;

	fence = sync_file_get_fence(param->fence_fd);
	if (fence == NULL) {
		ret = -EBADF;
		goto out;
	}

	ret = kgsl_syncsource_signal(syncsource, fence);
out:
	if (fence)
		dma_fence_put(fence);
	if (syncsource)
		kgsl_syncsource_put(syncsource);
	return ret;
}

static void kgsl_syncsource_fence_release(struct dma_fence *fence)
{
	struct kgsl_syncsource_fence *sfence =
			(struct kgsl_syncsource_fence *)fence;

	/* Signal if it's not signaled yet */
	kgsl_syncsource_signal(sfence->parent, fence);

	/* Release the refcount on the syncsource */
	kgsl_syncsource_put(sfence->parent);

	kfree(sfence);
}

void kgsl_syncsource_process_release_syncsources(
		struct kgsl_process_private *private)
{
	struct kgsl_syncsource *syncsource;
	int next = 0;

	while (1) {
		spin_lock(&private->syncsource_lock);
		syncsource = idr_get_next(&private->syncsource_idr, &next);

		if (syncsource == NULL) {
			spin_unlock(&private->syncsource_lock);
			break;
		}

		if (syncsource->id != 0) {
			idr_remove(&private->syncsource_idr, syncsource->id);
			syncsource->id = 0;
		}
		spin_unlock(&private->syncsource_lock);

		kgsl_syncsource_cleanup(private, syncsource);
		next = next + 1;
	}
}

static const char *kgsl_syncsource_get_timeline_name(struct dma_fence *fence)
{
	struct kgsl_syncsource_fence *sfence =
			(struct kgsl_syncsource_fence *)fence;
	struct kgsl_syncsource *syncsource = sfence->parent;

	return syncsource->name;
}

static bool kgsl_syncsource_enable_signaling(struct dma_fence *fence)
{
	return true;
}

static const char *kgsl_syncsource_driver_name(struct dma_fence *fence)
{
	return "kgsl-syncsource-timeline";
}

static const struct dma_fence_ops kgsl_syncsource_fence_ops = {
	.get_driver_name = kgsl_syncsource_driver_name,
	.get_timeline_name = kgsl_syncsource_get_timeline_name,
	.enable_signaling = kgsl_syncsource_enable_signaling,
	.wait = dma_fence_default_wait,
	.release = kgsl_syncsource_fence_release,

#if (KERNEL_VERSION(6, 16, 0) > LINUX_VERSION_CODE)
	.fence_value_str = kgsl_syncsource_fence_value_str,
#endif
};



============================================================
FILE: kgsl_sync.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2012-2014,2018-2019, 2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */
#ifndef __KGSL_SYNC_H
#define __KGSL_SYNC_H

#include <linux/dma-fence.h>

/**
 * struct kgsl_sync_timeline - A sync timeline associated with a kgsl context
 * @kref: Refcount to keep the struct alive until all its fences are signaled,
	  and as long as the context exists
 * @name: String to describe this timeline
 * @fence_context: Used by the fence driver to identify fences belonging to
 *		   this context
 * @child_list_head: List head for all fences on this timeline
 * @lock: Spinlock to protect this timeline
 * @last_timestamp: Last timestamp when signaling fences
 * @device: kgsl device
 * @context: kgsl context
 */
struct kgsl_sync_timeline {
	struct kref kref;
	char name[32];

	u64 fence_context;

	struct list_head child_list_head;

	spinlock_t lock;
	unsigned int last_timestamp;
	struct kgsl_device *device;
	struct kgsl_context *context;
};

/**
 * struct kgsl_sync_fence - A struct containing a fence and other data
 *				associated with it
 * @fence: The fence struct
 * @sync_file: Pointer to the sync file
 * @parent: Pointer to the kgsl sync timeline this fence is on
 * @child_list: List of fences on the same timeline
 * @context_id: kgsl context id
 * @timestamp: Context timestamp that this fence is associated with
 */
struct kgsl_sync_fence {
	struct dma_fence fence;
	struct sync_file *sync_file;
	struct kgsl_sync_timeline *parent;
	struct list_head child_list;
	u32 context_id;
	unsigned int timestamp;
	/** @hw_fence_index: Index of hw fence in hw fence table */
	u64 hw_fence_index;
	/** @hw_fence_list: Global list of hw fences */
	struct list_head hw_fence_list;
};

/**
 * struct kgsl_sync_fence_cb - Used for fence callbacks
 * fence_cb: Fence callback struct
 * fence: Pointer to the fence for which the callback is done
 * priv: Private data for the callback
 * func: Pointer to the kgsl function to call. This function should return
 * false if the sync callback is marked for cancellation in a separate thread.
 */
struct kgsl_sync_fence_cb {
	struct dma_fence_cb fence_cb;
	struct dma_fence *fence;
	void *priv;
	bool (*func)(void *priv);
};

struct kgsl_device_private;
struct kgsl_drawobj_sync_event;
struct event_fence_info;
struct kgsl_process_private;
struct kgsl_syncsource;

#if defined(CONFIG_SYNC_FILE)
int kgsl_add_fence_event(struct kgsl_device *device,
	u32 context_id, u32 timestamp, void __user *data, int len,
	struct kgsl_device_private *owner);

int kgsl_sync_timeline_create(struct kgsl_context *context);

void kgsl_sync_timeline_detach(struct kgsl_sync_timeline *ktimeline);

void kgsl_sync_timeline_put(struct kgsl_sync_timeline *ktimeline);

void kgsl_sync_timeline_value_str(struct dma_fence *fence, char *str, int size);

struct kgsl_sync_fence_cb *kgsl_sync_fence_async_wait(int fd, bool (*func)(void *priv), void *priv);

void kgsl_get_fence_info(struct kgsl_drawobj_sync_event *event);

void kgsl_sync_fence_async_cancel(struct kgsl_sync_fence_cb *kcb);

long kgsl_ioctl_syncsource_create(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data);
long kgsl_ioctl_syncsource_destroy(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data);
long kgsl_ioctl_syncsource_create_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data);
long kgsl_ioctl_syncsource_signal_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data);

void kgsl_syncsource_put(struct kgsl_syncsource *syncsource);

void kgsl_syncsource_process_release_syncsources(
		struct kgsl_process_private *private);

bool is_kgsl_fence(struct dma_fence *f);

void kgsl_sync_timeline_signal(struct kgsl_sync_timeline *ktimeline,
		u32 timestamp);

int kgsl_hw_fence_init(struct kgsl_device *device);

void kgsl_hw_fence_close(struct kgsl_device *device);

void kgsl_hw_fence_populate_md(struct kgsl_device *device, struct kgsl_memdesc *md);

int kgsl_hw_fence_create(struct kgsl_device *device, struct kgsl_sync_fence *kfence);

int kgsl_hw_fence_add_waiter(struct kgsl_device *device, struct dma_fence *fence, u32 *hash_index);

bool kgsl_hw_fence_tx_slot_available(struct kgsl_device *device, u32 pending_hw_fence_count);

void kgsl_hw_fence_destroy(struct kgsl_sync_fence *kfence);

void kgsl_hw_fence_trigger_cpu(struct kgsl_device *device, struct kgsl_sync_fence *kfence);

bool kgsl_hw_fence_signaled(struct dma_fence *fence);

void kgsl_get_fence_name(struct dma_fence *f, char *name, u32 max_size);

int kgsl_hw_fence_soccp_vote(bool pwr_on);

#else
static inline int kgsl_add_fence_event(struct kgsl_device *device,
	u32 context_id, u32 timestamp, void __user *data, int len,
	struct kgsl_device_private *owner)
{
	return -EINVAL;
}

static inline int kgsl_sync_timeline_create(struct kgsl_context *context)
{
	context->ktimeline = NULL;
	return 0;
}

static inline void kgsl_sync_timeline_detach(struct kgsl_sync_timeline *ktimeline)
{
}

static inline void kgsl_sync_timeline_put(struct kgsl_sync_timeline *ktimeline)
{
}


static inline void kgsl_get_fence_info(struct kgsl_drawobj_sync_event *event)
{
}

static inline struct kgsl_sync_fence_cb *kgsl_sync_fence_async_wait(int fd,
	bool (*func)(void *priv), void *priv)
{
	return NULL;
}

static inline void
kgsl_sync_fence_async_cancel(struct kgsl_sync_fence_cb *kcb)
{
}

static inline long
kgsl_ioctl_syncsource_create(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	return -ENOIOCTLCMD;
}

static inline long
kgsl_ioctl_syncsource_destroy(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	return -ENOIOCTLCMD;
}

static inline long
kgsl_ioctl_syncsource_create_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	return -ENOIOCTLCMD;
}

static inline long
kgsl_ioctl_syncsource_signal_fence(struct kgsl_device_private *dev_priv,
					unsigned int cmd, void *data)
{
	return -ENOIOCTLCMD;
}

static inline void kgsl_syncsource_put(struct kgsl_syncsource *syncsource)
{

}

static inline void kgsl_syncsource_process_release_syncsources(
		struct kgsl_process_private *private)
{

}

bool is_kgsl_fence(struct dma_fence *f)
{
	return false;
}

void kgsl_sync_timeline_signal(struct kgsl_sync_timeline *ktimeline,
		u32 timestamp)
{

}

int kgsl_hw_fence_soccp_vote(bool pwr_on)
{
	return -EINVAL;
}

int kgsl_hw_fence_init(struct kgsl_device *device)
{
	return -EINVAL;
}

void kgsl_hw_fence_close(struct kgsl_device *device)
{

}

void kgsl_hw_fence_populate_md(struct kgsl_device *device, struct kgsl_memdesc *md)
{

}

int kgsl_hw_fence_create(struct kgsl_device *device, struct kgsl_sync_fence *kfence)
{
	return -EINVAL;
}

int kgsl_hw_fence_add_waiter(struct kgsl_device *device, struct dma_fence *fence, u32 *hash_index)
{
	return -EINVAL;
}

bool kgsl_hw_fence_tx_slot_available(struct kgsl_device *device, u32 pending_hw_fence_count)
{
	return false;
}

void kgsl_hw_fence_destroy(struct kgsl_sync_fence *kfence)
{

}

void kgsl_hw_fence_trigger_cpu(struct kgsl_device *device, struct kgsl_sync_fence *kfence)
{

}

bool kgsl_hw_fence_signaled(struct dma_fence *fence)
{
	return false;
}

void kgsl_get_fence_name(struct dma_fence *f, char *name, u32 max_size)
{

}

#endif /* CONFIG_SYNC_FILE */

#endif /* __KGSL_SYNC_H */


============================================================
FILE: kgsl_sysfs.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2020, The Linux Foundation. All rights reserved.
 */
#ifndef _KGSL_SYSFS_H_
#define _KGSL_SYSFS_H_

struct kgsl_device;

/**
 * struct kgsl_gpu_sysfs_attr - Attribute definition for sysfs objects in the
 * /sys/kernel/gpu kobject
 */
struct kgsl_gpu_sysfs_attr {
	/** @attr: Attribute for the sysfs node */
	struct attribute attr;
	/** @show: Show function for the node */
	ssize_t (*show)(struct kgsl_device *device, char *buf);
	/** @store: Store function for the node */
	ssize_t (*store)(struct kgsl_device *device, const char *buf,
			size_t count);
};

#define GPU_SYSFS_ATTR(_name, _mode, _show, _store)		\
const struct kgsl_gpu_sysfs_attr gpu_sysfs_attr_##_name = {		\
	.attr = { .name = __stringify(_name), .mode = _mode },	\
	.show = _show,						\
	.store = _store,					\
}

#endif


============================================================
FILE: kgsl_timeline.c
REASON: SOURCE
============================================================
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (c) 2020-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#include <linux/dma-fence.h>
#include <linux/file.h>
#include <linux/list.h>
#include <linux/kref.h>
#include <linux/sync_file.h>
#include <linux/version.h>

#include "kgsl_device.h"
#include "kgsl_eventlog.h"
#include "kgsl_sharedmem.h"
#include "kgsl_sync.h"
#include "kgsl_timeline.h"
#include "kgsl_trace.h"

struct kgsl_timeline_fence {
	struct dma_fence base;
	struct kgsl_timeline *timeline;
	struct list_head node;
};

/*
 * kgsl_timelines_collect_fences - Collect timeline fences from userspace
 * @device: A KGSL device handle
 * @timelines: Userspace pointer to an array of &struct kgsl_timeline_val
 * @count: Number of entries in @timelines
 * @usize: Size of each entry in @timelines
 *
 * Returns an array of dma_fence pointers on success, or ERR_PTR on failure.
 */
static struct dma_fence **kgsl_timelines_collect_fences(
		struct kgsl_device *device, u64 timelines, u32 count,
		u64 usize)
{
	void __user *uptr = u64_to_user_ptr(timelines);
	struct dma_fence **fences;
	int i, ret = 0;

	if (!count || count > INT_MAX)
		return ERR_PTR(-EINVAL);

	fences = kcalloc(count, sizeof(*fences),
		GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN);

	if (!fences)
		return ERR_PTR(-ENOMEM);

	for (i = 0; i < count; i++) {
		struct kgsl_timeline_val val;
		struct kgsl_timeline *timeline;

		if (copy_struct_from_user(&val, sizeof(val), uptr, usize)) {
			ret = -EFAULT;
			goto err;
		}

		if (val.padding) {
			ret = -EINVAL;
			goto err;
		}

		timeline = kgsl_timeline_by_id(device, val.timeline);
		if (!timeline) {
			ret = -ENOENT;
			goto err;
		}

		fences[i] = kgsl_timeline_fence_alloc(timeline, val.seqno);
		kgsl_timeline_put(timeline);

		if (IS_ERR(fences[i])) {
			ret = PTR_ERR(fences[i]);
			goto err;
		}

		uptr += usize;
	}

	return fences;
err:
	for (i = 0; i < count; i++) {
		if (!IS_ERR_OR_NULL(fences[i]))
			dma_fence_put(fences[i]);
	}

	kfree(fences);
	return ERR_PTR(ret);
}

#if (KERNEL_VERSION(7, 2, 0) <= LINUX_VERSION_CODE)
static struct dma_fence_array *kgsl_dma_fence_array_create(int count,
		struct dma_fence **fences)
{
	return dma_fence_array_create(count, fences,
		dma_fence_context_alloc(1), 0);
}
#else
static struct dma_fence_array *kgsl_dma_fence_array_create(int count,
		struct dma_fence **fences)
{
	return dma_fence_array_create(count, fences,
		dma_fence_context_alloc(1), 0, false);
}
#endif

struct dma_fence *kgsl_timelines_to_fence_array(struct kgsl_device *device,
		u64 timelines, u32 count, u64 usize)
{
	struct dma_fence_array *array;
	struct dma_fence **fences;
	int i;

	fences = kgsl_timelines_collect_fences(device, timelines, count, usize);
	if (IS_ERR(fences))
		return ERR_CAST(fences);

	if (count == 1) {
		struct dma_fence *fence = fences[0];

		kfree(fences);
		return fence;
	}

	array = kgsl_dma_fence_array_create(count, fences);

	if (array)
		return &array->base;

	for (i = 0; i < count; i++)
		dma_fence_put(fences[i]);

	kfree(fences);
	return ERR_PTR(-ENOMEM);
}

void kgsl_timeline_destroy(struct kref *kref)
{
	struct kgsl_timeline *timeline = container_of(kref,
		struct kgsl_timeline, ref);

	WARN_ON(!list_empty(&timeline->fences));
	WARN_ON(!list_empty(&timeline->events));

	trace_kgsl_timeline_destroy(timeline->id);

	kfree(timeline);
}

struct kgsl_timeline *kgsl_timeline_get(struct kgsl_timeline *timeline)
{
	if (timeline) {
		if (!kref_get_unless_zero(&timeline->ref))
			return NULL;
	}

	return timeline;
}

static struct kgsl_timeline *kgsl_timeline_alloc(struct kgsl_device_private *dev_priv,
		u64 initial)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline *timeline;
	int id;

	timeline = kzalloc(sizeof(*timeline), GFP_KERNEL);
	if (!timeline)
		return ERR_PTR(-ENOMEM);

	idr_preload(GFP_KERNEL);
	spin_lock(&device->timelines_lock);
	/* Allocate the ID but don't attach the pointer just yet */
	id = idr_alloc(&device->timelines, NULL, 1, 0, GFP_NOWAIT);
	spin_unlock(&device->timelines_lock);
	idr_preload_end();

	if (id < 0) {
		kfree(timeline);
		return ERR_PTR(id);
	}

	timeline->context = dma_fence_context_alloc(1);
	timeline->id = id;
	INIT_LIST_HEAD(&timeline->fences);
	INIT_LIST_HEAD(&timeline->events);
	timeline->value = initial;
	timeline->dev_priv = dev_priv;

	snprintf((char *) timeline->name, sizeof(timeline->name),
		"kgsl-sw-timeline-%d", id);

	trace_kgsl_timeline_alloc(id, initial);

	spin_lock_init(&timeline->lock);
	spin_lock_init(&timeline->fence_lock);

	kref_init(&timeline->ref);

	return timeline;
}

static struct kgsl_timeline_fence *to_timeline_fence(struct dma_fence *fence)
{
	return container_of(fence, struct kgsl_timeline_fence, base);
}

static void timeline_fence_release(struct dma_fence *fence)
{
	struct kgsl_timeline_fence *f = to_timeline_fence(fence);
	struct kgsl_timeline *timeline = f->timeline;
	struct kgsl_timeline_fence *cur, *temp;
	unsigned long flags;

	spin_lock_irqsave(&timeline->fence_lock, flags);

	/* If the fence is still on the active list, remove it */
	list_for_each_entry_safe(cur, temp, &timeline->fences, node) {
		if (f != cur)
			continue;

		list_del_init(&f->node);
		break;
	}
	spin_unlock_irqrestore(&timeline->fence_lock, flags);
	trace_kgsl_timeline_fence_release(f->timeline->id, fence->seqno);
	log_kgsl_timeline_fence_release_event(f->timeline->id, fence->seqno);

	kgsl_timeline_put(f->timeline);
	dma_fence_free(fence);
}

#if (KERNEL_VERSION(6, 17, 0) <= LINUX_VERSION_CODE)
static bool timeline_fence_signaled(struct dma_fence *fence)
{
	struct kgsl_timeline_fence *f = to_timeline_fence(fence);

	return !__dma_fence_is_later(fence, fence->seqno, f->timeline->value);
}
#else
static bool timeline_fence_signaled(struct dma_fence *fence)
{
	struct kgsl_timeline_fence *f = to_timeline_fence(fence);

	return !__dma_fence_is_later(fence->seqno, f->timeline->value,
		fence->ops);
}
#endif

static bool timeline_fence_enable_signaling(struct dma_fence *fence)
{
	/*
	 * Return value of false indicates the fence already passed.
	 * When fence is not passed we return true indicating successful
	 * enabling.
	 */
	return !timeline_fence_signaled(fence);
}

static const char *timeline_get_driver_name(struct dma_fence *fence)
{
	return "kgsl-sw-timeline";
}

static const char *timeline_get_timeline_name(struct dma_fence *fence)
{
	struct kgsl_timeline_fence *f = to_timeline_fence(fence);

	return f->timeline->name;
}

static void timeline_get_value_str(struct dma_fence *fence,
		char *str, int size)
{
	struct kgsl_timeline_fence *f = to_timeline_fence(fence);

	snprintf(str, size, "%lld", f->timeline->value);
}

static const struct dma_fence_ops timeline_fence_ops = {
	.get_driver_name = timeline_get_driver_name,
	.get_timeline_name = timeline_get_timeline_name,
	.signaled = timeline_fence_signaled,
	.release = timeline_fence_release,
	.enable_signaling = timeline_fence_enable_signaling,

#if (KERNEL_VERSION(6, 16, 0) > LINUX_VERSION_CODE)
	.timeline_value_str = timeline_get_value_str,
#endif

#if (KERNEL_VERSION(6, 17, 0) > LINUX_VERSION_CODE)
	.use_64bit_seqno = true,
#endif

};

#if (KERNEL_VERSION(6, 16, 0) > LINUX_VERSION_CODE)
void kgsl_fence_timeline_value_str(struct dma_fence *fence, char *value, size_t size)
{
	if (!fence || !fence->ops || !value || !size)
		return;

	if (fence->ops->timeline_value_str)
		fence->ops->timeline_value_str(fence, value, size);

}
#else
void kgsl_fence_timeline_value_str(struct dma_fence *fence, char *value, size_t size)
{
	if (!fence || !fence->ops || !value || !size)
		return;

	if (fence->ops == &timeline_fence_ops)
		timeline_get_value_str(fence, value, size);
	else
		kgsl_sync_timeline_value_str(fence, value, size);
}
#endif

static void kgsl_timeline_add_fence(struct kgsl_timeline *timeline,
		struct kgsl_timeline_fence *fence)
{
	struct kgsl_timeline_fence *entry;
	unsigned long flags;

	spin_lock_irqsave(&timeline->fence_lock, flags);
	list_for_each_entry(entry, &timeline->fences, node) {
		if (fence->base.seqno < entry->base.seqno) {
			list_add_tail(&fence->node, &entry->node);
			spin_unlock_irqrestore(&timeline->fence_lock, flags);
			return;
		}
	}

	list_add_tail(&fence->node, &timeline->fences);
	spin_unlock_irqrestore(&timeline->fence_lock, flags);
}

void kgsl_timeline_add_signal(struct kgsl_timeline_event *signal)
{
	struct kgsl_timeline *timeline = signal->timeline;
	struct kgsl_timeline_event *event;
	unsigned long flags;

	spin_lock_irqsave(&timeline->lock, flags);

	/* If we already signaled this seqno don't add it to the list */
	if (timeline->value >= signal->seqno)
		goto done;

	/* Keep the list sorted by seqno */
	list_for_each_entry_reverse(event, &timeline->events, node) {
		if (event->seqno <= signal->seqno)
			break;
	}
	list_add(&signal->node, &event->node);
done:
	spin_unlock_irqrestore(&timeline->lock, flags);
}

void kgsl_timeline_signal(struct kgsl_timeline *timeline, u64 seqno)
{
	struct kgsl_timeline_fence *fence, *tmp;
	struct kgsl_timeline_event *event, *tmp_event;
	struct list_head temp;

	INIT_LIST_HEAD(&temp);

	spin_lock_irq(&timeline->lock);

	if (seqno < timeline->value)
		goto unlock;

	trace_kgsl_timeline_signal(timeline->id, seqno);

	timeline->value = seqno;
	list_for_each_entry_safe(event, tmp_event, &timeline->events, node) {
		/* List is sorted by seqno */
		if (event->seqno > seqno)
			break;

		/* Remove retired nodes */
		list_del(&event->node);
	}

	spin_lock(&timeline->fence_lock);
	list_for_each_entry_safe(fence, tmp, &timeline->fences, node)
		if (timeline_fence_signaled(&fence->base) &&
				kref_get_unless_zero(&fence->base.refcount))
			list_move(&fence->node, &temp);
	spin_unlock(&timeline->fence_lock);

	list_for_each_entry_safe(fence, tmp, &temp, node) {
		dma_fence_signal_locked(&fence->base);
		dma_fence_put(&fence->base);
	}

unlock:
	spin_unlock_irq(&timeline->lock);
}

#if KERNEL_VERSION(6, 17, 0) <= LINUX_VERSION_CODE
static inline void kgsl_timeline_dma_fence_init(struct dma_fence *fence,
		const struct dma_fence_ops *ops, spinlock_t *lock, u64 context, u64 seqno)
{
	dma_fence_init64(fence, ops, lock, context, seqno);
}
#else
static inline void kgsl_timeline_dma_fence_init(struct dma_fence *fence,
		const struct dma_fence_ops *ops, spinlock_t *lock, u64 context, u64 seqno)
{
	dma_fence_init(fence, ops, lock, context, seqno);
}
#endif

struct dma_fence *kgsl_timeline_fence_alloc(struct kgsl_timeline *timeline,
		u64 seqno)
{
	struct kgsl_timeline_fence *fence;

	fence = kzalloc(sizeof(*fence), GFP_KERNEL);
	if (!fence)
		return ERR_PTR(-ENOMEM);

	fence->timeline = kgsl_timeline_get(timeline);
	if (!fence->timeline) {
		kfree(fence);
		return ERR_PTR(-ENOENT);
	}

	kgsl_timeline_dma_fence_init(&fence->base, &timeline_fence_ops, &timeline->lock,
			timeline->context, seqno);

	INIT_LIST_HEAD(&fence->node);

	/*
	 * Once fence is checked as not signaled, allow it to be added
	 * in the list before other thread such as kgsl_timeline_signal
	 * can get chance to signal.
	 */
	spin_lock_irq(&timeline->lock);
	if (!dma_fence_is_signaled_locked(&fence->base))
		kgsl_timeline_add_fence(timeline, fence);

	trace_kgsl_timeline_fence_alloc(timeline->id, seqno);
	spin_unlock_irq(&timeline->lock);

	log_kgsl_timeline_fence_alloc_event(timeline->id, seqno);

	return &fence->base;
}

long kgsl_ioctl_timeline_create(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline_create *param = data;
	struct kgsl_timeline *timeline;

	timeline = kgsl_timeline_alloc(dev_priv, param->seqno);
	if (IS_ERR(timeline))
		return PTR_ERR(timeline);

	/* Commit the pointer to the timeline in timeline idr */
	spin_lock(&device->timelines_lock);
	idr_replace(&device->timelines, timeline, timeline->id);
	param->id = timeline->id;
	spin_unlock(&device->timelines_lock);
	return 0;
}

struct kgsl_timeline *kgsl_timeline_by_id(struct kgsl_device *device,
		u32 id)
{
	struct kgsl_timeline *timeline;
	int ret = 0;

	spin_lock(&device->timelines_lock);
	timeline = idr_find(&device->timelines, id);

	if (timeline)
		ret = kref_get_unless_zero(&timeline->ref);
	spin_unlock(&device->timelines_lock);

	return ret ? timeline : NULL;
}

long kgsl_ioctl_timeline_wait(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline_wait *param = data;
	struct dma_fence_array *array;
	struct dma_fence **fences;
	unsigned long timeout;
	signed long ret;
	int i;

	if (param->flags != KGSL_TIMELINE_WAIT_ANY &&
		param->flags != KGSL_TIMELINE_WAIT_ALL)
		return -EINVAL;

	if (param->padding)
		return -EINVAL;

	fences = kgsl_timelines_collect_fences(device, param->timelines,
		param->count, param->timelines_size);

	if (IS_ERR(fences))
		return PTR_ERR(fences);

	if (param->tv_sec >= KTIME_SEC_MAX)
		timeout = MAX_SCHEDULE_TIMEOUT;
	else {
		ktime_t time = ktime_set(param->tv_sec, param->tv_nsec);

		timeout = msecs_to_jiffies(ktime_to_ms(time));
	}

	trace_kgsl_timeline_wait(param->flags, param->tv_sec, param->tv_nsec);

	if (param->flags == KGSL_TIMELINE_WAIT_ANY) {
		ret = dma_fence_wait_any_timeout(fences, param->count,
			true, timeout, NULL);

		for (i = 0; i < param->count; i++)
			dma_fence_put(fences[i]);
		kfree(fences);
	} else {
		array = kgsl_dma_fence_array_create(param->count, fences);
		if (!array) {
			for (i = 0; i < param->count; i++)
				dma_fence_put(fences[i]);
			kfree(fences);
			return -ENOMEM;
		}

		ret = dma_fence_wait_timeout(&array->base, true, timeout);
		dma_fence_put(&array->base);
	}

	if (!ret)
		ret = (!timeout) ? -EBUSY : -ETIMEDOUT;
	else if (ret > 0)
		ret = 0;

	return ret;
}

long kgsl_ioctl_timeline_query(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_timeline_val *param = data;
	struct kgsl_timeline *timeline;
	struct kgsl_timeline_event *event;
	u64 seqno;

	if (param->padding)
		return -EINVAL;

	timeline = kgsl_timeline_by_id(dev_priv->device, param->timeline);
	if (!timeline)
		return -ENODEV;

	/*
	 * Start from the end of the list to find the last retired signal event
	 * that was not yet processed. Leave the entry in the list until the
	 * timeline signal actually advances the timeline's value. This ensures
	 * subsequent query ioctls return a monotonically increasing seqno.
	 */
	spin_lock_irq(&timeline->lock);
	seqno = timeline->value;
	list_for_each_entry_reverse(event, &timeline->events, node) {
		if (kgsl_check_timestamp(event->context->device,
			event->context, event->timestamp)) {
			seqno = event->seqno;
			break;
		}
	}
	spin_unlock_irq(&timeline->lock);

	param->seqno = seqno;
	kgsl_timeline_put(timeline);

	return 0;
}

long kgsl_ioctl_timeline_fence_get(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline_fence_get *param = data;
	struct kgsl_timeline *timeline;
	struct sync_file *sync_file;
	struct dma_fence *fence;
	int ret = 0, fd;

	timeline = kgsl_timeline_by_id(device, param->timeline);
	if (!timeline)
		return -ENODEV;

	fence = kgsl_timeline_fence_alloc(timeline, param->seqno);

	if (IS_ERR(fence)) {
		kgsl_timeline_put(timeline);
		return PTR_ERR(fence);
	}

	fd = get_unused_fd_flags(O_CLOEXEC);
	if (fd < 0) {
		ret = fd;
		goto out;
	}

	sync_file = sync_file_create(fence);
	if (sync_file) {
		fd_install(fd, sync_file->file);
		param->handle = fd;
	} else {
		put_unused_fd(fd);
		ret = -ENOMEM;
	}

out:
	dma_fence_put(fence);
	kgsl_timeline_put(timeline);

	return ret;
}

long kgsl_ioctl_timeline_signal(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline_signal *param = data;
	u64 timelines;
	int i;

	if (!param->timelines_size) {
		param->timelines_size = sizeof(struct kgsl_timeline_val);
		return -EAGAIN;
	}

	if (!param->count)
		return -EINVAL;

	timelines = param->timelines;

	for (i = 0; i < param->count; i++) {
		struct kgsl_timeline *timeline;
		struct kgsl_timeline_val val;

		if (copy_struct_from_user(&val, sizeof(val),
			u64_to_user_ptr(timelines), param->timelines_size))
			return -EFAULT;

		if (val.padding)
			return -EINVAL;

		timeline = kgsl_timeline_by_id(device, val.timeline);
		if (!timeline)
			return -ENODEV;

		kgsl_timeline_signal(timeline, val.seqno);

		kgsl_timeline_put(timeline);

		timelines += param->timelines_size;
	}

	return 0;
}

long kgsl_ioctl_timeline_destroy(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_device *device = dev_priv->device;
	struct kgsl_timeline_fence *fence, *tmp;
	struct kgsl_timeline *timeline;
	struct list_head temp;
	u32 *param = data;

	if (*param == 0)
		return -ENODEV;

	spin_lock(&device->timelines_lock);
	timeline = idr_find(&device->timelines, *param);

	if (timeline == NULL) {
		spin_unlock(&device->timelines_lock);
		return -ENODEV;
	}

	/*
	 * Validate that the id given is owned by the dev_priv
	 * instance that is passed in. If not, abort.
	 */
	if (timeline->dev_priv != dev_priv) {
		spin_unlock(&device->timelines_lock);
		return -EINVAL;
	}

	idr_remove(&device->timelines, timeline->id);
	spin_unlock(&device->timelines_lock);

	INIT_LIST_HEAD(&temp);

	spin_lock(&timeline->fence_lock);
	list_for_each_entry_safe(fence, tmp, &timeline->fences, node)
		if (!kref_get_unless_zero(&fence->base.refcount))
			list_del_init(&fence->node);
	list_replace_init(&timeline->fences, &temp);
	spin_unlock(&timeline->fence_lock);

	spin_lock_irq(&timeline->lock);
	list_for_each_entry_safe(fence, tmp, &temp, node) {
		dma_fence_set_error(&fence->base, -ENOENT);
		dma_fence_signal_locked(&fence->base);
		dma_fence_put(&fence->base);
	}
	spin_unlock_irq(&timeline->lock);

	kgsl_timeline_put(timeline);

	return 0;
}


============================================================
FILE: kgsl_timeline.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2020-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#ifndef __KGSL_TIMELINE_H
#define __KGSL_TIMELINE_H

/**
 * struct kgsl_timeline - Container for a timeline object
 */
struct kgsl_timeline {
	/** @context: dma-fence timeline context */
	u64 context;
	/** @id: Timeline identifier */
	int id;
	/** @value: Current value of the timeline */
	u64 value;
	/** @fence_lock: Lock to protect @fences */
	spinlock_t fence_lock;
	/** @lock: Lock to use for locking each fence in @fences */
	spinlock_t lock;
	/** @ref: Reference count for the struct */
	struct kref ref;
	/** @fences: sorted list of active fences */
	struct list_head fences;
	/** @events: sorted list of events to be retired */
	struct list_head events;
	/** @name: Name of the timeline for debugging */
	const char name[32];
	/** @dev_priv: pointer to the owning device instance */
	struct kgsl_device_private *dev_priv;
};

/**
 * struct kgsl_timeline_event - Contains data to signal a timeline
 */
struct kgsl_timeline_event {
	/** @timeline: Pointer to the timeline to signal */
	struct kgsl_timeline *timeline;
	/** @seqno: seqno of the timeline to signal */
	u64 seqno;
	/** @context: context this event is waiting for */
	struct kgsl_context *context;
	/** @timestamp: context timestamp this event is waiting for */
	unsigned int timestamp;
	/** @node: list node */
	struct list_head node;
};

/**
 * kgsl_fence_timeline_value_str - Get the timeline value as a string
 * @fence: Pointer to the dma_fence object
 * @value: Pointer to the character buffer to store the value string
 * @size: Size of the character buffer
 *
 * This function retrieves the timeline value from a DMA fence as a string and
 * copies at most @size characters into @value.
 * It delegates to the appropriate timeline_value_str implementation based on
 * the fence operations.
 *
 * If either the fence, fence operations, or value pointer is NULL, the function
 * returns without doing anything.
 */
void kgsl_fence_timeline_value_str(struct dma_fence *fence, char *value,
	size_t size);

/**
 * kgsl_timeline_add_signal - Notify a timeline of an upcoming signal
 * @signal: Pointer to a kgsl_timeline_event
 *
 * Notify the timeline that a GPU AUX command is expected to signal.
 */
void kgsl_timeline_add_signal(struct kgsl_timeline_event *signal);

/**
 * kgsl_timeline_signal - Signal the timeline
 * @timeline: Pointer to a timeline container
 * @seqno: Seqeuence number to signal
 *
 * Advance @timeline to sequence number @seqno and signal any fences that might
 * have expired.
 */
void kgsl_timeline_signal(struct kgsl_timeline *timeline, u64 seqno);

/**
 * kgsl_timeline_destroy - Timeline destroy callback
 * @kref: Refcount pointer for the timeline
 *
 * Reference count callback for the timeline called when the all the object
 * references have been released.
 */
void kgsl_timeline_destroy(struct kref *kref);

/**
 * kgsl_timeline_fence_alloc - Allocate a new fence on a timeline
 * @timeline: Pointer to a timeline container
 * @seqno: Sequence number for the new fence to wait for
 *
 * Create and return a new fence on the timeline that will expire when the
 * timeline value is greater or equal to @seqno.
 * Return: A pointer to the newly created fence
 */
struct dma_fence *kgsl_timeline_fence_alloc(struct kgsl_timeline *timeline,
		u64 seqno);

/**
 * kgsl_timeline_by_id - Look up a timeline by an id
 * @device: A KGSL device handle
 * @id: Lookup identifier
 *
 * Find and return the timeline associated with identifer @id.
 * Return: A pointer to a timeline or PTR_ERR() encoded error on failure.
 */
struct kgsl_timeline *kgsl_timeline_by_id(struct kgsl_device *device,
		u32 id);

/**
 * kgsl_timeline_get - Get a reference to an existing timeline
 * @timeline: Pointer to a timeline container
 *
 * Get a new reference to the timeline and return the pointer back to the user.
 * Return: The pointer to the timeline or PTR_ERR encoded error on failure
 */
struct kgsl_timeline *kgsl_timeline_get(struct kgsl_timeline *timeline);

/**
 * kgsl_timeline_put - Release a reference to a timeline
 * @timeline: Pointer to a timeline container
 *
 * Release a reference to a timeline and destroy it if there are no other
 * references
 */
static inline void kgsl_timeline_put(struct kgsl_timeline *timeline)
{
	if (!IS_ERR_OR_NULL(timeline))
		kref_put(&timeline->ref, kgsl_timeline_destroy);
}

/**
 * kgsl_timelines_to_fence_array - Return a dma-fence array of timeline fences
 * @device: A KGSL device handle
 * @timelines: Userspace pointer to an array of &struct kgsl_timeline_val
 * @count: Number of entries in @timelines
 * @usize: Size of each entry in @timelines
 *
 * Given a list of &struct kgsl_timeline_val entries, create a dma-fence-array
 * containing fences for each timeline/seqno pair. The fence will wait for ALL
 * of the encapsulated timeline fences to expire.
 */
struct dma_fence *kgsl_timelines_to_fence_array(struct kgsl_device *device,
		u64 timelines, u32 count, u64 usize);

#endif


============================================================
FILE: kgsl_trace.c
REASON: SOURCE
============================================================
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (c) 2011,2013,2015,2019 The Linux Foundation. All rights reserved.
 */

#include <linux/module.h>

#include "kgsl_device.h"

/* Instantiate tracepoints */
#define CREATE_TRACE_POINTS
#include "kgsl_trace.h"


============================================================
FILE: kgsl_trace.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2011-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#if !defined(_KGSL_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
#define _KGSL_TRACE_H

#undef TRACE_SYSTEM
#define TRACE_SYSTEM kgsl
#undef TRACE_INCLUDE_PATH
#define TRACE_INCLUDE_PATH .
#undef TRACE_INCLUDE_FILE
#define TRACE_INCLUDE_FILE kgsl_trace

#include <linux/tracepoint.h>

#include "kgsl.h"
#include "kgsl_drawobj.h"
#include "kgsl_sharedmem.h"

#if (KERNEL_VERSION(6, 10, 0) > LINUX_VERSION_CODE)
#define kgsl_assign_str(dst, src) __assign_str(dst, src)
#else
#define kgsl_assign_str(dst, src) __assign_str(dst)
#endif

#define KGSL_TRACE_GPU_FREQ(freq, gpu_id, ticks) \
	do { \
		trace_gpu_frequency(freq, gpu_id); \
		trace_kgsl_gpu_frequency(freq, gpu_id, ticks); \
	} while (0)

#define show_memtype(type) \
	__print_symbolic(type, \
		{ KGSL_MEM_ENTRY_KERNEL, "gpumem" }, \
		{ KGSL_MEM_ENTRY_USER, "usermem" }, \
		{ KGSL_MEM_ENTRY_ION, "ion" })

#define show_constraint(type) \
	__print_symbolic(type, \
		{ KGSL_CONSTRAINT_NONE, "None" }, \
		{ KGSL_CONSTRAINT_PWRLEVEL, "Pwrlevel" }, \
		{ KGSL_CONSTRAINT_L3_NONE, "L3_none" }, \
		{ KGSL_CONSTRAINT_L3_PWRLEVEL, "L3_pwrlevel" })

struct kgsl_ringbuffer_issueibcmds;
struct kgsl_device_waittimestamp;

/*
 * Tracepoint for kgsl issue ib commands
 */
TRACE_EVENT(kgsl_issueibcmds,

	TP_PROTO(struct kgsl_device *device,
			int drawctxt_id,
			unsigned int numibs,
			int timestamp,
			int flags,
			int result,
			unsigned int type),

	TP_ARGS(device, drawctxt_id, numibs, timestamp,
		flags, result, type),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, drawctxt_id)
		__field(unsigned int, numibs)
		__field(unsigned int, timestamp)
		__field(unsigned int, flags)
		__field(int, result)
		__field(unsigned int, drawctxt_type)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->drawctxt_id = drawctxt_id;
		__entry->numibs = numibs;
		__entry->timestamp = timestamp;
		__entry->flags = flags;
		__entry->result = result;
		__entry->drawctxt_type = type;
	),

	TP_printk(
		"d_name=%s ctx=%u ib=0x0 numibs=%u ts=%u flags=%s result=%d type=%s",
		__get_str(device_name),
		__entry->drawctxt_id,
		__entry->numibs,
		__entry->timestamp,
		__entry->flags ? __print_flags(__entry->flags, "|",
						KGSL_DRAWOBJ_FLAGS) : "None",
		__entry->result,
		kgsl_context_type(__entry->drawctxt_type)
	)
);

/*
 * Tracepoint for kgsl readtimestamp
 */
TRACE_EVENT(kgsl_readtimestamp,

	TP_PROTO(struct kgsl_device *device,
			unsigned int context_id,
			unsigned int type,
			unsigned int timestamp),

	TP_ARGS(device, context_id, type, timestamp),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, context_id)
		__field(unsigned int, type)
		__field(unsigned int, timestamp)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->context_id = context_id;
		__entry->type = type;
		__entry->timestamp = timestamp;
	),

	TP_printk(
		"d_name=%s context_id=%u type=%u ts=%u",
		__get_str(device_name),
		__entry->context_id,
		__entry->type,
		__entry->timestamp
	)
);

/*
 * Tracepoint for kgsl waittimestamp entry
 */
TRACE_EVENT(kgsl_waittimestamp_entry,

	TP_PROTO(struct kgsl_device *device,
			unsigned int context_id,
			unsigned int curr_ts,
			unsigned int wait_ts,
			unsigned int timeout),

	TP_ARGS(device, context_id, curr_ts, wait_ts, timeout),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, context_id)
		__field(unsigned int, curr_ts)
		__field(unsigned int, wait_ts)
		__field(unsigned int, timeout)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->context_id = context_id;
		__entry->curr_ts = curr_ts;
		__entry->wait_ts = wait_ts;
		__entry->timeout = timeout;
	),

	TP_printk(
		"d_name=%s ctx=%u curr_ts=%u ts=%u timeout=%u",
		__get_str(device_name),
		__entry->context_id,
		__entry->curr_ts,
		__entry->wait_ts,
		__entry->timeout
	)
);

/*
 * Tracepoint for kgsl waittimestamp exit
 */
TRACE_EVENT(kgsl_waittimestamp_exit,

	TP_PROTO(struct kgsl_device *device, unsigned int curr_ts,
		 int result),

	TP_ARGS(device, curr_ts, result),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, curr_ts)
		__field(int, result)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->curr_ts = curr_ts;
		__entry->result = result;
	),

	TP_printk(
		"d_name=%s curr_ts=%u result=%d",
		__get_str(device_name),
		__entry->curr_ts,
		__entry->result
	)
);

DECLARE_EVENT_CLASS(kgsl_pwr_template,
	TP_PROTO(struct kgsl_device *device, bool on),

	TP_ARGS(device, on),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(bool, on)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->on = on;
	),

	TP_printk(
		"d_name=%s flag=%s",
		__get_str(device_name),
		__entry->on ? "on" : "off"
	)
);

DEFINE_EVENT(kgsl_pwr_template, kgsl_irq,
	TP_PROTO(struct kgsl_device *device, bool on),
	TP_ARGS(device, on)
);

DEFINE_EVENT(kgsl_pwr_template, kgsl_bus,
	TP_PROTO(struct kgsl_device *device, bool on),
	TP_ARGS(device, on)
);

DEFINE_EVENT(kgsl_pwr_template, kgsl_rail,
	TP_PROTO(struct kgsl_device *device, bool on),
	TP_ARGS(device, on)
);

TRACE_EVENT(kgsl_clk,

	TP_PROTO(struct kgsl_device *device, bool on,
		unsigned int freq),

	TP_ARGS(device, on, freq),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(bool, on)
		__field(unsigned int, freq)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->on = on;
		__entry->freq = freq;
	),

	TP_printk(
		"d_name=%s flag=%s active_freq=%d",
		__get_str(device_name),
		__entry->on ? "on" : "off",
		__entry->freq
	)
);

TRACE_EVENT(kgsl_gmu_pwrlevel,

	TP_PROTO(unsigned long freq,
		unsigned long prev_freq),

	TP_ARGS(freq, prev_freq),

	TP_STRUCT__entry(
		__field(unsigned long, freq)
		__field(unsigned long, prev_freq)
	),

	TP_fast_assign(
		__entry->freq = freq;
		__entry->prev_freq = prev_freq;
	),

	TP_printk(
		"gmu_freq=%ld gmu_prev_freq=%ld",
		__entry->freq,
		__entry->prev_freq
	)
);

TRACE_EVENT(kgsl_pwrlevel,

	TP_PROTO(struct kgsl_device *device,
		unsigned int pwrlevel,
		unsigned int freq,
		unsigned int prev_pwrlevel,
		unsigned int prev_freq,
		u64 ticks),

	TP_ARGS(device, pwrlevel, freq, prev_pwrlevel, prev_freq, ticks),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, pwrlevel)
		__field(unsigned int, freq)
		__field(unsigned int, prev_pwrlevel)
		__field(unsigned int, prev_freq)
		__field(u64, ticks)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->pwrlevel = pwrlevel;
		__entry->freq = freq;
		__entry->prev_pwrlevel = prev_pwrlevel;
		__entry->prev_freq = prev_freq;
		__entry->ticks = ticks;
	),

	TP_printk(
		"d_name=%s pwrlevel=%d freq=%d prev_pwrlevel=%d prev_freq=%d ticks=%llu",
		__get_str(device_name),
		__entry->pwrlevel,
		__entry->freq,
		__entry->prev_pwrlevel,
		__entry->prev_freq,
		__entry->ticks
	)
);

/*
 * Tracepoint for kgsl gpu_frequency
 */
TRACE_EVENT(kgsl_gpu_frequency,
	TP_PROTO(unsigned int gpu_freq, unsigned int gpu_id, u64 ticks),
	TP_ARGS(gpu_freq, gpu_id, ticks),
	TP_STRUCT__entry(
		__field(unsigned int, gpu_freq)
		__field(unsigned int, gpu_id)
		__field(u64, ticks)
	),
	TP_fast_assign(
		__entry->gpu_freq = gpu_freq;
		__entry->gpu_id = gpu_id;
		__entry->ticks = ticks;
	),

	TP_printk("gpu_freq=%luKhz gpu_id=%lu ticks=%llu",
		(unsigned long)__entry->gpu_freq,
		(unsigned long)__entry->gpu_id,
		__entry->ticks)
);

TRACE_EVENT(kgsl_buslevel,

	TP_PROTO(struct kgsl_device *device, u32 pwrlevel,
		 u32 bus, u32 avg_bw, u64 ticks),

	TP_ARGS(device, pwrlevel, bus, avg_bw, ticks),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(u32, pwrlevel)
		__field(u32, bus)
		__field(u32, avg_bw)
		__field(u64, ticks)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->pwrlevel = pwrlevel;
		__entry->bus = bus;
		__entry->avg_bw = avg_bw;
		__entry->ticks = ticks;
	),

	TP_printk(
		"d_name=%s pwrlevel=%u bus=%u avg_bw=%u ticks=%llu",
		__get_str(device_name),
		__entry->pwrlevel,
		__entry->bus,
		__entry->avg_bw,
		__entry->ticks
	)
);

TRACE_EVENT(kgsl_gpubusy,
	TP_PROTO(struct kgsl_device *device, unsigned int busy,
		unsigned int elapsed, u64 ticks),

	TP_ARGS(device, busy, elapsed, ticks),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, busy)
		__field(unsigned int, elapsed)
		__field(u64, ticks)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->busy = busy;
		__entry->elapsed = elapsed;
		__entry->ticks = ticks;
	),

	TP_printk(
		"d_name=%s busy=%u elapsed=%d ticks=%llu",
		__get_str(device_name),
		__entry->busy,
		__entry->elapsed,
		__entry->ticks
	)
);

TRACE_EVENT(kgsl_pwrstats,
	TP_PROTO(struct kgsl_device *device, s64 time,
		struct kgsl_power_stats *pstats, u32 ctxt_count, u64 ticks),

	TP_ARGS(device, time, pstats, ctxt_count, ticks),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(s64, total_time)
		__field(u64, busy_time)
		__field(u64, ram_time)
		__field(u64, ram_wait)
		__field(u32, context_count)
		__field(u64, ticks)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->total_time = time;
		__entry->busy_time = pstats->busy_time;
		__entry->ram_time = pstats->ram_time;
		__entry->ram_wait = pstats->ram_wait;
		__entry->context_count = ctxt_count;
		__entry->ticks = ticks;
	),

	TP_printk(
		"d_name=%s total=%lld busy=%lld ram_time=%lld ram_wait=%lld context_count=%u ticks=%llu",
		__get_str(device_name), __entry->total_time, __entry->busy_time,
		__entry->ram_time, __entry->ram_wait, __entry->context_count,
		__entry->ticks
	)
);

DECLARE_EVENT_CLASS(kgsl_pwrstate_template,
	TP_PROTO(struct kgsl_device *device, unsigned int state),

	TP_ARGS(device, state),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, state)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->state = state;
	),

	TP_printk(
		"d_name=%s state=%s",
		__get_str(device_name),
		kgsl_pwrstate_to_str(__entry->state)
	)
);

DEFINE_EVENT(kgsl_pwrstate_template, kgsl_pwr_set_state,
	TP_PROTO(struct kgsl_device *device, unsigned int state),
	TP_ARGS(device, state)
);

DEFINE_EVENT(kgsl_pwrstate_template, kgsl_pwr_request_state,
	TP_PROTO(struct kgsl_device *device, unsigned int state),
	TP_ARGS(device, state)
);

TRACE_EVENT(kgsl_mem_alloc,

	TP_PROTO(struct kgsl_mem_entry *mem_entry),

	TP_ARGS(mem_entry),

	TP_STRUCT__entry(
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__field(unsigned int, tgid)
		__array(char, usage, 16)
		__field(unsigned int, id)
		__field(uint64_t, flags)
	),

	TP_fast_assign(
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		__entry->tgid = pid_nr(mem_entry->priv->pid);
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->id = mem_entry->id;
		__entry->flags = mem_entry->memdesc.flags;
	),

	TP_printk(
		"gpuaddr=0x%llx size=%llu tgid=%u usage=%s id=%u flags=0x%llx",
		__entry->gpuaddr, __entry->size, __entry->tgid,
		__entry->usage, __entry->id, __entry->flags
	)
);

TRACE_EVENT(kgsl_mem_mmap,

	TP_PROTO(struct kgsl_mem_entry *mem_entry, unsigned long useraddr),

	TP_ARGS(mem_entry, useraddr),

	TP_STRUCT__entry(
		__field(unsigned long, useraddr)
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__array(char, usage, 16)
		__field(unsigned int, id)
		__field(uint64_t, flags)
	),

	TP_fast_assign(
		__entry->useraddr = useraddr;
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->id = mem_entry->id;
		__entry->flags = mem_entry->memdesc.flags;
	),

	TP_printk(
	 "useraddr=0x%lx gpuaddr=0x%llx size=%llu usage=%s id=%u flags=0x%llx",
		__entry->useraddr, __entry->gpuaddr, __entry->size,
		__entry->usage, __entry->id, __entry->flags
	)
);

TRACE_EVENT(kgsl_mem_unmapped_area_collision,

	TP_PROTO(struct kgsl_mem_entry *mem_entry,
		 unsigned long addr,
		 unsigned long len),

	TP_ARGS(mem_entry, addr, len),

	TP_STRUCT__entry(
		__field(unsigned int, id)
		__field(unsigned long, addr)
		__field(unsigned long, len)
	),

	TP_fast_assign(
		__entry->id = mem_entry->id;
		__entry->len = len;
		__entry->addr = addr;
	),

	TP_printk(
		"id=%u len=%lu addr=0x%lx",
		__entry->id, __entry->len, __entry->addr
	)
);

TRACE_EVENT(kgsl_mem_map,

	TP_PROTO(struct kgsl_mem_entry *mem_entry, int fd),

	TP_ARGS(mem_entry, fd),

	TP_STRUCT__entry(
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__field(int, fd)
		__field(int, type)
		__field(unsigned int, tgid)
		__array(char, usage, 16)
		__field(unsigned int, id)
	),

	TP_fast_assign(
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		__entry->fd = fd;
		__entry->type = kgsl_memdesc_usermem_type(&mem_entry->memdesc);
		__entry->tgid = pid_nr(mem_entry->priv->pid);
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->id = mem_entry->id;
	),

	TP_printk(
		"gpuaddr=0x%llx size=%llu type=%s fd=%d tgid=%u usage=%s id=%u",
		__entry->gpuaddr, __entry->size,
		show_memtype(__entry->type),
		__entry->fd, __entry->tgid,
		__entry->usage, __entry->id
	)
);

TRACE_EVENT(kgsl_mem_free,

	TP_PROTO(struct kgsl_mem_entry *mem_entry),

	TP_ARGS(mem_entry),

	TP_STRUCT__entry(
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__field(int, type)
		__field(int, fd)
		__field(unsigned int, tgid)
		__array(char, usage, 16)
		__field(unsigned int, id)
	),

	TP_fast_assign(
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		__entry->type = kgsl_memdesc_usermem_type(&mem_entry->memdesc);
		__entry->tgid = pid_nr(mem_entry->priv->pid);
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->id = mem_entry->id;
	),

	TP_printk(
		"gpuaddr=0x%llx size=%llu type=%s tgid=%u usage=%s id=%u",
		__entry->gpuaddr, __entry->size,
		show_memtype(__entry->type),
		__entry->tgid, __entry->usage, __entry->id
	)
);

TRACE_EVENT(kgsl_mem_sync_cache,

	TP_PROTO(struct kgsl_mem_entry *mem_entry, uint64_t offset,
		uint64_t length, unsigned int op),

	TP_ARGS(mem_entry, offset, length, op),

	TP_STRUCT__entry(
		__field(uint64_t, gpuaddr)
		__array(char, usage, 16)
		__field(unsigned int, tgid)
		__field(unsigned int, id)
		__field(unsigned int, op)
		__field(uint64_t, offset)
		__field(uint64_t, length)
	),

	TP_fast_assign(
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->tgid = pid_nr(mem_entry->priv->pid);
		__entry->id = mem_entry->id;
		__entry->op = op;
		__entry->offset = offset;
		__entry->length = (length == 0) ?
				mem_entry->memdesc.size : length;
	),

	TP_printk(
	 "gpuaddr=0x%llx size=%llu tgid=%u  usage=%s id=%u op=%c%c offset=%llu",
		__entry->gpuaddr,  __entry->length,
		__entry->tgid, __entry->usage, __entry->id,
		(__entry->op & KGSL_GPUMEM_CACHE_CLEAN) ? 'c' : '.',
		(__entry->op & KGSL_GPUMEM_CACHE_INV) ? 'i' : '.',
		__entry->offset
	)
);

TRACE_EVENT(kgsl_mem_add_bind_range,
	TP_PROTO(struct kgsl_mem_entry *target, u64 offset,
		 struct kgsl_mem_entry *child, u64 length),

	TP_ARGS(target, offset, child, length),

	TP_STRUCT__entry(
		__field(u64, gpuaddr)
		__field(u32, target)
		__field(u32, tgid)
		__field(u32, child)
		__field(u64, length)
	),

	TP_fast_assign(
		__entry->gpuaddr = target->memdesc.gpuaddr + offset;
		__entry->tgid = pid_nr(target->priv->pid);
		__entry->target = target->id;
		__entry->child = child->id;
		__entry->length = length;
	),

	TP_printk(
	"tgid=%u target=%d gpuaddr=%llx length %llu child=%d",
		__entry->tgid, __entry->target, __entry->gpuaddr,
		__entry->length, __entry->child
	)
);

TRACE_EVENT(kgsl_mem_remove_bind_range,
	TP_PROTO(struct kgsl_mem_entry *target, u64 offset,
		 struct kgsl_mem_entry *child, u64 length),

	TP_ARGS(target, offset, child, length),

	TP_STRUCT__entry(
		__field(u64, gpuaddr)
		__field(u32, target)
		__field(u32, tgid)
		__field(u32, child)
		__field(u64, length)
	),

	TP_fast_assign(
		__entry->gpuaddr = target->memdesc.gpuaddr + offset;
		__entry->tgid = pid_nr(target->priv->pid);
		__entry->target = target->id;
		__entry->child = child->id;
		__entry->length = length;
	),

	TP_printk(
	"tgid=%u target=%d gpuaddr=%llx length %llu child=%d",
		__entry->tgid, __entry->target, __entry->gpuaddr,
		__entry->length, __entry->child
	)
);

TRACE_EVENT(kgsl_mem_sync_full_cache,

	TP_PROTO(unsigned int num_bufs, uint64_t bulk_size),
	TP_ARGS(num_bufs, bulk_size),

	TP_STRUCT__entry(
		__field(unsigned int, num_bufs)
		__field(uint64_t, bulk_size)
	),

	TP_fast_assign(
		__entry->num_bufs = num_bufs;
		__entry->bulk_size = bulk_size;
	),

	TP_printk(
		"num_bufs=%u bulk_size=%llu op=ci",
		__entry->num_bufs, __entry->bulk_size
	)
);

DECLARE_EVENT_CLASS(kgsl_mem_timestamp_template,

	TP_PROTO(struct kgsl_device *device, struct kgsl_mem_entry *mem_entry,
		unsigned int id, unsigned int curr_ts, unsigned int free_ts),

	TP_ARGS(device, mem_entry, id, curr_ts, free_ts),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__field(int, type)
		__array(char, usage, 16)
		__field(unsigned int, id)
		__field(unsigned int, drawctxt_id)
		__field(unsigned int, curr_ts)
		__field(unsigned int, free_ts)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		kgsl_get_memory_usage(__entry->usage, sizeof(__entry->usage),
				     mem_entry->memdesc.flags);
		__entry->id = mem_entry->id;
		__entry->drawctxt_id = id;
		__entry->type = kgsl_memdesc_usermem_type(&mem_entry->memdesc);
		__entry->curr_ts = curr_ts;
		__entry->free_ts = free_ts;
	),

	TP_printk(
		"d_name=%s gpuaddr=0x%llx size=%llu type=%s usage=%s id=%u ctx=%u curr_ts=%u free_ts=%u",
		__get_str(device_name),
		__entry->gpuaddr,
		__entry->size,
		show_memtype(__entry->type),
		__entry->usage,
		__entry->id,
		__entry->drawctxt_id,
		__entry->curr_ts,
		__entry->free_ts
	)
);

DEFINE_EVENT(kgsl_mem_timestamp_template, kgsl_mem_timestamp_queue,
	TP_PROTO(struct kgsl_device *device, struct kgsl_mem_entry *mem_entry,
		unsigned int id, unsigned int curr_ts, unsigned int free_ts),
	TP_ARGS(device, mem_entry, id, curr_ts, free_ts)
);

DEFINE_EVENT(kgsl_mem_timestamp_template, kgsl_mem_timestamp_free,
	TP_PROTO(struct kgsl_device *device, struct kgsl_mem_entry *mem_entry,
		unsigned int id, unsigned int curr_ts, unsigned int free_ts),
	TP_ARGS(device, mem_entry, id, curr_ts, free_ts)
);

TRACE_EVENT(kgsl_context_create,

	TP_PROTO(struct kgsl_device *device, struct kgsl_context *context,
		 unsigned int flags),

	TP_ARGS(device, context, flags),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, id)
		__field(unsigned int, flags)
		__field(unsigned int, priority)
		__field(unsigned int, type)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->id = context->id;
		__entry->flags = flags & ~(KGSL_CONTEXT_PRIORITY_MASK |
						KGSL_CONTEXT_TYPE_MASK);
		__entry->priority =
			(flags & KGSL_CONTEXT_PRIORITY_MASK)
				>> KGSL_CONTEXT_PRIORITY_SHIFT;
		__entry->type =
			(flags & KGSL_CONTEXT_TYPE_MASK)
				>> KGSL_CONTEXT_TYPE_SHIFT;
	),

	TP_printk(
		"d_name=%s ctx=%u flags=%s priority=%u type=%s",
		__get_str(device_name), __entry->id,
		__entry->flags ? __print_flags(__entry->flags, "|",
						KGSL_CONTEXT_FLAGS) : "None",
		__entry->priority,
		kgsl_context_type(__entry->type)
	)
);

TRACE_EVENT(kgsl_context_detach,

	TP_PROTO(struct kgsl_device *device, struct kgsl_context *context),

	TP_ARGS(device, context),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, id)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->id = context->id;
	),

	TP_printk(
		"d_name=%s ctx=%u",
		__get_str(device_name), __entry->id
	)
);

TRACE_EVENT(kgsl_context_destroy,

	TP_PROTO(struct kgsl_device *device, struct kgsl_context *context),

	TP_ARGS(device, context),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, id)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->id = context->id;
	),

	TP_printk(
		"d_name=%s ctx=%u",
		__get_str(device_name), __entry->id
	)
);

TRACE_EVENT(kgsl_user_pwrlevel_constraint,

	TP_PROTO(struct kgsl_device *device, unsigned int id, unsigned int type,
		unsigned int sub_type),

	TP_ARGS(device, id, type, sub_type),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, id)
		__field(unsigned int, type)
		__field(unsigned int, sub_type)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->id = id;
		__entry->type = type;
		__entry->sub_type = sub_type;
	),

	TP_printk(
		"d_name=%s ctx=%u constraint_type=%s constraint_subtype=%s",
		__get_str(device_name), __entry->id,
		show_constraint(__entry->type),
		__print_symbolic(__entry->sub_type,
			{ KGSL_CONSTRAINT_PWR_MIN, "Min" },
			{ KGSL_CONSTRAINT_PWR_MAX, "Max" })
	)
);

TRACE_EVENT(kgsl_constraint,

	TP_PROTO(struct kgsl_device *device, unsigned int type,
		unsigned int value, unsigned int on, u64 ticks),

	TP_ARGS(device, type, value, on, ticks),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, type)
		__field(unsigned int, value)
		__field(unsigned int, on)
		__field(u64, ticks)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->type = type;
		__entry->value = value;
		__entry->on = on;
		__entry->ticks = ticks;
	),

	TP_printk(
		"d_name=%s constraint_type=%s constraint_value=%u status=%s ticks=%llu",
		__get_str(device_name),
		show_constraint(__entry->type),
		__entry->value,
		__entry->on ? "ON" : "OFF",
		__entry->ticks
	)
);

TRACE_EVENT(kgsl_mmu_pagefault,

	TP_PROTO(struct kgsl_device *device, unsigned long page,
		 unsigned int pt, const char *name, const char *op),

	TP_ARGS(device, page, pt, name, op),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned long, page)
		__field(unsigned int, pt)
		__string(name, name)
		__string(op, op)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->page = page;
		__entry->pt = pt;
		kgsl_assign_str(name, name);
		kgsl_assign_str(op, op);
	),

	TP_printk(
		"d_name=%s page=0x%lx pt=%u op=%s name=%s",
		__get_str(device_name), __entry->page, __entry->pt,
		__get_str(op), __get_str(name)
	)
);

TRACE_EVENT(kgsl_regwrite,

	TP_PROTO(unsigned int offset, unsigned int value),

	TP_ARGS(offset, value),

	TP_STRUCT__entry(
		__string(device_name, "kgsl-3d0")
		__field(unsigned int, offset)
		__field(unsigned int, value)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, "kgsl-3d0");
		__entry->offset = offset;
		__entry->value = value;
	),

	TP_printk(
		"d_name=%s reg=0x%x value=0x%x",
		__get_str(device_name), __entry->offset, __entry->value
	)
);

TRACE_EVENT(kgsl_register_event,
		TP_PROTO(unsigned int id, unsigned int timestamp, void *func),
		TP_ARGS(id, timestamp, func),
		TP_STRUCT__entry(
			__field(unsigned int, id)
			__field(unsigned int, timestamp)
			__field(void *, func)
		),
		TP_fast_assign(
			__entry->id = id;
			__entry->timestamp = timestamp;
			__entry->func = func;
		),
		TP_printk(
			"ctx=%u ts=%u cb=%pS",
			__entry->id, __entry->timestamp, __entry->func)
);

TRACE_EVENT(kgsl_fire_event,
		TP_PROTO(unsigned int id, unsigned int ts,
			unsigned int type, unsigned int age, void *func),
		TP_ARGS(id, ts, type, age, func),
		TP_STRUCT__entry(
			__field(unsigned int, id)
			__field(unsigned int, ts)
			__field(unsigned int, type)
			__field(unsigned int, age)
			__field(void *, func)
		),
		TP_fast_assign(
			__entry->id = id;
			__entry->ts = ts;
			__entry->type = type;
			__entry->age = age;
			__entry->func = func;
		),
		TP_printk(
			"ctx=%u ts=%u type=%s age=%u cb=%pS",
			__entry->id, __entry->ts,
			__print_symbolic(__entry->type,
				{ KGSL_EVENT_RETIRED, "retired" },
				{ KGSL_EVENT_CANCELLED, "cancelled" }),
			__entry->age, __entry->func)
);

TRACE_EVENT(kgsl_active_count,

	TP_PROTO(struct kgsl_device *device, unsigned long ip),

	TP_ARGS(device, ip),

	TP_STRUCT__entry(
		__string(device_name, device->name)
		__field(unsigned int, count)
		__field(unsigned long, ip)
	),

	TP_fast_assign(
		kgsl_assign_str(device_name, device->name);
		__entry->count = atomic_read(&device->active_cnt);
		__entry->ip = ip;
	),

	TP_printk(
		"d_name=%s active_cnt=%u func=%ps",
		__get_str(device_name), __entry->count, (void *) __entry->ip
	)
);

TRACE_EVENT(kgsl_pagetable_destroy,
	TP_PROTO(u64 ptbase, unsigned int name),
	TP_ARGS(ptbase, name),
	TP_STRUCT__entry(
		__field(u64, ptbase)
		__field(unsigned int, name)
	),
	TP_fast_assign(
		__entry->ptbase = ptbase;
		__entry->name = name;
	),
	TP_printk("ptbase=%llx name=%u", __entry->ptbase, __entry->name)
);

DECLARE_EVENT_CLASS(syncpoint_timestamp_template,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj,
		struct kgsl_context *context,
		unsigned int timestamp),
	TP_ARGS(syncobj, context, timestamp),
	TP_STRUCT__entry(
		__field(unsigned int, syncobj_context_id)
		__field(unsigned int, context_id)
		__field(unsigned int, timestamp)
	),
	TP_fast_assign(
		__entry->syncobj_context_id = syncobj->base.context->id;
		__entry->context_id = context->id;
		__entry->timestamp = timestamp;
	),
	TP_printk("ctx=%u sync ctx=%u ts=%u",
		__entry->syncobj_context_id, __entry->context_id,
		__entry->timestamp)
);

DEFINE_EVENT(syncpoint_timestamp_template, syncpoint_timestamp,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj,
		struct kgsl_context *context,
		unsigned int timestamp),
	TP_ARGS(syncobj, context, timestamp)
);

DEFINE_EVENT(syncpoint_timestamp_template, syncpoint_timestamp_expire,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj,
		struct kgsl_context *context,
		unsigned int timestamp),
	TP_ARGS(syncobj, context, timestamp)
);

DECLARE_EVENT_CLASS(syncpoint_fence_template,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj, char *name),
	TP_ARGS(syncobj, name),
	TP_STRUCT__entry(
		__string(fence_name, name)
		__field(unsigned int, syncobj_context_id)
	),
	TP_fast_assign(
		__entry->syncobj_context_id = syncobj->base.context->id;
		kgsl_assign_str(fence_name, name);
	),
	TP_printk("ctx=%u fence=%s",
		__entry->syncobj_context_id, __get_str(fence_name))
);

DEFINE_EVENT(syncpoint_fence_template, syncpoint_fence,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj, char *name),
	TP_ARGS(syncobj, name)
);

DEFINE_EVENT(syncpoint_fence_template, syncpoint_fence_expire,
	TP_PROTO(struct kgsl_drawobj_sync *syncobj, char *name),
	TP_ARGS(syncobj, name)
);

TRACE_EVENT(kgsl_msg,
	TP_PROTO(const char *msg),
	TP_ARGS(msg),
	TP_STRUCT__entry(
		__string(msg, msg)
	),
	TP_fast_assign(
		kgsl_assign_str(msg, msg);
	),
	TP_printk(
		"%s", __get_str(msg)
	)
);

TRACE_EVENT(kgsl_clock_throttling,
	TP_PROTO(
		int idle_10pct,
		int crc_50pct,
		int crc_more50pct,
		int crc_less50pct,
		int64_t adj
	),
	TP_ARGS(
		idle_10pct,
		crc_50pct,
		crc_more50pct,
		crc_less50pct,
		adj
	),
	TP_STRUCT__entry(
		__field(int, idle_10pct)
		__field(int, crc_50pct)
		__field(int, crc_more50pct)
		__field(int, crc_less50pct)
		__field(int64_t, adj)
	),
	TP_fast_assign(
		__entry->idle_10pct = idle_10pct;
		__entry->crc_50pct = crc_50pct;
		__entry->crc_more50pct = crc_more50pct;
		__entry->crc_less50pct = crc_less50pct;
		__entry->adj = adj;
	),
	TP_printk("idle_10=%d crc_50=%d crc_more50=%d crc_less50=%d adj=%lld",
		__entry->idle_10pct, __entry->crc_50pct, __entry->crc_more50pct,
		__entry->crc_less50pct, __entry->adj
	)
);

TRACE_EVENT(kgsl_bcl_clock_throttling,
	TP_PROTO(
		int crc_25pct,
		int crc_58pct,
		int crc_75pct
	),
	TP_ARGS(
		crc_25pct,
		crc_58pct,
		crc_75pct
	),
	TP_STRUCT__entry(
		__field(int, crc_25pct)
		__field(int, crc_58pct)
		__field(int, crc_75pct)
	),
	TP_fast_assign(
		__entry->crc_25pct = crc_25pct;
		__entry->crc_58pct = crc_58pct;
		__entry->crc_75pct = crc_75pct;
	),
	TP_printk("crc_25=%d crc_58=%d crc_75=%d",
		__entry->crc_25pct, __entry->crc_58pct,
		__entry->crc_75pct
	)
);

DECLARE_EVENT_CLASS(gmu_oob_template,
	TP_PROTO(unsigned int mask),
	TP_ARGS(mask),
	TP_STRUCT__entry(
		__field(unsigned int, mask)
	),
	TP_fast_assign(
		__entry->mask = mask;
	),
	TP_printk("mask=0x%08x", __entry->mask)
);

DEFINE_EVENT(gmu_oob_template, kgsl_gmu_oob_set,
	TP_PROTO(unsigned int mask),
	TP_ARGS(mask)
);

DEFINE_EVENT(gmu_oob_template, kgsl_gmu_oob_clear,
	TP_PROTO(unsigned int mask),
	TP_ARGS(mask)
);

DECLARE_EVENT_CLASS(hfi_msg_template,
	TP_PROTO(unsigned int id, unsigned int size, unsigned int seqnum),
	TP_ARGS(id, size, seqnum),
	TP_STRUCT__entry(
		__field(unsigned int, id)
		__field(unsigned int, size)
		__field(unsigned int, seq)
	),
	TP_fast_assign(
		__entry->id = id;
		__entry->size = size;
		__entry->seq = seqnum;
	),
	TP_printk("id=0x%x size=0x%x seqnum=0x%x",
		__entry->id, __entry->size, __entry->seq)
);

DEFINE_EVENT(hfi_msg_template, kgsl_hfi_send,
	TP_PROTO(unsigned int id, unsigned int size, unsigned int seqnum),
	TP_ARGS(id, size, seqnum)
);

DEFINE_EVENT(hfi_msg_template, kgsl_hfi_receive,
	TP_PROTO(unsigned int id, unsigned int size, unsigned int seqnum),
	TP_ARGS(id, size, seqnum)
);

TRACE_EVENT(kgsl_timeline_alloc,
	TP_PROTO(
		u32 id,
		u64 seqno
	),
	TP_ARGS(
		id,
		seqno
	),
	TP_STRUCT__entry(
		__field(u32, id)
		__field(u64, seqno)
	),
	TP_fast_assign(
		__entry->id = id;
		__entry->seqno = seqno;
	),
	TP_printk("id=%u initial=%llu",
		__entry->id, __entry->seqno
	)
);

TRACE_EVENT(kgsl_timeline_destroy,
	TP_PROTO(
		u32 id
	),
	TP_ARGS(
		id
	),
	TP_STRUCT__entry(
		__field(u32, id)
	),
	TP_fast_assign(
		__entry->id = id;
	),
	TP_printk("id=%u",
		__entry->id
	)
);


TRACE_EVENT(kgsl_timeline_signal,
	TP_PROTO(
		u32 id,
		u64 seqno
	),
	TP_ARGS(
		id,
		seqno
	),
	TP_STRUCT__entry(
		__field(u32, id)
		__field(u64, seqno)
	),
	TP_fast_assign(
		__entry->id = id;
		__entry->seqno = seqno;
	),
	TP_printk("id=%u seqno=%llu",
		__entry->id, __entry->seqno
	)
);

TRACE_EVENT(kgsl_timeline_fence_alloc,
	TP_PROTO(
		u32 timeline,
		u64 seqno
	),
	TP_ARGS(
		timeline,
		seqno
	),
	TP_STRUCT__entry(
		__field(u32, timeline)
		__field(u64, seqno)
	),
	TP_fast_assign(
		__entry->timeline = timeline;
		__entry->seqno = seqno;
	),
	TP_printk("timeline=%u seqno=%llu",
		__entry->timeline, __entry->seqno
	)
);

TRACE_EVENT(kgsl_timeline_fence_release,
	TP_PROTO(
		u32 timeline,
		u64 seqno
	),
	TP_ARGS(
		timeline,
		seqno
	),
	TP_STRUCT__entry(
		__field(u32, timeline)
		__field(u64, seqno)
	),
	TP_fast_assign(
		__entry->timeline = timeline;
		__entry->seqno = seqno;
	),
	TP_printk("timeline=%u seqno=%llu",
		__entry->timeline, __entry->seqno
	)
);


TRACE_EVENT(kgsl_timeline_wait,
	TP_PROTO(
		u32 flags,
		s64 tv_sec,
		s64 tv_nsec
	),
	TP_ARGS(
		flags,
		tv_sec,
		tv_nsec
	),
	TP_STRUCT__entry(
		__field(u32, flags)
		__field(s64, tv_sec)
		__field(s64, tv_nsec)
	),
	TP_fast_assign(
		__entry->flags = flags;
		__entry->tv_sec = tv_sec;
		__entry->tv_nsec = tv_nsec;
	),
	TP_printk("flags=0x%x tv_sec=%llu tv_nsec=%llu",
		__entry->flags, __entry->tv_sec, __entry->tv_nsec

	)
);

TRACE_EVENT(kgsl_aux_command,
	TP_PROTO(u32 drawctxt_id, u32 numcmds, u32 flags, u32 timestamp
	),
	TP_ARGS(drawctxt_id, numcmds, flags, timestamp
	),
	TP_STRUCT__entry(
		__field(u32, drawctxt_id)
		__field(u32, numcmds)
		__field(u32, flags)
		__field(u32, timestamp)
	),
	TP_fast_assign(
		__entry->drawctxt_id = drawctxt_id;
		__entry->numcmds = numcmds;
		__entry->flags = flags;
		__entry->timestamp = timestamp;
	),
	TP_printk("context=%u numcmds=%u flags=0x%x timestamp=%u",
		__entry->drawctxt_id, __entry->numcmds, __entry->flags,
		__entry->timestamp
	)
);

TRACE_EVENT(kgsl_drawobj_timeline,
	TP_PROTO(u32 timeline, u64 seqno
	),
	TP_ARGS(timeline, seqno
	),
	TP_STRUCT__entry(
		__field(u32, timeline)
		__field(u64, seqno)
	),
	TP_fast_assign(
		__entry->timeline = timeline;
		__entry->seqno = seqno;
	),
	TP_printk("timeline=%u seqno=%llu",
		__entry->timeline, __entry->seqno
	)
);

TRACE_EVENT(kgsl_thermal_constraint,
	TP_PROTO(
		s32 max_freq
	),
	TP_ARGS(
		max_freq
	),
	TP_STRUCT__entry(
		__field(s32, max_freq)
	),
	TP_fast_assign(
		__entry->max_freq = max_freq;
	),
	TP_printk("Thermal max freq=%d",
		__entry->max_freq
	)
);

TRACE_EVENT(kgsl_pool_add_page,
	TP_PROTO(int order, u32 count),
	TP_ARGS(order, count),
	TP_STRUCT__entry(
		__field(int, order)
		__field(u32, count)
	),
	TP_fast_assign(
		__entry->order = order;
		__entry->count = count;
	),
	TP_printk("order=%d count=%u",
		__entry->order, __entry->count
	)
);

TRACE_EVENT(kgsl_pool_get_page,
	TP_PROTO(int order, u32 count),
	TP_ARGS(order, count),
	TP_STRUCT__entry(
		__field(int, order)
		__field(u32, count)
	),
	TP_fast_assign(
		__entry->order = order;
		__entry->count = count;
	),
	TP_printk("order=%d count=%u",
		__entry->order, __entry->count
	)
);

TRACE_EVENT(kgsl_pool_alloc_page_system,
	TP_PROTO(int order),
	TP_ARGS(order),
	TP_STRUCT__entry(
		__field(int, order)
	),
	TP_fast_assign(
		__entry->order = order;
	),
	TP_printk("order=%d",
		__entry->order
	)
);

TRACE_EVENT(kgsl_pool_try_page_lower,
	TP_PROTO(int order),
	TP_ARGS(order),
	TP_STRUCT__entry(
		__field(int, order)
	),
	TP_fast_assign(
		__entry->order = order;
	),
	TP_printk("order=%d",
		__entry->order
	)
);

TRACE_EVENT(kgsl_pool_free_page,
	TP_PROTO(int order),
	TP_ARGS(order),
	TP_STRUCT__entry(
		__field(int, order)
	),
	TP_fast_assign(
		__entry->order = order;
	),
	TP_printk("order=%d",
		__entry->order
	)
);

TRACE_EVENT(kgsl_reclaim_memdesc,
	TP_PROTO(
		struct kgsl_mem_entry *mem_entry,
		bool swapout
	),

	TP_ARGS(mem_entry, swapout
	),

	TP_STRUCT__entry(
		__field(uint64_t, gpuaddr)
		__field(uint64_t, size)
		__field(unsigned int, page_count)
		__field(unsigned int, tgid)
		__field(unsigned int, id)
		__field(uint64_t, flags)
		__field(bool, swapout)
	),

	TP_fast_assign(
		__entry->gpuaddr = mem_entry->memdesc.gpuaddr;
		__entry->size = mem_entry->memdesc.size;
		__entry->page_count = mem_entry->memdesc.page_count;
		__entry->tgid = pid_nr(mem_entry->priv->pid);
		__entry->id = mem_entry->id;
		__entry->flags = mem_entry->memdesc.flags;
		__entry->swapout = swapout;
	),

	TP_printk(
		"gpuaddr=0x%llx size=%llu page_count=%u tgid=%u id=%u flags=0x%llx swap=%s",
		__entry->gpuaddr, __entry->size, __entry->page_count, __entry->tgid,
		__entry->id, __entry->flags, __entry->swapout ? "out" : "in"
	)
);

TRACE_EVENT(kgsl_reclaim_process,
	TP_PROTO(
		struct kgsl_process_private *process,
		u32 swap_count,
		bool swapout
	),

	TP_ARGS(process, swap_count, swapout
	),

	TP_STRUCT__entry(
		__field(unsigned int, pid)
		__field(u32, swap_count)
		__field(u32, unpinned_page_count)
		__field(bool, swapout)
	),
	TP_fast_assign(
		__entry->pid = pid_nr(process->pid);
		__entry->swap_count = swap_count;
		__entry->unpinned_page_count = atomic_read(&process->unpinned_page_count);
		__entry->swapout = swapout;
	),
	TP_printk(
		"tgid=%u swapped=%u swapped_out_total=%u swap=%s",
		__entry->pid, __entry->swap_count, __entry->unpinned_page_count,
		__entry->swapout ? "out" : "in"
	)
);

#endif /* _KGSL_TRACE_H */

/* This part must be outside protection */
#include <trace/define_trace.h>


============================================================
FILE: kgsl_util.c
REASON: SOURCE
============================================================
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (c) 2020-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */


#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/ktime.h>
#include <linux/pm_domain.h>
#include <linux/version.h>
#if (KERNEL_VERSION(6, 3, 0) <= LINUX_VERSION_CODE)
#include <linux/firmware/qcom/qcom_scm.h>
#else
#include <linux/qcom_scm.h>
#endif
#if IS_ENABLED(CONFIG_QCOM_SCM_ADDON)
#include <linux/firmware/qcom/qcom_scm_addon.h>
#endif
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/string.h>

#include "adreno.h"
#include "kgsl_pool.h"
#include "kgsl_util.h"

int cmp_u32(const void *first, const void *second)
{
	u32 va = *(u32 *)first;
	u32 vb = *(u32 *)second;

	return (va > vb) - (va < vb);
}

bool kgsl_genpd_is_enabled(struct device *dev)
{
	struct generic_pm_domain *genpd;

	if (IS_ERR_OR_NULL(dev) || IS_ERR_OR_NULL(dev->pm_domain))
		return false;

	genpd = pd_to_genpd(dev->pm_domain);
	return (READ_ONCE(genpd->status) == GENPD_STATE_ON);
}

struct clk *kgsl_of_clk_by_name(struct clk_bulk_data *clks, int count,
		const char *id)
{
	int i;

	for (i = 0; clks && i < count; i++)
		if (!strcmp(clks[i].id, id))
			return clks[i].clk;

	return NULL;
}

int kgsl_regulator_set_voltage(struct device *dev,
		struct regulator *reg, u32 voltage)
{
	int ret;

	if (IS_ERR_OR_NULL(reg))
		return 0;

	ret = regulator_set_voltage(reg, voltage, INT_MAX);
	if (ret)
		dev_err(dev, "Regulator set voltage:%d failed:%d\n", voltage, ret);

	return ret;
}

int kgsl_clk_set_rate(struct clk_bulk_data *clks, int num_clks,
		const char *id, unsigned long rate)
{
	struct clk *clk;

	clk = kgsl_of_clk_by_name(clks, num_clks, id);

	/*
	 * If the downstream clock name isn't found, try removing "_clk" and retry
	 * with corresponding standard clock name.
	 */
	if (!clk && (strlen(id) > 4) && (strcmp(id + strlen(id) - 4, "_clk") == 0)) {
		char alt_id[32];
		size_t new_len = strlen(id) - 4;

		if (new_len < sizeof(alt_id)) {
			memcpy(alt_id, id, new_len);
			alt_id[new_len] = '\0';
			clk = kgsl_of_clk_by_name(clks, num_clks, alt_id);
		}
	}

	if (!clk)
		return -ENODEV;

	return clk_set_rate(clk, rate);
}

#if (KERNEL_VERSION(6, 1, 0) > LINUX_VERSION_CODE)
static int _kgsl_scm_gpu_init_regs(u32 gpu_req)
{
	return -EOPNOTSUPP;
}
#elif (KERNEL_VERSION(6, 11, 0) <= LINUX_VERSION_CODE)
static int _kgsl_scm_gpu_init_regs(u32 gpu_req)
{
	return qcom_scm_gpu_init_regs(gpu_req);
}
#elif (IS_ENABLED(CONFIG_QCOM_KGSL_UPSTREAM) && !IS_ENABLED(CONFIG_QCOM_SCM_ADDON))
static int _kgsl_scm_gpu_init_regs(u32 gpu_req)
{
	return -EINVAL;
}
#else
static int _kgsl_scm_gpu_init_regs(u32 gpu_req)
{
	return qcom_scm_kgsl_init_regs(gpu_req);
}
#endif

int kgsl_scm_gpu_init_regs(struct device *dev, u32 gpu_req, bool zap_enabled)
{
	int ret;

	if (!gpu_req)
		return -EOPNOTSUPP;

	ret = _kgsl_scm_gpu_init_regs(gpu_req);
	if (ret && (ret != -EOPNOTSUPP)) {
		if (zap_enabled)
			dev_err(dev, "Scm call for requests:0x%x failed with ret:: %d\n",
									gpu_req, ret);
		else
			return -EOPNOTSUPP;
	}

	return ret;
}

int kgsl_hwlock(struct cpu_gpu_lock *lock)
{
	unsigned long timeout = jiffies + msecs_to_jiffies(1000);

	/* Indicate that the CPU wants the lock */
	lock->cpu_req = 1;

	/* post the request */
	wmb();

	/* Wait for our turn */
	lock->turn = 0;

	/* Finish all memory transactions before moving on */
	mb();

	/*
	 * Spin here while GPU ucode holds the lock, lock->gpu_req will
	 * be set to 0 after GPU ucode releases the lock. Maximum wait time
	 * is 1 second and this should be enough for GPU to release the lock.
	 */
	while (lock->gpu_req && lock->turn == 0) {
		cpu_relax();
		/* Get the latest updates from GPU */
		rmb();

		if (time_after(jiffies, timeout))
			break;
	}

	if (lock->gpu_req && lock->turn == 0)
		return -EBUSY;

	return 0;
}

void kgsl_hwunlock(struct cpu_gpu_lock *lock)
{
	/* Make sure all writes are done before releasing the lock */
	wmb();
	lock->cpu_req = 0;
}


bool kgsl_is_compatible_node_available(const char *compat)
{
	struct device_node *node;
	bool avail;

	node = of_find_compatible_node(NULL, NULL, compat);

	if (!node)
		return false;

	avail = of_device_is_available(node);
	of_node_put(node);

	return avail;
}

int kgsl_attach_iommu_group(struct device *dev, struct iommu_domain *domain,
		struct iommu_group **group)
{
	struct iommu_group *grp = iommu_group_get(dev);
	int ret;

	if (!grp)
		return -ENODEV;

	ret = iommu_attach_group(domain, grp);
	if (ret) {
		iommu_group_put(grp);
		return ret;
	}

	*group = grp;

	return 0;
}

void kgsl_detach_iommu_group(struct iommu_domain *domain, struct iommu_group *group)
{
	iommu_detach_group(domain, group);
	iommu_group_put(group);
}

#if IS_ENABLED(CONFIG_QCOM_KGSL_UPSTREAM)
#include <linux/soc/qcom/smem.h>
#include <linux/soc/qcom/socinfo.h>

#if defined(SMEM_DDR_BUILD_ID)
int kgsl_get_ddrtype(void)
{
	struct ddrinfo *ddr;

	ddr = qcom_smem_get(QCOM_SMEM_HOST_ANY, SMEM_DDR_BUILD_ID, NULL);
	if (IS_ERR(ddr)) {
		pr_err("kgsl: Unable to get ddr type\n");
		return PTR_ERR(ddr);
	}

	return ddr->device_type;
}
#else /* !defined(SMEM_DDR_BUILD_ID) */
int kgsl_get_ddrtype(void)
{
	return -ENOENT;
}
#endif /* defined(SMEM_DDR_BUILD_ID) */
#else /* !IS_ENABLED(CONFIG_QCOM_KGSL_UPSTREAM) */
#include <soc/qcom/of_common.h>
int kgsl_get_ddrtype(void)
{
	return of_fdt_get_ddrtype();
}
#endif /* IS_ENABLED(CONFIG_QCOM_KGSL_UPSTREAM) */

#if IS_ENABLED(CONFIG_QCOM_VA_MINIDUMP)
#include <soc/qcom/minidump.h>

void kgsl_add_to_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size)
{
	struct md_region md_entry = {0};
	int ret;

	if (!msm_minidump_enabled())
		return;

	scnprintf(md_entry.name, sizeof(md_entry.name), name);
	md_entry.virt_addr = virt_addr;
	md_entry.phys_addr = phy_addr;
	md_entry.size = size;
	ret = msm_minidump_add_region(&md_entry);
	if (ret < 0 && ret != -EEXIST)
		pr_err("kgsl: Failed to register %s with minidump:%d\n", name, ret);

}

void kgsl_remove_from_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size)
{
	struct md_region md_entry = {0};
	int ret;

	if (!msm_minidump_enabled())
		return;

	scnprintf(md_entry.name, sizeof(md_entry.name), name);
	md_entry.virt_addr = virt_addr;
	md_entry.phys_addr = phy_addr;
	md_entry.size = size;
	ret = msm_minidump_remove_region(&md_entry);
	if (ret < 0 && ret != -ENOENT)
		pr_err("kgsl: Failed to remove %s from minidump\n", name);
}

int kgsl_add_va_to_minidump(struct device *dev, const char *name, void *ptr,
		size_t size)
{
	struct va_md_entry entry = {0};
	int ret;

	scnprintf(entry.owner, sizeof(entry.owner), name);
	entry.vaddr = (u64)(ptr);
	entry.size = size;
	ret = qcom_va_md_add_region(&entry);
	if (ret < 0)
		dev_err(dev, "Failed to register %s with va_minidump: %d\n", name,
				ret);

	return ret;
}

static bool include_global_in_minidump(struct kgsl_global_memdesc *md)
{
	static const char * const globals[] = {"ringbuffer", "memstore", "scratch",
				"profile", "profile_desc", "alwayson"};
	int i;

	for (i = 0; i < ARRAY_SIZE(globals); i++) {
		if (!strcmp(md->name, globals[i]))
			return true;
	}

	return false;
}

#ifdef CONFIG_QCOM_KGSL_USE_SHMEM
static int kgsl_add_page_pools_to_va_minidump(struct kgsl_device *device)
{
	return 0;
}
#else
static int kgsl_add_page_pools_to_va_minidump(struct kgsl_device *device)
{
	int i, ret;

	for (i = 0; i < kgsl_num_pools; i++) {
		ret = kgsl_add_va_to_minidump(device->dev, KGSL_PAGE_POOL_ENTRY,
				(void *)&kgsl_pools[i], sizeof(kgsl_pools[i]));
		if (ret)
			return ret;
	}

	return 0;
}
#endif

#ifdef CONFIG_SYNC_FILE
static int kgsl_add_sync_timeline_info_to_va_minidump(struct kgsl_device *device)
{
	int ret, id;
	struct kgsl_context *context;

	idr_for_each_entry(&device->context_idr, context, id) {
		char name[MAX_VA_MINIDUMP_STR_LEN];
		struct kgsl_sync_fence *kfence, *next;
		struct kgsl_sync_timeline *ktimeline = context->ktimeline;

		snprintf(name, sizeof(name), KGSL_SYNC_TIMELINE_ENTRY "_ctxt:%d", context->id);
		ret = kgsl_add_va_to_minidump(device->dev, name,
				(void *)(ktimeline), sizeof(*ktimeline));
		if (ret)
			return ret;

		list_for_each_entry_safe(kfence, next, &ktimeline->child_list_head, child_list) {
			snprintf(name, sizeof(name), KGSL_SYNC_FENCE_ENTRY "_ctxt:%d",
				context->id);
			ret = kgsl_add_va_to_minidump(device->dev, name,
					(void *)(kfence), sizeof(*kfence));
			if (ret)
				return ret;
		}
	}

	return 0;
}
#else
static int kgsl_add_sync_timeline_info_to_va_minidump(struct kgsl_device *device)
{
	return 0;
}
#endif

static int kgsl_add_driver_data_to_va_minidump(struct kgsl_device *device)
{
	int ret;
	char name[MAX_VA_MINIDUMP_STR_LEN];
	struct kgsl_pagetable *pt;
	struct adreno_context *ctxt;
	struct kgsl_process_private *p;
	struct kgsl_global_memdesc *md;
	struct adreno_device *adreno_dev = ADRENO_DEVICE(device);

	ret = kgsl_add_va_to_minidump(device->dev, KGSL_DRIVER,
			(void *)(&kgsl_driver), sizeof(struct kgsl_driver));
	if (ret)
		return ret;

	if (!ADRENO_FEATURE(adreno_dev, ADRENO_GMU_BASED_DCVS) &&
		device->pwrscale.enabled) {
		struct msm_busmon_extended_profile bus_profile = device->pwrscale.bus_profile;

		ret = kgsl_add_va_to_minidump(device->dev, KGSL_ADRENO_TZ_DATA_ENTRY,
				(void *)bus_profile.private_data,
				sizeof(*bus_profile.private_data));
		if (ret)
			return ret;
	}

	ret = kgsl_add_page_pools_to_va_minidump(device);
	if (ret)
		return ret;

	list_for_each_entry(ctxt, &adreno_dev->active_list, active_node) {
		snprintf(name, sizeof(name), KGSL_ADRENO_CTX_ENTRY"_%d", ctxt->base.id);
		ret = kgsl_add_va_to_minidump(device->dev, name,
				(void *)(ctxt), sizeof(struct adreno_context));
		if (ret)
			break;
	}

	list_for_each_entry(p, &kgsl_driver.process_list, list) {
		snprintf(name, sizeof(name), KGSL_PROC_PRIV_ENTRY "_%d", pid_nr(p->pid));
		ret = kgsl_add_va_to_minidump(device->dev, name,
				(void *)(p), sizeof(struct kgsl_process_private));
		if (ret)
			break;
	}

	list_for_each_entry(pt, &kgsl_driver.pagetable_list, list) {
		snprintf(name, sizeof(name), KGSL_PGTABLE_ENTRY"_%d", pt->name);
		ret = kgsl_add_va_to_minidump(device->dev, name,
				(void *)(pt), sizeof(struct kgsl_pagetable));
		if (ret)
			break;
	}

	ret = kgsl_add_sync_timeline_info_to_va_minidump(device);
	if (ret)
		return ret;

	/*
	 * Global buffers for HWSCHED are dumped in target-specific code. Therefore,
	 * only dump the required globals for SWSCHED here.
	 */
	if (!adreno_dev->hwsched_enabled) {
		list_for_each_entry(md, &device->globals, node) {
			if (include_global_in_minidump(md)) {
				snprintf(name, sizeof(name), "kgsl_global_%s", md->name);
				ret = kgsl_add_va_to_minidump(device->dev, name,
						md->memdesc.hostptr, md->memdesc.size);
				if (ret)
					break;
			}
		}
	}

	return ret;
}

static int kgsl_va_minidump_callback(struct notifier_block *nb,
		unsigned long action, void *unused)
{
	struct adreno_device *adreno_dev = ADRENO_DEVICE(kgsl_driver.devp[0]);
	const struct adreno_gpudev *gpudev = ADRENO_GPU_DEVICE(adreno_dev);

	if (kgsl_add_driver_data_to_va_minidump(kgsl_driver.devp[0]))
		return NOTIFY_BAD;

	if (gpudev->add_to_va_minidump(adreno_dev))
		return NOTIFY_BAD;

	return NOTIFY_OK;
}

static struct notifier_block kgsl_va_minidump_nb = {
	.priority = INT_MAX,
	.notifier_call = kgsl_va_minidump_callback,
};

void kgsl_qcom_va_md_register(struct kgsl_device *device)
{
	int ret;

	if (!qcom_va_md_enabled())
		return;

	ret = qcom_va_md_register("KGSL", &kgsl_va_minidump_nb);
	if (ret)
		dev_err(device->dev, "Failed to register notifier with va_minidump: %d\n", ret);
}

void kgsl_qcom_va_md_unregister(struct kgsl_device *device)
{
	int ret;

	if (!qcom_va_md_enabled())
		return;

	ret = qcom_va_md_unregister("KGSL", &kgsl_va_minidump_nb);
	if (ret)
		dev_err(device->dev, "Failed to unregister notifier with va_minidump: %d\n", ret);
}
#endif


============================================================
FILE: kgsl_util.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2019-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#ifndef _KGSL_UTIL_H_
#define _KGSL_UTIL_H_

#include <linux/version.h>

#define KGSL_DRIVER "kgsl_driver"
#define KGSL_ADRENO_DEVICE "kgsl_adreno_device"
#define KGSL_A6XX_DEVICE "kgsl_a6xx_device"
#define KGSL_GEN7_DEVICE "kgsl_gen7_device"
#define KGSL_HWSCHED_DEVICE "kgsl_hwsched_device"
#define KGSL_GEN8_DEVICE "kgsl_gen8_device"

#define KGSL_SCRATCH_ENTRY "scratch"
#define KGSL_MEMSTORE_ENTRY "memstore"
#define KGSL_GMU_LOG_ENTRY "kgsl_gmu_log"
#define KGSL_GMU_TRACE_ENTRY "kgsl_gmu_trace"
#define KGSL_HFIMEM_ENTRY "kgsl_hfi_mem"
#define KGSL_GMU_DUMPMEM_ENTRY "kgsl_gmu_dump_mem"
#define KGSL_GMU_RB_ENTRY "gmu_rb"
#define KGSL_GMU_KERNEL_PROF_ENTRY "gmu_kernel_profiling"
#define KGSL_GMU_USER_PROF_ENTRY "gmu_user_profiling"
#define KGSL_GMU_CMD_BUFFER_ENTRY "gmu_cmd_buffer"
#define KGSL_HFI_BIG_IB_ENTRY "kgsl_hfi_big_ib"
#define KGSL_HFI_BIG_IB_REC_ENTRY "kgsl_hfi_big_ib_rec"
#define KGSL_ADRENO_CTX_ENTRY "kgsl_adreno_ctx"
#define KGSL_PROC_PRIV_ENTRY "kgsl_proc_priv"
#define KGSL_PGTABLE_ENTRY "kgsl_pgtable"
#define KGSL_GMU_VRB_ENTRY "kgsl_gmu_vrb"
#define KGSL_SYNC_FENCE_ENTRY "kgsl_sync_fence"
#define KGSL_SYNC_TIMELINE_ENTRY "kgsl_sync_timeline"
#define KGSL_PAGE_POOL_ENTRY "kgsl_page_pool"
#define KGSL_ADRENO_TZ_DATA_ENTRY "kgsl_adreno_tz_data"
#define KGSL_NC_OVERRIDES_ENTRY "kgsl_nc_overrides"

#define MAX_VA_MINIDUMP_STR_LEN 48


/**
 * Request TZ to program set of access controlled registers that KGSL needs
 * irrespective of any features
 */
#define GPU_ALWAYS_EN_REQ BIT(0)
/**
 * Request TZ to program BCL id to access controlled register when BCL is
 * enabled
 */
#define GPU_BCL_EN_REQ BIT(1)
/**
 * Request TZ to program set of access controlled register for CLX feature
 * when enabled
 */
#define GPU_CLX_EN_REQ BIT(2)
/**
 * Request TZ to program tsense ids to access controlled registers for reading
 * gpu temperature sensors
 */
#define GPU_TSENSE_EN_REQ BIT(3)
/**
 * Request TZ to program tsense measurement to a large period
 */
#define GPU_TSENSE_MEASURE_DEFAULT_DISABLE BIT(4)

struct regulator;
struct clk_bulk_data;

/**
 * struct cpu_gpu_lock - CP spinlock structure for power up list
 * @gpu_req: flag value set by CP
 * @cpu_req: flag value set by KMD
 * @turn: turn variable set by both CP and KMD
 * @list_length: this tells CP the last dword in the list:
 * 16 + (4 * (List_Length - 1))
 * @list_offset: this tells CP the start of preemption only list:
 * 16 + (4 * List_Offset)
 * @ifpc_list_len: number of static ifpc duplets in the list
 * @preemption_list_len: number of static preemption duplets in the list
 * @dynamic_list_len: number of dynamically added triplets in the list
 */
struct cpu_gpu_lock {
	u32 gpu_req;
	u32 cpu_req;
	u32 turn;
	union {
		struct {
			u16 list_length;
			u16 list_offset;
		};
		struct {
			u8 ifpc_list_len;
			u8 preemption_list_len;
			u16 dynamic_list_len;
		};
	};
};

/**
 * kgsl_hwlock - Try to get the spinlock
 * @lock: cpu_gpu_lock structure
 *
 * Spin while the GPU has the lock.
 *
 * Return: 0 if lock is successful, -EBUSY if timed out waiting for lock
 */
int kgsl_hwlock(struct cpu_gpu_lock *lock);

/**
 * kgsl_hwunlock - Release a previously grabbed lock
 * @lock: cpu_gpu_lock structure
 */
void kgsl_hwunlock(struct cpu_gpu_lock *lock);

/**
 * kgsl_genpd_is_enabled - Check whether genpd is enabled or not
 * @dev: Power domain handle
 *
 * Return: True if genpd is enabled otherwise false.
 */
bool kgsl_genpd_is_enabled(struct device *dev);

/**
 * kgsl_of_clk_by_name - Return a clock device for a given name
 * @clks: Pointer to an array of bulk clk data
 * @count: Number of entries in the array
 * @id: Name of the clock to search for
 *
 * Returns: A pointer to the clock device for the given name or NULL if not
 * found
 */
struct clk *kgsl_of_clk_by_name(struct clk_bulk_data *clks, int count,
		const char *id);
/**
 * kgsl_regulator_set_voltage - Set voltage level for regulator
 * @dev: A &struct device pointer
 * @reg: A &struct regulator handle
 * @voltage: Voltage value to set regulator
 *
 * Return: 0 on success and negative error on failure.
 */
int kgsl_regulator_set_voltage(struct device *dev,
		struct regulator *reg, u32 voltage);

/**
 * kgsl_clk_set_rate - Set a clock to a given rate
 * @clks: Pointer to an array of bulk clk data
 * @count: Number of entries in the array
 * @id: Name of the clock to search for
 * @rate: Rate to st the clock to
 *
 * Return: 0 on success or negative error on failure
 */
int kgsl_clk_set_rate(struct clk_bulk_data *clks, int num_clks,
		const char *id, unsigned long rate);


/**
 * kgsl_is_compatible_node_available() - Check if a device with matching
 *					compatible is available
 * @compat: The compatible string that the device must have
 *
 * Find a device with the compatible string that is passed and check if
 * the device is available.
 *
 * Return: true if a suitable device is available, false otherwise
 */
bool kgsl_is_compatible_node_available(const char *compat);

/**
 * kgsl_attach_iommu_group() - Get iommu group and attach domain
 *
 * @dev: iommu group of this device is used
 * @domain: iommu domain to attach
 * @group: This is updated with iommu group on successful attach
 *
 * Get the iommu group of a device and attach iommu domain to the group.
 *
 * Return: 0 on success, negative error on failure
 */
int kgsl_attach_iommu_group(struct device *dev, struct iommu_domain *domain,
		struct iommu_group **group);

/**
 * kgsl_detach_iommu_group() - Detach iommu domain from group
 *
 * @domain: iommu domain to detach
 * @group: iommu group to be used for detach
 *
 * Detach iommu domain from iommu group
 */
void kgsl_detach_iommu_group(struct iommu_domain *domain, struct iommu_group *group);

/**
 * kgsl_scm_gpu_init_regs - Load secure registers through tz
 * @dev: Pointer to the GPU platform device
 * @gpu_req: Bit mask of requests to enable
 * @zap_enabled: True when there is no zap-shader
 *
 * Return: 0 on success or negative on failure and EOPNOTSUPP if scm call
 * not supported
 */
int kgsl_scm_gpu_init_regs(struct device *dev, u32 gpu_req, bool zap_enabled);

#if IS_ENABLED(CONFIG_QCOM_VA_MINIDUMP)
/**
 * kgsl_add_to_minidump - Add a physically contiguous section to minidump
 * @name: Name of the section
 * @virt_addr: Virtual address of the section
 * @phy_addr: Physical address of the section
 * @size: Size of the section
 */
void kgsl_add_to_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size);

/**
 * kgsl_remove_from_minidump - Remove a contiguous section from minidump
 * @name: Name of the section
 * @virt_addr: Virtual address of the section
 * @phy_addr: Physical address of the section
 * @size: Size of the section
 */
void kgsl_remove_from_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size);

/**
 * kgsl_add_va_to_minidump - Add a physically non-contiguous section to minidump
 * @dev: Pointer to the struct device for the GPU platform device
 * @name: Name of the section
 * @ptr: Virtual address of the section
 * @size: Size of the section
 */
int kgsl_add_va_to_minidump(struct device *dev, const char *name, void *ptr,
		size_t size);

/**
 * kgsl_qcom_va_md_register - Register driver with va-minidump
 * @device: Pointer to kgsl device
 */
void kgsl_qcom_va_md_register(struct kgsl_device *device);

/**
 * kgsl_qcom_va_md_unregister - Unregister driver with va-minidump
 * @device: Pointer to kgsl device
 */
void kgsl_qcom_va_md_unregister(struct kgsl_device *device);
#else
static inline void kgsl_add_to_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size)
{
}

static inline void kgsl_remove_from_minidump(char *name, u64 virt_addr, u64 phy_addr, size_t size)
{
}

static inline int kgsl_add_va_to_minidump(struct device *dev, const char *name, void *ptr,
		size_t size)
{
	return 0;
}

static inline void kgsl_qcom_va_md_register(struct kgsl_device *device)
{
}

static inline void kgsl_qcom_va_md_unregister(struct kgsl_device *device)
{
}
#endif

#ifdef CONFIG_QCOM_KGSL_UPSTREAM
static inline int qcom_scm_pas_shutdown_retry(u32 peripheral)
{
	return -EINVAL;
}

static inline int qcom_scm_kgsl_set_smmu_lpac_aperture(
                               unsigned int num_context_bank)
{
       return -EINVAL;
}

/**
 * kgsl_get_ddrtype - Type of ddr on the current device
 *
 * Return: ddr type on success or negative error on failure.
 */
int kgsl_get_ddrtype(void);

static inline void qcom_clk_dump(struct clk *clk, struct regulator *regulator,
		bool calltrace)
{
}

#endif

#if IS_ENABLED(CONFIG_QCOM_PAS)
#include <linux/firmware/qcom/qcom_pas.h>

static inline int kgsl_pas_auth_and_reset(u32 pas_id)
{
	return qcom_pas_auth_and_reset(pas_id);
}

static inline int kgsl_pas_shutdown(u32 pas_id)
{
	return qcom_pas_shutdown(pas_id);
}

static inline int kgsl_pas_set_remote_state(u32 state, u32 pas_id)
{
	return qcom_pas_set_remote_state(state, pas_id);
}
#else
#if (KERNEL_VERSION(6, 3, 0) <= LINUX_VERSION_CODE)
#include <linux/firmware/qcom/qcom_scm.h>
#else
#include <linux/qcom_scm.h>
#endif

static inline int kgsl_pas_auth_and_reset(u32 pas_id)
{
	return qcom_scm_pas_auth_and_reset(pas_id);
}

static inline int kgsl_pas_shutdown(u32 pas_id)
{
	return qcom_scm_pas_shutdown_retry(pas_id);
}

static inline int kgsl_pas_set_remote_state(u32 state, u32 pas_id)
{
	return qcom_scm_set_remote_state(state, pas_id);
}
#endif

/**
 * isdb_write - Program isdb registers to issue break commands to SP
 * @base: Base address of qdss registers to be programmed
 * @offset: offset to the SP block
 */
void isdb_write(void __iomem *base, u32 offset);

/**
 * cmp_u32 - Comparator function for sorting u32 values
 * @first: Pointer to the first element
 * @second: Pointer to the second element
 *
 * It is intended for use with the kernel's sort() function to sort
 * arrays of u32 in ascending order.
 */
int cmp_u32(const void *first, const void *second);

#if KERNEL_VERSION(6, 15, 0) <= LINUX_VERSION_CODE
#define kgsl_delete_timer(timer) timer_delete(timer)
#define kgsl_delete_timer_sync(timer) timer_delete_sync(timer)
#else
#define kgsl_delete_timer(timer) del_timer(timer)
#define kgsl_delete_timer_sync(timer) del_timer_sync(timer)
#endif

#if (KERNEL_VERSION(6, 16, 0) <= LINUX_VERSION_CODE)
#define kgsl_timer_container_of timer_container_of
#else
#define kgsl_timer_container_of from_timer
#endif

#if (KERNEL_VERSION(6, 18, 0) <= LINUX_VERSION_CODE)
/**
 * When using kgsl_nth_page, user has to make sure the pages are contiguous.
 * It can be checked with help of page_range_contiguous().
 */
#define kgsl_nth_page(page, n) ((page) + (n))
#else
#define kgsl_nth_page(page, n) nth_page((page), (n))
#endif

/*
 * Create and wake a kthread worker. On kernel versions below 6.14, kthread_create_worker
 * created a kthread worker and immediately woke it up. This was changed on kernel version 6.14
 * to only create the kthread worker. Use kthread_run_worker to restore the kthread worker
 * behavior.
 */
#if (KERNEL_VERSION(6, 14, 0) <= LINUX_VERSION_CODE)
#define kgsl_kthread_run_worker kthread_run_worker
#else
#define kgsl_kthread_run_worker kthread_create_worker
#endif

#endif


============================================================
FILE: kgsl_vbo.c
REASON: SOURCE
============================================================
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (c) 2020-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#include <linux/file.h>
#include <linux/interval_tree.h>
#include <linux/seq_file.h>
#include <linux/sync_file.h>
#include <linux/slab.h>

#include "kgsl_device.h"
#include "kgsl_mmu.h"
#include "kgsl_reclaim.h"
#include "kgsl_sharedmem.h"
#include "kgsl_trace.h"

struct kgsl_memdesc_bind_range {
	struct kgsl_mem_entry *entry;
	struct interval_tree_node range;
};

static struct kgsl_memdesc_bind_range *bind_to_range(struct interval_tree_node *node)
{
	return container_of(node, struct kgsl_memdesc_bind_range, range);
}

static struct kgsl_memdesc_bind_range *bind_range_create(u64 start, u64 last,
		struct kgsl_mem_entry *entry)
{
	struct kgsl_memdesc_bind_range *range =
		kzalloc(sizeof(*range), GFP_KERNEL);

	if (!range)
		return ERR_PTR(-ENOMEM);

	range->range.start = start;
	range->range.last = last;
	range->entry = kgsl_mem_entry_get(entry);

	if (!range->entry) {
		kfree(range);
		return ERR_PTR(-EINVAL);
	}

	atomic_inc(&entry->vbo_count);
	return range;
}

static void bind_range_destroy(struct kgsl_memdesc_bind_range *range)
{
	struct kgsl_mem_entry *entry = range->entry;

	atomic_dec(&entry->vbo_count);
	kgsl_mem_entry_put(entry);
	kfree(range);
}

static u64 bind_range_len(struct kgsl_memdesc_bind_range *range)
{
	return (range->range.last - range->range.start) + 1;
}

void kgsl_memdesc_print_vbo_ranges(struct kgsl_mem_entry *entry,
		struct seq_file *s)
{
	struct  interval_tree_node *next;
	struct kgsl_memdesc *memdesc = &entry->memdesc;

	if (!(memdesc->flags & KGSL_MEMFLAGS_VBO))
		return;

	/*
	 * We are called in an atomic context so try to get the mutex but if we
	 * don't then skip this item
	 */
	if (!mutex_trylock(&memdesc->ranges_lock))
		return;

	next = interval_tree_iter_first(&memdesc->ranges, 0, ~0UL);
	while (next) {
		struct kgsl_memdesc_bind_range *range = bind_to_range(next);

		seq_printf(s, "%5d %5d 0x%16.16lx-0x%16.16lx\n",
			entry->id, range->entry->id, range->range.start,
			range->range.last);

		next = interval_tree_iter_next(next, 0, ~0UL);
	}

	mutex_unlock(&memdesc->ranges_lock);
}

static void kgsl_memdesc_remove_range(struct kgsl_mem_entry *target,
		u64 start, u64 last, struct kgsl_mem_entry *entry)
{
	struct  interval_tree_node *node, *next;
	struct kgsl_memdesc_bind_range *range;
	struct kgsl_memdesc *memdesc = &target->memdesc;

	mutex_lock(&memdesc->ranges_lock);

	next = interval_tree_iter_first(&memdesc->ranges, start, last);
	while (next) {
		node = next;
		range = bind_to_range(node);
		next = interval_tree_iter_next(node, start, last);

		/*
		 * If entry is null, consider it as a special request. Unbind
		 * the entire range between start and last in this case.
		 */
		if (!entry || range->entry->id == entry->id) {
			if (kgsl_mmu_unmap_range(memdesc->pagetable,
				memdesc, range->range.start, bind_range_len(range)))
				continue;

			interval_tree_remove(node, &memdesc->ranges);
			trace_kgsl_mem_remove_bind_range(target,
				range->range.start, range->entry,
				bind_range_len(range));

			if (!(memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO))
				kgsl_mmu_map_zero_page_to_range(memdesc->pagetable,
					memdesc, range->range.start, bind_range_len(range));

			bind_range_destroy(range);
		}
	}

	mutex_unlock(&memdesc->ranges_lock);
}

static int kgsl_memdesc_add_range(struct kgsl_mem_entry *target,
		u64 start, u64 last, struct kgsl_mem_entry *entry, u64 offset)
{
	struct  interval_tree_node *node, *next;
	struct kgsl_memdesc *memdesc = &target->memdesc;
	struct kgsl_memdesc_bind_range *range =
		bind_range_create(start, last, entry);
	int ret = 0;

	if (IS_ERR(range))
		return PTR_ERR(range);

	mutex_lock(&memdesc->ranges_lock);

	/*
	 * If the VBO maps the zero page, then we can unmap the requested range
	 * in one call. Otherwise we have to figure out what ranges to unmap
	 * while walking the interval tree.
	 */
	if (!(memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO)) {
		ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc, start,
			last - start + 1);
		if (ret)
			goto error;
	}

	next = interval_tree_iter_first(&memdesc->ranges, start, last);

	while (next) {
		struct kgsl_memdesc_bind_range *cur;

		node = next;
		cur = bind_to_range(node);
		next = interval_tree_iter_next(node, start, last);

		trace_kgsl_mem_remove_bind_range(target, cur->range.start,
			cur->entry, bind_range_len(cur));

		interval_tree_remove(node, &memdesc->ranges);

		if (start <= cur->range.start) {
			if (last >= cur->range.last) {
				/* Unmap the entire cur range */
				if (memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO) {
					ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc,
						cur->range.start,
						cur->range.last - cur->range.start + 1);
					if (ret) {
						interval_tree_insert(node, &memdesc->ranges);
						goto error;
					}
				}

				bind_range_destroy(cur);
				continue;
			}

			/* Unmap the range overlapping cur */
			if (memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO) {
				ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc,
					cur->range.start,
					last - cur->range.start + 1);
				if (ret) {
					interval_tree_insert(node, &memdesc->ranges);
					goto error;
				}
			}

			/* Adjust the start of the mapping */
			cur->range.start = last + 1;
			/* And put it back into the tree */
			interval_tree_insert(node, &memdesc->ranges);

			trace_kgsl_mem_add_bind_range(target,
				cur->range.start, cur->entry, bind_range_len(cur));
		} else {
			if (last < cur->range.last) {
				struct kgsl_memdesc_bind_range *temp;

				/*
				 * The range is split into two so make a new
				 * entry for the far side
				 */
				temp = bind_range_create(last + 1, cur->range.last,
					cur->entry);
				/* FIXME: Uhoh, this would be bad */
				BUG_ON(IS_ERR(temp));

				interval_tree_insert(&temp->range,
					&memdesc->ranges);

				trace_kgsl_mem_add_bind_range(target,
					temp->range.start,
					temp->entry, bind_range_len(temp));
			}

			/* Unmap the range overlapping cur */
			if (memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO) {
				ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc,
					start,
					min_t(u64, cur->range.last, last) - start + 1);
				if (ret) {
					interval_tree_insert(node, &memdesc->ranges);
					goto error;
				}
			}

			cur->range.last = start - 1;
			interval_tree_insert(node, &memdesc->ranges);

			trace_kgsl_mem_add_bind_range(target, cur->range.start,
				cur->entry, bind_range_len(cur));
		}
	}

	ret = kgsl_mmu_map_child(memdesc->pagetable, memdesc, start,
			&entry->memdesc, offset, last - start + 1);
	if (ret)
		goto error;

	/* Add the new range */
	interval_tree_insert(&range->range, &memdesc->ranges);

	trace_kgsl_mem_add_bind_range(target, range->range.start,
		range->entry, bind_range_len(range));
	mutex_unlock(&memdesc->ranges_lock);

	return ret;

error:
	bind_range_destroy(range);
	mutex_unlock(&memdesc->ranges_lock);
	return ret;
}

static void kgsl_sharedmem_vbo_put_gpuaddr(struct kgsl_memdesc *memdesc)
{
	struct interval_tree_node *node, *next;
	struct kgsl_memdesc_bind_range *range;
	int ret = 0;
	bool unmap_fail;

	/*
	 * If the VBO maps the zero range then we can unmap the entire
	 * pagetable region in one call.
	 */
	if (!(memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO))
		ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc,
			0, memdesc->size);

	unmap_fail = ret;

	/*
	 * FIXME: do we have a use after free potential here?  We might need to
	 * lock this and set a "do not update" bit
	 */

	/* Now delete each range and release the mem entries */
	next = interval_tree_iter_first(&memdesc->ranges, 0, ~0UL);

	while (next) {
		node = next;
		range = bind_to_range(node);
		next = interval_tree_iter_next(node, 0, ~0UL);

		interval_tree_remove(node, &memdesc->ranges);

		/* Unmap this range */
		if (memdesc->flags & KGSL_MEMFLAGS_VBO_NO_MAP_ZERO)
			ret = kgsl_mmu_unmap_range(memdesc->pagetable, memdesc,
				range->range.start,
				range->range.last - range->range.start + 1);

		/* Put the child's refcount if unmap succeeds */
		if (!ret)
			bind_range_destroy(range);
		else
			kfree(range);

		unmap_fail = unmap_fail || ret;
	}

	if (unmap_fail)
		return;

	/* Put back the GPU address */
	kgsl_mmu_put_gpuaddr(memdesc->pagetable, memdesc);

	memdesc->gpuaddr = 0;
	memdesc->pagetable = NULL;
}

static struct kgsl_memdesc_ops kgsl_vbo_ops = {
	.put_gpuaddr = kgsl_sharedmem_vbo_put_gpuaddr,
};

int kgsl_sharedmem_allocate_vbo(struct kgsl_device *device,
		struct kgsl_memdesc *memdesc, u64 size, u64 flags)
{
	size = PAGE_ALIGN(size);

	/* Make sure that VBOs are supported by the MMU */
	if (WARN_ON_ONCE(!kgsl_mmu_has_feature(device,
		KGSL_MMU_SUPPORT_VBO)))
		return -EOPNOTSUPP;

	kgsl_memdesc_init(device, memdesc, flags);
	atomic_set(&memdesc->priv, 0);

	memdesc->ops = &kgsl_vbo_ops;
	memdesc->size = size;

	/* Set up the interval tree and lock */
	memdesc->ranges = RB_ROOT_CACHED;
	mutex_init(&memdesc->ranges_lock);

	return 0;
}

static bool kgsl_memdesc_check_range(struct kgsl_memdesc *memdesc,
		u64 offset, u64 length)
{
	return ((offset < memdesc->size) &&
		(offset + length > offset) &&
		(offset + length) <= memdesc->size);
}

static void kgsl_sharedmem_free_bind_op(struct kgsl_sharedmem_bind_op *op)
{
	int i;

	if (IS_ERR_OR_NULL(op))
		return;

	for (i = 0; i < op->nr_ops; i++) {
		/* Decrement the vbo_count we added when creating the bind_op */
		if (op->ops[i].entry)
			atomic_dec(&op->ops[i].entry->vbo_count);

		/* Release the reference on the child entry */
		kgsl_mem_entry_put_deferred(op->ops[i].entry);
	}

	/* Release the reference on the target entry */
	kgsl_mem_entry_put_deferred(op->target);

	kvfree(op->ops);
	kfree(op);
}

struct kgsl_sharedmem_bind_op *
kgsl_sharedmem_create_bind_op(struct kgsl_process_private *private,
		u32 target_id, void __user *ranges, u32 ranges_nents,
		u64 ranges_size)
{
	struct kgsl_sharedmem_bind_op *op;
	struct kgsl_mem_entry *target;
	int ret, i;

	/* There must be at least one defined operation */
	if (!ranges_nents)
		return ERR_PTR(-EINVAL);

	/* Find the target memory entry */
	target = kgsl_sharedmem_find_id(private, target_id);
	if (!target)
		return ERR_PTR(-ENOENT);

	if (!(target->memdesc.flags & KGSL_MEMFLAGS_VBO)) {
		kgsl_mem_entry_put(target);
		return ERR_PTR(-EINVAL);
	}

	/* Make a container for the bind operations */
	op = kzalloc(sizeof(*op), GFP_KERNEL);
	if (!op) {
		kgsl_mem_entry_put(target);
		return ERR_PTR(-ENOMEM);
	}

	/*
	 * Make an array for the individual operations.  Use __GFP_NOWARN and
	 * __GFP_NORETRY to make sure a very large request quietly fails
	 */
	op->ops = kvcalloc(ranges_nents, sizeof(*op->ops),
		GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
	if (!op->ops) {
		kfree(op);
		kgsl_mem_entry_put(target);
		return ERR_PTR(-ENOMEM);
	}

	op->nr_ops = ranges_nents;
	op->target = target;

	/* Make sure process is pinned in memory before proceeding */
	atomic_inc(&private->cmd_count);
	ret = kgsl_reclaim_to_pinned_state(private);
	if (ret)
		goto err;

	for (i = 0; i < ranges_nents; i++) {
		struct kgsl_gpumem_bind_range range;
		struct kgsl_mem_entry *entry;
		u32 size;

		size = min_t(u32, sizeof(range), ranges_size);

		ret = -EINVAL;

		if (copy_from_user(&range, ranges, size)) {
			ret = -EFAULT;
			goto err;
		}

		/* The offset must be page aligned */
		if (!PAGE_ALIGNED(range.target_offset))
			goto err;

		/* The length of the operation must be aligned and non zero */
		if (!range.length || !PAGE_ALIGNED(range.length))
			goto err;

		/* Make sure the range fits in the target */
		if (!kgsl_memdesc_check_range(&target->memdesc,
			range.target_offset, range.length))
			goto err;

		/*
		 * Special case: Consider child id 0 as a special request incase of
		 * unbind. This helps to unbind the specified range (could span multiple
		 * child buffers) without supplying backing physical buffer information.
		 */
		if (range.child_id == 0 && range.op == KGSL_GPUMEM_RANGE_OP_UNBIND) {
			op->ops[i].entry = NULL;
			op->ops[i].start = range.target_offset;
			op->ops[i].last = range.target_offset + range.length - 1;
			/* Child offset doesn't matter for unbind. set it to 0 */
			op->ops[i].child_offset = 0;
			op->ops[i].op = range.op;

			ranges += ranges_size;
			continue;
		}

		/* Get the child object */
		op->ops[i].entry = kgsl_sharedmem_find_id(private,
			range.child_id);
		entry = op->ops[i].entry;
		if (!entry) {
			ret = -ENOENT;
			goto err;
		}

		/* Keep the child pinned in memory */
		atomic_inc(&entry->vbo_count);

		/* Make sure the child is not a VBO */
		if ((entry->memdesc.flags & KGSL_MEMFLAGS_VBO)) {
			ret = -EINVAL;
			goto err;
		}

		/*
		 * Make sure that only secure children are mapped in secure VBOs
		 * and vice versa
		 */
		if ((target->memdesc.flags & KGSL_MEMFLAGS_SECURE) !=
		    (entry->memdesc.flags & KGSL_MEMFLAGS_SECURE)) {
			ret = -EPERM;
			goto err;
		}

		/* Make sure the range operation is valid */
		if (range.op != KGSL_GPUMEM_RANGE_OP_BIND &&
			range.op != KGSL_GPUMEM_RANGE_OP_UNBIND)
			goto err;

		if (range.op == KGSL_GPUMEM_RANGE_OP_BIND) {
			if (!PAGE_ALIGNED(range.child_offset))
				goto err;

			/* Make sure the range fits in the child */
			if (!kgsl_memdesc_check_range(&entry->memdesc,
				range.child_offset, range.length))
				goto err;
		} else {
			/* For unop operations the child offset must be 0 */
			if (range.child_offset)
				goto err;
		}

		op->ops[i].entry = entry;
		op->ops[i].start = range.target_offset;
		op->ops[i].last = range.target_offset + range.length - 1;
		op->ops[i].child_offset = range.child_offset;
		op->ops[i].op = range.op;

		ranges += ranges_size;
	}

	atomic_dec(&private->cmd_count);
	init_completion(&op->comp);
	kref_init(&op->ref);

	return op;

err:
	atomic_dec(&private->cmd_count);
	kgsl_sharedmem_free_bind_op(op);
	return ERR_PTR(ret);
}

void kgsl_sharedmem_bind_range_destroy(struct kref *kref)
{
	struct kgsl_sharedmem_bind_op *op = container_of(kref,
		struct kgsl_sharedmem_bind_op, ref);

	kgsl_sharedmem_free_bind_op(op);
}

static void kgsl_sharedmem_bind_worker(struct work_struct *work)
{
	struct kgsl_sharedmem_bind_op *op = container_of(work,
		struct kgsl_sharedmem_bind_op, work);
	int i;

	for (i = 0; i < op->nr_ops; i++) {
		if (op->ops[i].op == KGSL_GPUMEM_RANGE_OP_BIND) {
			spin_lock(&op->ops[i].entry->priv->mem_lock);
			if (op->ops[i].entry->pending_free) {
				spin_unlock(&op->ops[i].entry->priv->mem_lock);
				continue;
			}
			spin_unlock(&op->ops[i].entry->priv->mem_lock);
			kgsl_memdesc_add_range(op->target,
				op->ops[i].start,
				op->ops[i].last,
				op->ops[i].entry,
				op->ops[i].child_offset);
		} else {
			kgsl_memdesc_remove_range(op->target,
				op->ops[i].start,
				op->ops[i].last,
				op->ops[i].entry);
		}
	}

	/* Wake up any threads waiting for the bind operation */
	complete_all(&op->comp);

	if (op->callback)
		op->callback(op);

	/* Put the refcount we took when scheduling the worker */
	kgsl_sharedmem_put_bind_op(op);
}

void kgsl_sharedmem_bind_ranges(struct kgsl_sharedmem_bind_op *op)
{
	/* Take a reference to the operation while it is scheduled */
	kref_get(&op->ref);

	INIT_WORK(&op->work, kgsl_sharedmem_bind_worker);
	schedule_work(&op->work);
}

struct kgsl_sharedmem_bind_fence {
	struct dma_fence base;
	spinlock_t lock;
	int fd;
	struct kgsl_sharedmem_bind_op *op;
};

static const char *bind_fence_get_driver_name(struct dma_fence *fence)
{
	return "kgsl_sharedmem_bind";
}

static const char *bind_fence_get_timeline_name(struct dma_fence *fence)
{
	return "(unbound)";
}

static void bind_fence_release(struct dma_fence *fence)
{
	struct kgsl_sharedmem_bind_fence *bind_fence = container_of(fence,
		struct kgsl_sharedmem_bind_fence, base);

	kgsl_sharedmem_put_bind_op(bind_fence->op);
	kfree(bind_fence);
}

static void
kgsl_sharedmem_bind_fence_callback(struct kgsl_sharedmem_bind_op *op)
{
	struct kgsl_sharedmem_bind_fence *bind_fence = op->data;

	dma_fence_signal(&bind_fence->base);
	dma_fence_put(&bind_fence->base);
}

static const struct dma_fence_ops kgsl_sharedmem_bind_fence_ops = {
	.get_driver_name = bind_fence_get_driver_name,
	.get_timeline_name = bind_fence_get_timeline_name,
	.release = bind_fence_release,
};

static struct kgsl_sharedmem_bind_fence *
kgsl_sharedmem_bind_fence(struct kgsl_sharedmem_bind_op *op)
{
	struct kgsl_sharedmem_bind_fence *fence;
	struct sync_file *sync_file;
	int fd;

	fence = kzalloc(sizeof(*fence), GFP_KERNEL);
	if (!fence)
		return ERR_PTR(-ENOMEM);

	spin_lock_init(&fence->lock);

	dma_fence_init(&fence->base, &kgsl_sharedmem_bind_fence_ops,
		&fence->lock, dma_fence_context_alloc(1), 0);

	fd = get_unused_fd_flags(O_CLOEXEC);
	if (fd < 0) {
		kfree(fence);
		return ERR_PTR(fd);
	}

	sync_file = sync_file_create(&fence->base);
	if (!sync_file) {
		put_unused_fd(fd);
		kfree(fence);
		return ERR_PTR(-ENOMEM);
	}

	fd_install(fd, sync_file->file);

	fence->fd = fd;
	fence->op = op;

	return fence;
}

long kgsl_ioctl_gpumem_bind_ranges(struct kgsl_device_private *dev_priv,
		unsigned int cmd, void *data)
{
	struct kgsl_process_private *private = dev_priv->process_priv;
	struct kgsl_gpumem_bind_ranges *param = data;
	struct kgsl_sharedmem_bind_op *op;
	int ret;

	/* If ranges_size isn't set, return the expected size to the user */
	if (!param->ranges_size) {
		param->ranges_size = sizeof(struct kgsl_gpumem_bind_range);
		return 0;
	}

	/* FENCE_OUT only makes sense with ASYNC */
	if ((param->flags & KGSL_GPUMEM_BIND_FENCE_OUT) &&
	    !(param->flags & KGSL_GPUMEM_BIND_ASYNC))
		return -EINVAL;

	op = kgsl_sharedmem_create_bind_op(private, param->id,
		u64_to_user_ptr(param->ranges), param->ranges_nents,
		param->ranges_size);
	if (IS_ERR(op))
		return PTR_ERR(op);

	if (param->flags & KGSL_GPUMEM_BIND_ASYNC) {
		struct kgsl_sharedmem_bind_fence *fence;

		if (param->flags & KGSL_GPUMEM_BIND_FENCE_OUT) {
			fence = kgsl_sharedmem_bind_fence(op);

			if (IS_ERR(fence)) {
				kgsl_sharedmem_put_bind_op(op);
				return PTR_ERR(fence);
			}

			op->data = fence;
			op->callback = kgsl_sharedmem_bind_fence_callback;
			param->fence_id = fence->fd;
		}

		kgsl_sharedmem_bind_ranges(op);

		if (!(param->flags & KGSL_GPUMEM_BIND_FENCE_OUT))
			kgsl_sharedmem_put_bind_op(op);

		return 0;
	}

	/*
	 * Schedule the work. All the resources will be released after
	 * the bind operation is done
	 */
	kgsl_sharedmem_bind_ranges(op);

	ret = wait_for_completion_interruptible(&op->comp);
	kgsl_sharedmem_put_bind_op(op);

	return ret;
}


============================================================
FILE: LICENSE.txt
REASON: SUBSYSTEM CONFIG: gem
============================================================
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                       51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    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 the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.


============================================================
FILE: Makefile
REASON: BUILD CONFIG
============================================================
ifeq ($(KGSL_MODULE_ROOT),)
CUR_MKFILE = $(abspath $(lastword $(MAKEFILE_LIST)))
KGSL_MODULE_ROOT = $(dir $(CUR_MKFILE))
endif

KBUILD_OPTIONS+=KGSL_PATH=$(KGSL_MODULE_ROOT)

SRC := $(shell pwd)

all:
	$(MAKE) -C $(KERNEL_SRC) M=$(SRC) modules $(KBUILD_OPTIONS)

modules_install:
	$(MAKE) M=$(SRC) -C $(KERNEL_SRC) modules_install
%:
	$(MAKE) -C $(KERNEL_SRC) M=$(M) $@ $(KBUILD_OPTIONS)
clean:
	$(MAKE) -C $(KERNEL_SRC) M=$(SRC) clean


============================================================
FILE: msm_adreno_devfreq.h
REASON: SOURCE
============================================================
/* SPDX-License-Identifier: GPL-2.0-only */
/*
 * Copyright (c) 2016-2021, The Linux Foundation. All rights reserved.
 * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
 */

#ifndef MSM_ADRENO_DEVFREQ_H
#define MSM_ADRENO_DEVFREQ_H

#include <linux/devfreq.h>
#include <linux/notifier.h>

/* Flags used to send bus modifier hint from busmon governer to driver */
#define BUSMON_FLAG_FAST_HINT		BIT(0)
#define BUSMON_FLAG_SUPER_FAST_HINT	BIT(1)
#define BUSMON_FLAG_SLOW_HINT		BIT(2)

struct device;

/* same as KGSL_MAX_PWRLEVELS */
#define MSM_ADRENO_MAX_PWRLEVELS 32

struct xstats {
	u64 ram_time;
	u64 ram_wait;
	int buslevel;
	unsigned long gpu_minfreq;
};

struct devfreq_msm_adreno_tz_data {
	struct notifier_block nb;
	struct {
		s64 total_time;
		s64 busy_time;
		u32 ctxt_aware_target_pwrlevel;
		u32 ctxt_aware_busy_penalty;
	} bin;
	struct {
		u64 total_time;
		u64 ram_time;
		u64 ram_wait;
		u64 gpu_time;
		u32 num;
		u32 max;
		u32 width;
		u32 *up;
		u32 *down;
		s32 *p_up;
		s32 *p_down;
		u32 *ib_kbps;
		bool floating;
	} bus;
	unsigned int device_id;
	bool is_64;
	bool disable_busy_time_burst;
	bool ctxt_aware_enable;
	/* Multiplier to change gpu busy status */
	u32 mod_percent;
	/* Increase IB vote on high ddr stall */
	bool fast_bus_hint;
};

struct msm_adreno_extended_profile {
	struct devfreq_msm_adreno_tz_data *private_data;
	struct devfreq_dev_profile profile;
};

struct msm_busmon_extended_profile {
	u32 flag;
	u32 sampling_ms;
	unsigned long percent_ab;
	unsigned long ab_mbytes;
	struct devfreq_msm_adreno_tz_data *private_data;
	struct devfreq_dev_profile profile;
};

typedef void(*getbw_func)(unsigned long *, unsigned long *, void *);

int devfreq_vbif_update_bw(void);
void devfreq_vbif_register_callback(getbw_func func, void *data);

#if defined(QCOM_KGSL_SKIP_MSM_GOVERNORS)
static inline int msm_adreno_tz_reinit(struct devfreq *devfreq)
{
	return 0;
}
#else
int msm_adreno_tz_reinit(struct devfreq *devfreq);
#endif

#if defined(CONFIG_QTEE_SHM_BRIDGE)
#include <linux/qtee_shmbridge.h>
#else
struct qtee_shm {
	phys_addr_t paddr;
	void *vaddr;
	size_t size;
};

static inline bool qtee_shmbridge_is_enabled(void)
{
	return false;
}
static inline int32_t qtee_shmbridge_allocate_shm(size_t size, struct qtee_shm *shm)
{
	return -EINVAL;
}
static inline void qtee_shmbridge_free_shm(struct qtee_shm *shm) { }
#endif

#if IS_ENABLED(CONFIG_QCOM_KGSL_UPSTREAM) && !IS_ENABLED(CONFIG_QCOM_SCM_ADDON)
static inline int qcom_scm_io_reset(void)
{
	return -EINVAL;
}

static inline int qcom_scm_dcvs_reset(void)
{
	return -EINVAL;
}

static inline int qcom_scm_dcvs_update(int level, s64 total_time, s64 busy_time)
{
	return -EINVAL;
}

static inline int qcom_scm_dcvs_update_v2(int level, s64 total_time, s64 busy_time)
{
	return -EINVAL;
}

static inline int qcom_scm_dcvs_update_ca_v2(int level, s64 total_time, s64 busy_time,
				      int context_count)
{
	return -EINVAL;
}

static inline bool qcom_scm_dcvs_core_available(void)
{
	return false;
}

static inline int qcom_scm_dcvs_init_v2(phys_addr_t addr, size_t size, int *version)
{
	return -EINVAL;
}

static inline bool qcom_scm_dcvs_ca_available(void)
{
	return false;
}

static inline int qcom_scm_dcvs_init_ca_v2(phys_addr_t addr, size_t size)
{
	return -EINVAL;
}
#endif

#endif


============================================================
FILE: README.md
REASON: SUBSYSTEM CONFIG: gem
============================================================
# KGSL (Kernel Graphics Support Layer) Driver

This repository contains the source code of KGSL driver for the Adreno family
of GPUs. Required to use hardware accelerated OpenGL, compute and Vulkan on
Qualcomm Snapdragon targets.

KGSL is responsible for:
- GPU memory management
- Command submission to GPU
- GPU Power management
- Providing debug and profiling interface to userspace

# Branches

Primary development branch: gfx-kernel.le.0.0

# How-to-Build

This source code can be built using recipe file related to kgsl in meta-qcom
project, which is designed for Qualcomm-based platforms.

Steps for compilation:
- Modify the KGSL driver code as required and generate a corresponding patch
  file.
- Git clone meta-qcom project https://github.com/qualcomm-linux/meta-qcom.git .
- Integrate the patch into the kgsl related recipe file located at
  meta-qcom/recipes-graphics.
- Compile the project. Please refer to the README.md file provided in the
  meta-qcom repository.

# Getting in Contact

Problems specific to the KGSL driver can be reported in the Issues section of
this repository.

# License
This driver is released under the GPL-2.0 license. See LICENSE.txt for details.

