Trusted Firmware-A · source analysis

PSCI CPU_ON과 suspend 상태

Linux의 PSCI 요청을 TF-A의 CPU_ON·CPU_OFF·CPU_SUSPEND 처리와 연결합니다. HVC를 사용하는 경우에는 EL2의 PSCI 구현 또는 중계 경로를 구별합니다.

표의 버전은 소스 분석 기준이며 최신 보안 버전 권고가 아닙니다. TF-A LTS 2.14.3 이후에는 보안 수정이 있습니다. 제품 적용 시 공식 변경 기록과 사용 플랫폼의 errata를 확인하세요.

Series
09 / 12
Baseline
LTS 2.14.3
Commit
f5e765a3443f
Source
lib/psci/psci_on.c:62-154 (발췌 범위)

Linux CPU_ON 요청부터 새 CPU의 online까지

Linux v6.18.37 ARM64의 CPU_ON 호출에서 x1은 cpu_logical_map(cpu), x2는 secondary_entry의 물리 주소, x3은 context_id 0입니다. idle 태스크 포인터는 x3가 아니라 secondary_data.task에 따로 저장합니다. 펌웨어의 성공 반환 뒤에도 Linux는 새 CPU의 완료 통지와 online 상태를 확인합니다.

TF-A LTS 2.14.3은 대상 CPU의 잠금을 사용해 상태 검사와 ON_PENDING 전이를 보호합니다. warm boot에서는 CPU_ON과 suspend 복귀를 나누고, cm_init_my_context로 비보안 context를 준비합니다. HVC 경로는 EL2의 구현·중계를 구별해야 하며 HVC가 TF-A EL3에 직접 들어가는 명령은 아닙니다.

양쪽 코드를 이어서 읽기

CPU_ON의 성공과 대상 CPU의 실행은 언제 일치하는가?

Linux가 선택한 PSCI conduit가 SMC이면 TF-A BL31의 PSCI handler에 들어간다. HVC이면 먼저 EL2의 구현 또는 중계에 들어가므로, 같은 EL3 경로를 무조건 가정할 수 없다.

CPU_ON은 대상 MPIDR와 비보안 진입 정보를 확인하고 대상 CPU 잠금 아래 OFF를 ON_PENDING으로 바꾼 뒤 플랫폼의 pwr_domain_on()을 호출한다. 성공 반환은 요청 수락이지 대상 CPU의 Linux online 완료 통지가 아니다. CPU_OFF와 CPU_SUSPEND는 호출 CPU 자체의 전원 경로이며 반환·재진입 규칙도 다르다.

conduit, per-CPU 상태, 플랫폼 hook의 경계

그림 1. PSCI 호출이 지나가는 네 경계와 저장되는 값
Normal WorldEL3 PSCI core플랫폼·대상 CPU
01 · 선택Linux conduit
SMC 또는 HVC
02 · 분기BL31 SMC handler
PSCI function ID
03 · 상태CPU별 affinity 상태
warmboot_ep_info
04 · 실행plat_psci_ops
power domain hook
경계

HVC는 EL2로 들어간다. 02–04는 EL2가 PSCI를 TF-A EL3로 중계하는 경우에만 이어진다.

CPU_ON의 warmboot_ep_info는 대상 CPU별 진입 정보를 담는다. psci_power_state_t는 suspend의 도메인별 요청·복귀 상태를 담는 별도 객체다. 플랫폼 hook의 실제 register·mailbox 작업은 보드 구현에 달려 있다.

CPU_ON: 요청 수락과 대상 CPU 완료를 나눠 읽기

그림 2. SMC conduit일 때 CPU_ON의 호출 CPU와 대상 CPU 경로
Linux
CPU_ON · SMC
MPIDR·entrypoint 검증
warmboot_ep_info 준비
대상 CPU lock
OFF → ON_PENDING
pwr_domain_on()
성공 또는 OFF 복구
대상 warmboot
ON 전이 · NS 진입

04의 성공은 caller에 반환된다. 05는 다른 CPU에서 독립적으로 진행되므로 반환 순간에 이미 끝났을 수도, 아직 ON_PENDING일 수도 있다. 실패하면 TF-A는 대상 affinity를 OFF로 되돌린다. psci_cpu_on_finish()는 대상 경로의 별도 함수다.

세 PSCI 호출의 반환·복귀 계약

같은 SMC handler에서 분기해도 대상과 성공 후 위치는 다르다. LTS 2.14.3의 generic PSCI 경로를 기준으로 한다.

호출먼저 확인하는 값핵심 상태·플랫폼 동작성공 후 관찰
CPU_ON대상 MPIDR와 NS entrypoint, 대상 affinity OFF대상 잠금 아래 ON_PENDING, pwr_domain_on(); 실패 시 OFF 복구caller에 SUCCESS 반환 가능. 대상은 별도 warmboot 뒤 ON·NS 진입. Linux online은 그 이후 확인
CPU_OFF호출 CPU와 도메인 전원 상태psci_do_cpu_off()가 자신과 가능한 상위 도메인을 끔성공하면 원래 호출 위치로 돌아오지 않음. 거부 시 PSCI_E_DENIED 반환
CPU_SUSPEND · standbypower_state의 retention 요청CPU local state를 retention으로 두고 cpu_standby() 호출깨어나면 RUN으로 복구하고 원래 호출로 SUCCESS 반환
CPU_SUSPEND · power-downpower_state, NS 재진입 주소·context_idpsci_cpu_suspend_start()와 플랫폼 suspend hook전원 차단 후 wake는 warmboot. 중단·거부되면 원래 호출로 돌아올 수 있음

AFFINITY_INFO의 OFF·ON_PENDING·ON은 관찰용 affinity 상태이며 Linux의 online 플래그나 전원 레지스터의 즉시 값과 동일하지 않다.

다른 두 경로와 warmboot의 갈림길

CPU_ON은 다른 CPU를 시작한다. CPU_OFF와 CPU_SUSPEND는 호출한 CPU의 전원을 바꾼다. 같은 화살표 하나로 그리면 성공 반환 위치가 잘못 읽힌다.

그림 3. CPU_OFF와 CPU_SUSPEND의 다른 완료 조건

CPU_OFF · 현재 CPU

01psci_cpu_off()

02psci_do_cpu_off(PLAT_MAX_PWR_LVL)

03성공: 호출로 돌아오지 않음

04거부: PSCI_E_DENIED 반환

CPU_SUSPEND · 현재 CPU

01power_state 해석·수준 검증

02standby: cpu_standby() 뒤 RUN 복구

03power-down: 재진입 정보 후 suspend_start()

04wake는 warmboot; 중단되면 복귀 가능

그림 4. CPU_ON 완료와 suspend 복귀가 갈라지는 warmboot

psci_warmboot_entrypoint()는 affinity가 OFF이면 오류로 처리하고 ON_PENDING인지 확인해 두 finisher를 구분한다.

ON_PENDING · CPU_ON 대상

01psci_cpu_on_finish()

02platform pwr_domain_on_finish()

03필요한 cache·GIC·arch 설정

04NS context, domain RUN·affinity ON

ON · suspend power-down 복귀

01max_off_lvl 확인

02psci_cpu_suspend_to_powerdown_finish()

03platform suspend_finish() 등 복구

04NS context, domain RUN 유지·갱신

원본 코드

원문 Trusted Firmware-A LTS 2.14.3 · lib/psci/psci_on.c의 62–154행입니다.

commitf5e765a3443fe21154aa908228e75ee2600085f6anchor · L62int psci_cpu_on_start(u_register_t target_cpu,
62int psci_cpu_on_start(u_register_t target_cpu,
63		      const entry_point_info_t *ep)
64{
65	int rc;
66	aff_info_state_t target_aff_state;
67	unsigned int target_idx = (unsigned int)plat_core_pos_by_mpidr(target_cpu);
68
69	/*
70	 * This function must only be called on platforms where the
71	 * CPU_ON platform hooks have been implemented.
72	 */
73	assert((psci_plat_pm_ops->pwr_domain_on != NULL) &&
74	       (psci_plat_pm_ops->pwr_domain_on_finish != NULL));
75
76	/* Protect against multiple CPUs trying to turn ON the same target CPU */
77	psci_spin_lock_cpu(target_idx);
78
79	/*
80	 * Generic management: Ensure that the cpu is off to be
81	 * turned on.
82	 * Perform cache maintanence ahead of reading the target CPU state to
83	 * ensure that the data is not stale.
84	 * There is a theoretical edge case where the cache may contain stale
85	 * data for the target CPU data - this can occur under the following
86	 * conditions:
87	 * - the target CPU is in another cluster from the current
88	 * - the target CPU was the last CPU to shutdown on its cluster
89	 * - the cluster was removed from coherency as part of the CPU shutdown
90	 *
91	 * In this case the cache maintenace that was performed as part of the
92	 * target CPUs shutdown was not seen by the current CPU's cluster. And
93	 * so the cache may contain stale data for the target CPU.
94	 */
95	flush_cpu_data_by_index(target_idx, psci_svc_cpu_data);
96	rc = cpu_on_validate_state(psci_get_aff_info_state_by_idx(target_idx));
97	if (rc != PSCI_E_SUCCESS) {
98		goto on_exit;
99	}
100
101	/*
102	 * Call the cpu on handler registered by the Secure Payload Dispatcher
103	 * to let it do any bookeeping. If the handler encounters an error, it's
104	 * expected to assert within
105	 */
106	if ((psci_spd_pm != NULL) && (psci_spd_pm->svc_on != NULL)) {
107		psci_spd_pm->svc_on(target_cpu);
108	}
109
110	/*
111	 * Set the Affinity info state of the target cpu to ON_PENDING.
112	 * Flush aff_info_state as it will be accessed with caches
113	 * turned OFF.
114	 */
115	psci_set_aff_info_state_by_idx(target_idx, AFF_STATE_ON_PENDING);
116	flush_cpu_data_by_index(target_idx, psci_svc_cpu_data);
117
118	/*
119	 * The cache line invalidation by the target CPU after setting the
120	 * state to OFF (see psci_do_cpu_off()), could cause the update to
121	 * aff_info_state to be invalidated. Retry the update if the target
122	 * CPU aff_info_state is not ON_PENDING.
123	 */
124	target_aff_state = psci_get_aff_info_state_by_idx(target_idx);
125	if (target_aff_state != AFF_STATE_ON_PENDING) {
126		assert(target_aff_state == AFF_STATE_OFF);
127		psci_set_aff_info_state_by_idx(target_idx, AFF_STATE_ON_PENDING);
128		flush_cpu_data_by_index(target_idx, psci_svc_cpu_data);
129
130		assert(psci_get_aff_info_state_by_idx(target_idx) ==
131		       AFF_STATE_ON_PENDING);
132	}
133
134	/*
135	 * Perform generic, architecture and platform specific handling.
136	 */
137	/*
138	 * Plat. management: Give the platform the current state
139	 * of the target cpu to allow it to perform the necessary
140	 * steps to power on.
141	 */
142	rc = psci_plat_pm_ops->pwr_domain_on(target_cpu);
143	assert((rc == PSCI_E_SUCCESS) || (rc == PSCI_E_INTERN_FAIL));
144
145	if (rc != PSCI_E_SUCCESS) {
146		/* Restore the state on error. */
147		psci_set_aff_info_state_by_idx(target_idx, AFF_STATE_OFF);
148		flush_cpu_data_by_index(target_idx, psci_svc_cpu_data);
149	}
150
151on_exit:
152	psci_spin_unlock_cpu(target_idx);
153	return rc;
154}

발췌 범위와 읽기 기준

원문 62–154행의 psci_cpu_on_start()은 대상 CPU 잠금 아래에서 affinity 상태를 확인하고, ON_PENDING을 기록한 뒤 플랫폼의 전원 켜기 함수를 호출합니다. 실패하면 OFF로 되돌립니다. AArch64 Linux의 SMC64 진입 분기는 psci_main.c 546행 이후에서 확인합니다.

PSCI 반환값과 실제 hardware 전원 상태는 같은 시점에 바뀌지 않는다. pending, on, off state와 cache/coherency 경계를 따로 기록한다.

함께 읽어야 하는 원본 코드

첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.

01. target CPU의 affinity state를 바꾸는 CPU_ON

lib/psci/psci_main.c 15-105줄이다.

filelib/psci/psci_main.canchor · L25int psci_cpu_on(u_register_t target_cpu
15#include <lib/runtime_instr.h>
16#include <lib/smccc.h>
17#include <plat/common/platform.h>
18#include <services/arm_arch_svc.h>
19
20#include "psci_private.h"
21
22/*******************************************************************************
23 * PSCI frontend api for servicing SMCs. Described in the PSCI spec.
24 ******************************************************************************/
25int psci_cpu_on(u_register_t target_cpu,
26		uintptr_t entrypoint,
27		u_register_t context_id)
28
29{
30	int rc;
31	entry_point_info_t *ep = NULL;
32	unsigned int target_idx = (unsigned int)plat_core_pos_by_mpidr(target_cpu);
33
34	/* Validate the target CPU */
35	if (!is_valid_mpidr(target_cpu)) {
36		return PSCI_E_INVALID_PARAMS;
37	}
38
39	ep = get_cpu_data_by_index(target_idx, warmboot_ep_info);
40	/* Validate the lower EL entry point and put it in the entry_point_info */
41	rc = psci_validate_entry_point(ep, entrypoint, context_id);
42	if (rc != PSCI_E_SUCCESS) {
43		return rc;
44	}
45
46	/*
47	 * To turn this cpu on, specify which power
48	 * levels need to be turned on
49	 */
50	return psci_cpu_on_start(target_cpu, ep);
51}
52
53unsigned int psci_version(void)
54{
55	return PSCI_MAJOR_VER | PSCI_MINOR_VER;
56}
57
58int psci_cpu_suspend(unsigned int power_state,
59		     uintptr_t entrypoint,
60		     u_register_t context_id)
61{
62	int rc;
63	unsigned int target_pwrlvl, is_power_down_state;
64	psci_power_state_t state_info = { {PSCI_LOCAL_STATE_RUN} };
65	plat_local_state_t cpu_pd_state;
66	unsigned int cpu_idx = plat_my_core_pos();
67
68	/* Validate the power_state parameter */
69	rc = psci_validate_power_state(power_state, &state_info);
70	if (rc != PSCI_E_SUCCESS) {
71		assert(rc == PSCI_E_INVALID_PARAMS);
72		return rc;
73	}
74
75	/*
76	 * Get the value of the state type bit from the power state parameter.
77	 */
78	is_power_down_state = psci_get_pstate_type(power_state);
79
80	/* Sanity check the requested suspend levels */
81	assert(psci_validate_suspend_req(&state_info, is_power_down_state)
82			== PSCI_E_SUCCESS);
83
84	target_pwrlvl = psci_find_target_suspend_lvl(&state_info);
85	if (target_pwrlvl == PSCI_INVALID_PWR_LVL) {
86		ERROR("Invalid target power level for suspend operation\n");
87		panic();
88	}
89
90	/* Fast path for local CPU standby, won't interact with higher power levels. */
91	if (is_cpu_standby_req(is_power_down_state, target_pwrlvl)) {
92		if  (psci_plat_pm_ops->cpu_standby == NULL) {
93			return PSCI_E_INVALID_PARAMS;
94		}
95
96		/*
97		 * Set the state of the CPU power domain to the platform
98		 * specific retention state and enter the standby state.
99		 */
100		cpu_pd_state = state_info.pwr_domain_state[PSCI_CPU_PWR_LVL];
101		psci_set_cpu_local_state(cpu_pd_state);
102
103#if ENABLE_PSCI_STAT
104		plat_psci_stat_accounting_start(&state_info);
105#endif

02. CPU와 상위 power domain의 suspend state 처리

lib/psci/psci_main.c 48-158줄이다.

filelib/psci/psci_main.canchor · L58int psci_cpu_suspend(unsigned int power_state
48	 * levels need to be turned on
49	 */
50	return psci_cpu_on_start(target_cpu, ep);
51}
52
53unsigned int psci_version(void)
54{
55	return PSCI_MAJOR_VER | PSCI_MINOR_VER;
56}
57
58int psci_cpu_suspend(unsigned int power_state,
59		     uintptr_t entrypoint,
60		     u_register_t context_id)
61{
62	int rc;
63	unsigned int target_pwrlvl, is_power_down_state;
64	psci_power_state_t state_info = { {PSCI_LOCAL_STATE_RUN} };
65	plat_local_state_t cpu_pd_state;
66	unsigned int cpu_idx = plat_my_core_pos();
67
68	/* Validate the power_state parameter */
69	rc = psci_validate_power_state(power_state, &state_info);
70	if (rc != PSCI_E_SUCCESS) {
71		assert(rc == PSCI_E_INVALID_PARAMS);
72		return rc;
73	}
74
75	/*
76	 * Get the value of the state type bit from the power state parameter.
77	 */
78	is_power_down_state = psci_get_pstate_type(power_state);
79
80	/* Sanity check the requested suspend levels */
81	assert(psci_validate_suspend_req(&state_info, is_power_down_state)
82			== PSCI_E_SUCCESS);
83
84	target_pwrlvl = psci_find_target_suspend_lvl(&state_info);
85	if (target_pwrlvl == PSCI_INVALID_PWR_LVL) {
86		ERROR("Invalid target power level for suspend operation\n");
87		panic();
88	}
89
90	/* Fast path for local CPU standby, won't interact with higher power levels. */
91	if (is_cpu_standby_req(is_power_down_state, target_pwrlvl)) {
92		if  (psci_plat_pm_ops->cpu_standby == NULL) {
93			return PSCI_E_INVALID_PARAMS;
94		}
95
96		/*
97		 * Set the state of the CPU power domain to the platform
98		 * specific retention state and enter the standby state.
99		 */
100		cpu_pd_state = state_info.pwr_domain_state[PSCI_CPU_PWR_LVL];
101		psci_set_cpu_local_state(cpu_pd_state);
102
103#if ENABLE_PSCI_STAT
104		plat_psci_stat_accounting_start(&state_info);
105#endif
106
107#if ENABLE_RUNTIME_INSTRUMENTATION
108		PMF_CAPTURE_TIMESTAMP(rt_instr_svc,
109		    RT_INSTR_ENTER_HW_LOW_PWR,
110		    PMF_NO_CACHE_MAINT);
111#endif
112
113		psci_plat_pm_ops->cpu_standby(cpu_pd_state);
114
115		/* Upon exit from standby, set the state back to RUN. */
116		psci_set_cpu_local_state(PSCI_LOCAL_STATE_RUN);
117
118#if ENABLE_RUNTIME_INSTRUMENTATION
119		PMF_CAPTURE_TIMESTAMP(rt_instr_svc,
120		    RT_INSTR_EXIT_HW_LOW_PWR,
121		    PMF_NO_CACHE_MAINT);
122#endif
123
124#if ENABLE_PSCI_STAT
125		plat_psci_stat_accounting_stop(&state_info);
126
127		/* Update PSCI stats */
128		psci_stats_update_pwr_up(cpu_idx, PSCI_CPU_PWR_LVL, &state_info);
129#endif
130
131		return PSCI_E_SUCCESS;
132	}
133
134	/*
135	 * If a power down state has been requested, we need to verify entry
136	 * point and program entry information.
137	 */
138	if (is_power_down_state != 0U) {
139		entry_point_info_t *ep = get_cpu_data_by_index(cpu_idx, warmboot_ep_info);
140
141		rc = psci_validate_entry_point(ep, entrypoint, context_id);
142		if (rc != PSCI_E_SUCCESS) {
143			return rc;
144		}
145	}
146
147	/*
148	 * Do what is needed to enter the power down state. Upon success,
149	 * enter the final wfi which will power down this CPU. This function
150	 * might return if the power down was abandoned for any reason, e.g.
151	 * arrival of an interrupt
152	 */
153	rc = psci_cpu_suspend_start(cpu_idx,
154				    target_pwrlvl,
155				    &state_info,
156				    is_power_down_state);
157
158	return rc;

소스에서 경계를 확인하는 순서

01

Linux conduit

set_conduit()는 SMC/HVC 함수를 고른다. SMC면 EL3 PSCI handler를, HVC면 EL2 구현·중계를 먼저 추적한다.

02

CPU_ON 진입 정보

psci_cpu_on()은 MPIDR와 entrypoint를 검증하고 CPU별 warmboot_ep_info를 준비한다. psci_cpu_on_start()는 대상 잠금 아래 affinity를 검사한다. 이미 ON이면 ALREADY_ON, ON_PENDING이면 ON_PENDING 오류를 돌려준다.

03

플랫폼 요청과 복구

ON_PENDING을 게시한 뒤 pwr_domain_on(target_cpu)을 호출한다. 플랫폼 hook 실패 시 OFF로 복구한다. 성공 반환은 target warmboot와 Linux online을 기다리는 API가 아니다.

04

OFF와 SUSPEND

CPU_OFF의 성공은 비복귀다. CPU_SUSPEND의 standby는 원래 호출로 돌아와 local state를 RUN으로 바꾼다. power-down wake는 warmboot finisher로 돌아온다.

05

AFFINITY_INFO

TF-A는 다른 cluster의 오래된 cache line을 고려해 대상 per-CPU data를 정리한 뒤 affinity를 읽는다. 이 값과 Linux online·전원 register·CPU_ON 반환을 한 시점의 상태로 합치지 않는다.

반환값만으로 알 수 없는 부분

01

ON_PENDING은 완료 표시가 아니다

psci_cpu_on_start()가 ON_PENDING을 기록하고 cache에 반영한 뒤 플랫폼 pwr_domain_on()을 호출한다. 대상은 별도로 warmboot에 진입한다. psci_set_pwr_domains_to_run()에서 affinity가 ON으로 바뀌므로 CPU_ON SUCCESS, AFFINITY_INFO ON, Linux online은 세 관찰점이다.

02

두 warmboot 분기

psci_warmboot_entrypoint()는 affinity ON_PENDING이면 새 CPU 시작, ON이면 suspend 복귀를 고른다. 둘 다 저장된 비보안 진입 정보로 context를 만든다. psci_power_state_t는 도메인 상태 추적에 쓰이며 CPU_ON frontend의 첫 입력 객체가 아니다.

03

플랫폼별 hook

pwr_domain_on, pwr_domain_on_finish, cpu_standby, pwr_domain_suspend의 register·mailbox·GIC 처리는 보드가 제공한다. 구체적인 전원 register 순서는 플랫폼 소스로 확인한다.

레지스터에서 오류 판정까지 상세 분석

PSCI는 Linux의 CPU hotplug 요청을 power controller register write 하나로 바꾸는 함수가 아니다. 대상 CPU별 잠금으로 affinity 상태 변경을 보호하고, cache 일관성과 플랫폼 전원 상태를 준비한 뒤 새 CPU가 지정한 비보안 진입 주소에서 시작하도록 합니다. warm entry 설정 방식은 플랫폼에 따라 다릅니다.

CPU_ON의 성공 반환은 target CPU가 이미 kernel entry를 실행했다는 뜻이 아니다. 요청을 accepted/pending 상태로 만든 시점과 실제 power-on, coherency join, warm boot context 복원 완료를 분리해 측정해야 한다.

그림 5. CPU_ON에 한정한 인자와 affinity 상태 계약
01x0

CPU_ON의 지원 function ID여야 한다.

02x1 target_cpu

MPIDR affinity가 platform topology의 존재하는 CPU를 가리켜야 한다.

03x2 entrypoint

허용된 non-secure executable address이고 alignment를 만족해야 한다.

04x3 context_id

PSCI 호출자가 정한 값이며 AArch64 대상 진입의 x0로 전달됩니다. 이 Linux CPU_ON 경로는 0을 넘깁니다.

05대상 affinity 상태

CPU_ON은 OFF → ON_PENDING으로 요청을 게시하고, 대상 warmboot 뒤 ON으로 갱신합니다.

x1–x3의 이 의미는 CPU_ON 전용이다. CPU_OFF에는 target MPIDR·entrypoint 인자가 없고 CPU_SUSPEND의 x1은 power_state다. SMC32/SMC64 분기도 확인한다.

진입 레지스터와 메모리 계약

아래 x1–x3 표는 CPU_ON에 한정한다. CPU_OFF와 CPU_SUSPEND에 같은 인자 이름을 적용하지 않는다.

#입력 상태생산자정상 조건확인 이유
01x0Linux PSCI conduitCPU_ON의 지원 function ID여야 한다.PSCI handler 분기를 선택한다.
02x1 target_cpuCPU_ON callerMPIDR affinity가 platform topology의 존재하는 CPU를 가리켜야 한다.per-CPU state와 power domain path를 선택한다.
03x2 entrypointNormal World허용된 non-secure executable address이고 alignment를 만족해야 한다.target CPU warm entry 뒤 최종 PC가 된다.
04x3 context_idNormal WorldPSCI 호출자가 정한 값이며 AArch64 대상 진입의 x0로 전달됩니다. 이 Linux CPU_ON 경로는 0을 넘깁니다.호출자가 정한 시작 인자입니다. Linux는 idle 태스크 주소를 이 값으로 전달하지 않습니다.
05affinity 상태와 local power statePSCI per-CPU dataaffinity의 OFF/ON_PENDING/ON과 전원 도메인의 RUN/RETENTION/OFF를 구분합니다.대상 잠금으로 중복 요청을 직렬화합니다.

핵심 구조체 필드의 생산자, 소비자와 수명

구조체 이름만 나열하지 않고 어떤 코드가 값을 쓰고, 어느 코드가 처음 읽으며, 언제까지 주소와 내용이 유지되어야 하는지 구분했다.

#객체 또는 필드생산자소비자수명과 불변 조건
01psci_power_state_tSUSPEND decode 또는 warmboot domain snapshotsuspend hook·warmboot finisher요청 또는 복귀의 domain별 local state를 담는다.
02affinity_info_statePSCI coreCPU_ON/AFFINITY_INFOCPU_ON은 대상 잠금에서 전이하며 관측 전에 cache flush를 한다.
03psci_svc_cpu_dataPSCI setup·CPU_ON대상 warmboot와 AFFINITY_INFOCPU별 affinity와 warmboot entry information을 보관한다.
04plat_psci_ops_tplatform setupPSCI coreBL31 runtime 동안 유지되는 callback table이며 필수 op 조합이 검증돼야 한다.
05power domain treeplatform topologycoordination codeCPU-cluster-system level path와 affinity count가 일치해야 한다.
06warmboot_ep_infoCPU_ON entrypoint 검증대상 CPU의 NS context 준비구체적인 reset mailbox 방식은 플랫폼별이다.

함수 내부 실행 순서

소스의 큰 분기와 side effect를 실행 순서대로 다시 펼쳤다. breakpoint는 이 목록의 경계에 두고, 다음 번호로 넘어갈 때 새로 유효해진 객체를 기록한다.

  1. 01

    SMC dispatcher가 PSCI OEN과 function ID를 확인하고 x1-x3를 psci_smc_handler에 전달한다.

  2. 02

    CPU_ON 분기는 대상 MPIDR와 NS entrypoint를 검증한다. CPU_OFF·SUSPEND는 각각 다른 인자를 해석한다.

  3. 03

    CPU_ON의 MPIDR를 target index로 바꾸고 CPU별 entry information을 준비한다.

  4. 04

    psci_cpu_on은 전원 시작 함수 호출 전에 entrypoint와 context_id를 warmboot_ep_info에 준비합니다. 새 CPU는 coherency 준비 뒤 이를 읽어 자신의 비보안 context를 만듭니다.

  5. 05

    psci_cpu_on_start가 대상 CPU의 psci_spin_lock_cpu를 잡고 상태를 검사한 뒤 ON_PENDING으로 바꿉니다. 이 버전은 이 경로에서 compare-exchange 대신 잠금을 사용합니다.

  6. 06

    플랫폼의 pwr_domain_on 콜백이 전원 켜기를 요청합니다. reset·clock·전원 제어의 세부 순서는 SoC마다 다릅니다.

  7. 07

    대상 warmboot entry는 affinity로 CPU_ON 완료와 suspend 복귀를 구별한 뒤 플랫폼별 finisher와 필요한 cache·GIC 작업을 수행한다.

  8. 08

    새 CPU가 cm_init_my_context와 cm_prepare_el3_exit_ns로 비보안 진입을 준비하고 psci_set_pwr_domains_to_run으로 affinity ON·domain RUN을 반영합니다.

  9. 09

    AFFINITY_INFO와 Linux 로그를 이용해 accepted 시점부터 online 완료까지 지연과 실패 위치를 분리한다.

빌드 설정이 바꾸는 실제 코드 경로

동일한 함수 이름이라도 아래 설정에 따라 포함되는 source, 구조체 크기, 인자 의미와 failure path가 달라진다.

#설정바뀌는 동작확인 방법
01PLAT_MAX_PWR_LVLsuspend coordination에서 다루는 최상위 domain을 정한다.topology descriptor와 power_state 배열 크기를 비교한다.
02PSCI_EXTENDED_STATE_IDpower state parameter의 bit encoding을 바꾼다.Linux DT의 PSCI/idle-state 값과 decode 결과를 맞춘다.
03ENABLE_PSCI_STATresidency/count 통계를 유지한다.timestamp source와 suspend entry/exit update 위치를 확인한다.
04HW_ASSISTED_COHERENCYcache flush와 coherency exit/entry 책임이 달라진다.platform callback에서 생략 가능한 maintenance를 구분한다.

증상에서 최초 불일치 지점까지 추적하기

마지막 panic 메시지가 아니라 어디에서 멈추고 무엇을 읽어 어떤 결론을 내릴지 정리했다. 정상값과 실패값은 같은 build와 같은 위치에서 비교한다.

#관찰 증상중단 위치기록할 값판정
01CPU_ON은 SUCCESS인데 CPU가 online되지 않음cpu_on callback과 secondary reset vectoraffinity state, power register, target PCrequest accepted 이후 hardware release 또는 warm entry 문제를 찾는다.
02두 번째 CPU_ON에서 ALREADY_ON/ON_PENDING 고착대상 CPU 잠금과 affinity 상태 검사old/new state와 첫 요청 timestamp첫 요청 cleanup 또는 secondary completion 누락을 확인한다.
03suspend 뒤 오래된 mailbox 실행power-down 직전과 warm entryentrypoint/context_id cache linecache flush 또는 per-CPU slot 계산 오류를 판정한다.
04cluster suspend에서만 hangdomain coordination과 platform suspend oplevel별 local/target state, sibling counttopology 또는 last-man 판단 race를 찾는다.

상태가 보관되는 위치

대상쓰기·준비읽기·완료주의할 점
warmboot_ep_infoCPU_ON·power-down SUSPEND의 entrypoint 검증대상/복귀 CPU의 cm_init_my_context()CPU별 진입 정보, Linux task 포인터와 다름
aff_info_stateCPU_ON의 대상 잠금 아래 ON_PENDING; warmboot에서 ON중복 검사·AFFINITY_INFOstale cache를 고려한 flush 있음
psci_power_state_tSUSPEND domain state decode; warmboot 복귀 state플랫폼 suspend hook과 finisherCPU_ON 호출의 첫 입력 객체가 아님
plat_psci_ops_tplatform PSCI setupgeneric PSCI coreregister·mailbox 순서는 플랫폼별

오류 코드와 멈춘 단계

조건TF-A 관찰먼저 확인할 위치
이미 ON / ON_PENDING인 대상에 CPU_ONPSCI_E_ALREADY_ON / PSCI_E_ON_PENDINGcpu_on_validate_state()와 대상 잠금
pwr_domain_on() 실패대상 affinity OFF 복구 후 오류 반환플랫폼 hook 반환과 CPU별 state flush
SUCCESS 뒤 Linux online 지연요청 수락과 target warmboot 완료는 별도reset vector, on_finish, secondary entry
CPU_OFF 거부 / SUSPEND 중단OFF는 DENIED, SUSPEND는 interrupt 등으로 복귀 가능호출 CPU의 플랫폼 hook·도메인 상태

소스 밖에서 확인할 증거

소스에서 파악한 동작을 실제 빌드 결과와 대상 보드의 로그로 확인한다. 아래 명령의 보드 이름과 툴체인 접두사는 사용 중인 빌드 환경에 맞게 바꾼다.

#목적명령 또는 계측판정 기준
01빌드 산출물make PLAT=<platform> DEBUG=1 all fipBL1, BL2, BL31과 FIP가 같은 설정으로 만들어졌는지 전체 빌드 명령부터 기록한다.
02FIP 구성tools/fiptool/fiptool info build/<platform>/debug/fip.binFIP를 사용하는 플랫폼이면 BL31 이미지의 식별자·크기를 확인한다. CPU_ON runtime 동작은 FIP 목록으로 증명되지 않는다.
03심볼과 주소${CROSS_COMPILE}nm -n build/<platform>/debug/bl31/bl31.elf | grep ' psci_smc_handler$'대상 함수가 BL31의 어느 주소와 섹션에 놓였는지 확인한다.
04EL3 명령 추적${CROSS_COMPILE}objdump -drS build/<platform>/debug/bl31/bl31.elfC 코드가 EL3 system register 접근과 eret 경로로 어떻게 번역됐는지 대조한다.
05실행 시점 증거TF-A DEBUG log + CurrentEL/SCR_EL3/SPSR_EL3/x0-x3 기록어느 exception level에서 어떤 security state와 인자를 다음 이미지에 넘겼는지 serial log로 남긴다.

직접 확인할 실험

  1. 01
    수락과 online 사이

    SMC 반환, 대상의 psci_cpu_on_finish()·affinity ON, Linux secondary online을 따로 기록한다.

  2. 02
    겹친 CPU_ON 요청

    대상 잠금 아래 이전 affinity와 첫 요청의 플랫폼 반환값을 기록한다. 이미 ON/ON_PENDING인 경우와 플랫폼 실패 뒤 OFF 복구를 구분한다.

  3. 03
    두 SUSPEND 복귀

    cpu_standby()의 반환과 power-down wake의 warmboot를 분리한다. 보드가 지원하지 않는 상태는 강제로 요청하지 않는다.

원문과 다음 글