/*
 * Copyright (c) 2025, Arm Limited. All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <arch.h>
#include <asm_macros.S>
#include <platform_def.h>

	.global plat_arm_calc_core_pos
	.global plat_report_exception
	.global plat_my_core_pos
	.global plat_is_my_cpu_primary

	/* ---------------------------------------------------------------------
	 * unsigned int plat_arm_calc_core_pos(u_register_t mpidr)
	 *
	 * Function to calculate the core position.
	 *
	 * (ClusterId * PLAT_MAX_CPUS_PER_CLUSTER * PLAT_MAX_PE_PER_CPU) +
	 * (CPUId * PLAT_MAX_PE_PER_CPU) + ThreadId
	 *
	 * which can be simplified as:
	 *
	 * ((ClusterId * PLAT_MAX_CPUS_PER_CLUSTER + CPUId) * PLAT_MAX_PE_PER_CPU)
	 * + ThreadId
	 * ---------------------------------------------------------------------
	 */
func plat_arm_calc_core_pos
	/*
	 * Check for MT bit in MPIDR. If not set, shift MPIDR to left to make it
	 * look as if in a multi-threaded implementation.
	 */
	tst	x0, #MPIDR_MT_MASK
	lsl	x3, x0, #MPIDR_AFFINITY_BITS
	csel	x3, x3, x0, eq

	/* Extract individual affinity fields from MPIDR */
	ubfx	x0, x3, #MPIDR_AFF0_SHIFT, #MPIDR_AFFINITY_BITS
	ubfx	x1, x3, #MPIDR_AFF1_SHIFT, #MPIDR_AFFINITY_BITS
	ubfx	x2, x3, #MPIDR_AFF2_SHIFT, #MPIDR_AFFINITY_BITS

	/* Compute linear position */
	mov	x4, #PLAT_MAX_CPUS_PER_CLUSTER
	madd	x1, x2, x4, x1
	mov	x4, #PLAT_MAX_PE_PER_CPU
	madd	x0, x1, x4, x0
	ret
endfunc plat_arm_calc_core_pos

func plat_report_exception
	ret
endfunc plat_report_exception

	/* ---------------------------------------------------------------------
	 * unsigned int plat_my_core_pos(void)
	 * This function uses the plat_arm_calc_core_pos()
	 * definition to get the index of the calling CPU.
	 * ---------------------------------------------------------------------
	 */
func plat_my_core_pos
	mrs	x0, mpidr_el1
	b	plat_arm_calc_core_pos
endfunc plat_my_core_pos

	/* ---------------------------------------------------------------------
	 * unsigned int plat_is_my_cpu_primary (void);
	 *
	 * Find out whether the current cpu is the primary cpu
	 * ---------------------------------------------------------------------
	 */
#if CSS_USE_SCMI_SDS_DRIVER
func plat_is_my_cpu_primary
	mov	x9, x30
	bl	plat_my_core_pos
	cmp	x0, #RDASPEN_PRIMARY_CPU
	cset	w0, eq
	ret	x9
endfunc plat_is_my_cpu_primary
#endif
