Linux 드라이버가 이 진입에 넘기는 값
Linux v6.18.37은 ioctl 인자를 optee_msg_arg로 만들고 선택한 전송 ABI로 호출합니다. CALL_WITH_ARG 계열의 a1:a2는 메시지 물리 주소의 상위·하위 32비트이지만, CALL_WITH_REGD_ARG에서는 등록된 공유 메모리 cookie이며 a3는 offset입니다. FF-A 구성에는 별도의 전송 구현이 있으므로 이 레지스터 표를 공통 규약처럼 적용하지 않습니다.
QUESTION
secure thread와 message 중 무엇을 먼저 확인하는가?
새 표준 SMC는 FREE secure thread를 먼저 ACTIVE로 바꾼다. 그 thread의 std_smc_entry()가 호출 ID별로 message PA 또는 등록 SHM cookie를 해석한다. 기존 도식의 “message address lookup → thread allocate”는 순서가 거꾸로다.
RPC에서 돌아온 호출은 새 thread를 할당하지 않고 SUSPENDED thread를 재개한다. FF-A transport는 이 SMC 레지스터 경로와 별개다. outer 분기 · 할당 · 재개
STRUCTURE
같은 레지스터의 뜻은 호출 ID에 달려 있다
WITH_ARG / WITH_RPC_ARG
a1:a2 = 64비트 message 물리주소
RPC_ARG는 message 뒤에 별도 RPC arg 공간이 있다.
WITH_REGD_ARG
a1:a2 = 등록 SHM cookie
a3 = 그 mobj의 message offset
RETURN_FROM_RPC
a3 = suspend된 thread ID
a1:a2, a4:a5 = RPC 복귀 값
cookie를 PA로 역참조하거나 RPC의 a3를 등록 SHM offset으로 읽으면 안 된다. 이 레지스터 그림을 FF-A 호출에 적용하지 않는다.
CALL PATH
thread 확보 후 새 message를 해석한다
- Linux SMC
a0와 호출별a1:a3준비 - thread_handle_std_smc()
guest 설정 후 새 호출 분기
- thread_alloc_and_run()
FREE → ACTIVE; register frame
- std_smc_entry()
PA/cookie 검사 → command dispatch
FREE slot이 없으면 메시지 주소 검사 전에 ETHREAD_LIMIT로 돌아간다. secure monitor의 실제 연결은 플랫폼 구성에 따르며 이 그림은 OP-TEE C entry의 검증된 순서다.
STATE LEDGER
입력과 secure thread의 상태 전환
| 호출 | 레지스터 입력 | thread | 다음 검사 |
|---|---|---|---|
| WITH_ARG | a1:a2 = PA | FREE → ACTIVE | static NS SHM 또는 non-secure DDR와 message 길이 |
| WITH_RPC_ARG | a1:a2 = PA | FREE → ACTIVE | message 뒤 RPC arg 공간도 검사 |
| WITH_REGD_ARG | a1:a2 = cookie; a3 = offset | FREE → ACTIVE | registered mobj 참조/매핑, 두 arg 영역 |
| RETURN_FROM_RPC | a3 = thread ID | SUSPENDED → ACTIVE | 저장된 실행 복귀; 새 message lookup 없음 |
Linux 드라이버는 thread 부족 응답에서 대기 후 재시도하고, secure RPC에는 Normal World 처리를 거쳐 RETURN_FROM_RPC로 재진입한다.
VISUAL WALKTHROUGH
PA와 cookie의 message lookup은 별개다
std_entry_with_parg()
static NS SHM이면 PA 정렬·매핑·parameter 수·전체 길이 검사.
그 밖에는 page 정렬 후 non-secure DDR의 mapped mobj를 얻어 get_msg_arg(..., 0) 호출.
std_entry_with_regd_arg()
cookie로 mobj 참조를 얻고 map을 증가시킨다.
get_msg_arg(..., a3)에서 message와 후행 RPC arg를 확인한 뒤 map/ref를 내려놓는다.
get_msg_arg()는 정렬된 header, num_params 상한, 전체 길이, 요청 시 후행 RPC 공간을 검사한다. static SHM 경로는 별도 검사 코드를 쓰므로 모든 PA가 같은 mobj lookup을 거치지 않는다.
등록 SHM에서 mobj_inc_map()이 실패하면 ENOMEM을 반환하며 참조만 mobj_put()으로 내려놓는다. map 증가가 성공한 경로에서는 message 처리 성공·실패 모두 mobj_dec_map() 뒤 mobj_put()을 호출한다. 정적 SHM 경로에는 이 임시 mobj 정리가 없다.
get_msg_arg · PA · cookie
ACTIVE → SUSPENDED
thread_rpc()가 Normal World에 작업을 요청한다. 저장된 thread context가 남는다.
SUSPENDED → ACTIVE
a3 thread ID의 상태를 확인해 기존 context를 재개한다. 범위나 상태가 틀리면 ERESUME.
helper는 성공하면 이 outer 함수로 돌아오지 않는다. thread_handle_std_smc()의 helper 다음 return은 오류 경로다.
UPSTREAM SOURCE
원본 코드
아래 코드는 OP-TEE OS 4.10.0의 core/arch/arm/kernel/thread_optee_smc.c에서 28-116줄을 그대로 가져온 것이다.
28
29static_assert(NOTIF_VALUE_DO_BOTTOM_HALF ==
30 OPTEE_SMC_ASYNC_NOTIF_VALUE_DO_BOTTOM_HALF);
31
32void thread_handle_fast_smc(struct thread_smc_args *args)
33{
34 thread_check_canaries();
35
36 if (IS_ENABLED(CFG_NS_VIRTUALIZATION) &&
37 virt_set_guest(args->a7) && args->a7 != HYP_CLNT_ID) {
38 args->a0 = OPTEE_SMC_RETURN_ENOTAVAIL;
39 goto out;
40 }
41
42 tee_entry_fast(args);
43
44 if (IS_ENABLED(CFG_NS_VIRTUALIZATION))
45 virt_unset_guest();
46
47out:
48 /* Fast handlers must not unmask any exceptions */
49 assert(thread_get_exceptions() == THREAD_EXCP_ALL);
50}
51
52uint32_t thread_handle_std_smc(uint32_t a0, uint32_t a1, uint32_t a2,
53 uint32_t a3, uint32_t a4, uint32_t a5,
54 uint32_t a6 __unused, uint32_t a7 __maybe_unused)
55{
56 uint32_t rv = OPTEE_SMC_RETURN_OK;
57
58 thread_check_canaries();
59
60 if (IS_ENABLED(CFG_NS_VIRTUALIZATION) && virt_set_guest(a7))
61 return OPTEE_SMC_RETURN_ENOTAVAIL;
62
63 /*
64 * thread_resume_from_rpc() and thread_alloc_and_run() only return
65 * on error. Successful return is done via thread_exit() or
66 * thread_rpc().
67 */
68 if (a0 == OPTEE_SMC_CALL_RETURN_FROM_RPC) {
69 thread_resume_from_rpc(a3, a1, a2, a4, a5);
70 rv = OPTEE_SMC_RETURN_ERESUME;
71 } else {
72 thread_alloc_and_run(a0, a1, a2, a3, 0, 0);
73 rv = OPTEE_SMC_RETURN_ETHREAD_LIMIT;
74 }
75
76 if (IS_ENABLED(CFG_NS_VIRTUALIZATION))
77 virt_unset_guest();
78
79 return rv;
80}
81
82/**
83 * Free physical memory previously allocated with thread_rpc_alloc_arg()
84 *
85 * @cookie: cookie received when allocating the buffer
86 */
87static void thread_rpc_free_arg(uint64_t cookie)
88{
89 if (cookie) {
90 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
91 OPTEE_SMC_RETURN_RPC_FREE
92 };
93
94 reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
95 thread_rpc(rpc_args);
96 }
97}
98
99static uint32_t get_msg_arg(struct mobj *mobj, size_t offset,
100 size_t *num_params, struct optee_msg_arg **arg,
101 struct optee_msg_arg **rpc_arg)
102{
103 void *p = NULL;
104 size_t sz = 0;
105
106 if (!mobj)
107 return OPTEE_SMC_RETURN_EBADADDR;
108
109 p = mobj_get_va(mobj, offset, sizeof(struct optee_msg_arg));
110 if (!p || !IS_ALIGNED_WITH_TYPE(p, struct optee_msg_arg))
111 return OPTEE_SMC_RETURN_EBADADDR;
112
113 *arg = p;
114 *num_params = READ_ONCE((*arg)->num_params);
115 if (*num_params > OPTEE_MSG_MAX_NUM_PARAMS)
116 return OPTEE_SMC_RETURN_EBADADDR;
READING CONTRACT
발췌의 함수 경계를 먼저 구분한다
원본 28–116행의 52행은 thread_handle_std_smc() 시작, 99행은 별도 get_msg_arg() 시작이다. 89–167행 보충 발췌는 앞 함수 뒤에 이어지는 단일 실행이 아니다. 원본 세 code block은 고정 commit 753afbbee1682f5d16fd30e87b31058a4fd4f4b8과 행별로 대조해 그대로 보존했다.
새 호출 dispatch는 268–303행, PA/cookie 분기는 174–264행, thread 할당과 재개는 thread.c를 읽어야 완성된다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. 검증된 message를 command dispatcher에 전달
core/tee/entry_std.c 677-765줄이다.
677}
678
679/* Note: this function is weak to let platforms add special handling */
680TEE_Result __weak tee_entry_std(struct optee_msg_arg *arg, uint32_t num_params)
681{
682 return __tee_entry_std(arg, num_params);
683}
684
685/*
686 * If tee_entry_std() is overridden, it's still supposed to call this
687 * function.
688 */
689TEE_Result __tee_entry_std(struct optee_msg_arg *arg, uint32_t num_params)
690{
691 TEE_Result res = TEE_SUCCESS;
692
693 /* Enable foreign interrupts for STD calls */
694 thread_set_foreign_intr(true);
695 switch (arg->cmd) {
696 case OPTEE_MSG_CMD_OPEN_SESSION:
697 entry_open_session(arg, num_params);
698 break;
699 case OPTEE_MSG_CMD_CLOSE_SESSION:
700 entry_close_session(arg, num_params);
701 break;
702 case OPTEE_MSG_CMD_INVOKE_COMMAND:
703 entry_invoke_command(arg, num_params);
704 break;
705 case OPTEE_MSG_CMD_CANCEL:
706 entry_cancel(arg, num_params);
707 break;
708#if defined(CFG_CORE_DYN_SHM) && !defined(CFG_CORE_FFA)
709 case OPTEE_MSG_CMD_REGISTER_SHM:
710 register_shm(arg, num_params);
711 break;
712 case OPTEE_MSG_CMD_UNREGISTER_SHM:
713 unregister_shm(arg, num_params);
714 break;
715#endif
716 case OPTEE_MSG_CMD_DO_BOTTOM_HALF:
717 if (IS_ENABLED(CFG_CORE_ASYNC_NOTIF))
718 notif_deliver_event(NOTIF_EVENT_DO_BOTTOM_HALF);
719 else
720 goto err;
721 break;
722 case OPTEE_MSG_CMD_STOP_ASYNC_NOTIF:
723 if (IS_ENABLED(CFG_CORE_ASYNC_NOTIF))
724 notif_deliver_event(NOTIF_EVENT_STOPPED);
725 else
726 goto err;
727 break;
728#ifdef CFG_CORE_DYN_PROTMEM
729 case OPTEE_MSG_CMD_GET_PROTMEM_CONFIG:
730 get_protmem_config(arg, num_params);
731 break;
732#ifdef CFG_CORE_FFA
733 case OPTEE_MSG_CMD_ASSIGN_PROTMEM:
734 assign_protmem(arg, num_params);
735 break;
736#else
737 case OPTEE_MSG_CMD_LEND_PROTMEM:
738 lend_protmem(arg, num_params);
739 break;
740 case OPTEE_MSG_CMD_RECLAIM_PROTMEM:
741 reclaim_protmem(arg, num_params);
742 break;
743#endif /*!CFG_CORE_FFA*/
744#endif /*CFG_CORE_DYN_PROTMEM*/
745 default:
746err:
747 EMSG("Unknown cmd 0x%x", arg->cmd);
748 res = TEE_ERROR_NOT_IMPLEMENTED;
749 }
750
751 return res;
752}
753
754static TEE_Result default_mobj_init(void)
755{
756#ifdef CFG_CORE_RESERVED_SHM
757 shm_mobj = mobj_phys_alloc(default_nsec_shm_paddr,
758 default_nsec_shm_size, SHM_CACHE_ATTRS,
759 CORE_MEM_NSEC_SHM);
760 if (!shm_mobj)
761 panic("Failed to register shared memory");
762#endif
763
764#ifdef CFG_SECURE_DATA_PATH
765 sdp_mem_mobjs = core_sdp_mem_create_mobjs();
02. mobj와 offset에서 정렬된 optee_msg_arg를 찾는 함수
core/arch/arm/kernel/thread_optee_smc.c 89-167줄이다.
89 if (cookie) {
90 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = {
91 OPTEE_SMC_RETURN_RPC_FREE
92 };
93
94 reg_pair_from_64(cookie, rpc_args + 1, rpc_args + 2);
95 thread_rpc(rpc_args);
96 }
97}
98
99static uint32_t get_msg_arg(struct mobj *mobj, size_t offset,
100 size_t *num_params, struct optee_msg_arg **arg,
101 struct optee_msg_arg **rpc_arg)
102{
103 void *p = NULL;
104 size_t sz = 0;
105
106 if (!mobj)
107 return OPTEE_SMC_RETURN_EBADADDR;
108
109 p = mobj_get_va(mobj, offset, sizeof(struct optee_msg_arg));
110 if (!p || !IS_ALIGNED_WITH_TYPE(p, struct optee_msg_arg))
111 return OPTEE_SMC_RETURN_EBADADDR;
112
113 *arg = p;
114 *num_params = READ_ONCE((*arg)->num_params);
115 if (*num_params > OPTEE_MSG_MAX_NUM_PARAMS)
116 return OPTEE_SMC_RETURN_EBADADDR;
117
118 sz = OPTEE_MSG_GET_ARG_SIZE(*num_params);
119 if (!mobj_get_va(mobj, offset, sz))
120 return OPTEE_SMC_RETURN_EBADADDR;
121
122 if (rpc_arg) {
123 size_t rpc_sz = 0;
124
125 rpc_sz = OPTEE_MSG_GET_ARG_SIZE(THREAD_RPC_MAX_NUM_PARAMS);
126 p = mobj_get_va(mobj, offset + sz, rpc_sz);
127 if (!p)
128 return OPTEE_SMC_RETURN_EBADADDR;
129 *rpc_arg = p;
130 }
131
132 return OPTEE_SMC_RETURN_OK;
133}
134
135static void clear_prealloc_rpc_cache(struct thread_ctx *thr)
136{
137 thread_rpc_free_arg(mobj_get_cookie(thr->rpc_mobj));
138 mobj_put(thr->rpc_mobj);
139 thr->rpc_arg = NULL;
140 thr->rpc_mobj = NULL;
141}
142
143static uint32_t call_entry_std(struct optee_msg_arg *arg, size_t num_params,
144 struct optee_msg_arg *rpc_arg)
145{
146 struct thread_ctx *thr = threads + thread_get_id();
147 uint32_t rv = 0;
148
149 if (rpc_arg) {
150 /*
151 * In case the prealloc RPC arg cache is enabled, clear the
152 * cached object for this thread.
153 *
154 * Normally it doesn't make sense to have the prealloc RPC
155 * arg cache enabled together with a supplied RPC arg
156 * struct. But if it is we must use the supplied struct and
157 * at the same time make sure to not break anything.
158 */
159 if (IS_ENABLED(CFG_PREALLOC_RPC_CACHE) &&
160 thread_prealloc_rpc_cache)
161 clear_prealloc_rpc_cache(thr);
162 thr->rpc_arg = rpc_arg;
163 }
164
165 if (tee_entry_std(arg, num_params))
166 rv = OPTEE_SMC_RETURN_EBADCMD;
167 else
DETAILS
경계별 검사와 반환
| 코드 경계 | 검사 | 결과 |
|---|---|---|
| outer standard entry | guest 설정, a0 | guest 실패 ENOTAVAIL; 새 호출 또는 RPC 재개 선택 |
| thread_alloc_and_run() | FREE slot | ACTIVE로 전환; 없으면 ETHREAD_LIMIT |
| std_smc_entry() | 새 호출 ID | PA, RPC arg PA, cookie 중 선택; 기타 EBADCMD |
| get_msg_arg() | mobj/offset, 정렬, count, 크기 | 잘못된 주소·범위 EBADADDR |
| call_entry_std() | 검증된 message | tee_entry_std() 호출과 RPC/cache 정리 |
IMPLEMENTATION NOTES
소스에서 분명한 경계
메시지보다 thread가 먼저다
FREE slot을 ACTIVE로 바꾸고 register frame을 만든 후 thread_std_smc_entry를 실행한다. thread 부족이면 주소를 검사하지 않았다. invalid PA는 thread가 시작된 뒤 EBADADDR로 끝날 수 있다.
a3의 의미는 명령별이다
REGD_ARG에서는 message offset, RETURN_FROM_RPC에서는 thread ID다. 4.10.0 std_smc_entry()의 PA 분기는 a3를 사용하지 않는다. SMC ABI 주석의 cache field를 이 함수가 직접 검증하는 단계로 그리지 않는다.
RPC에는 새 thread가 없다
thread_resume_from_rpc()는 ID 범위와 SUSPENDED 상태를 검사한다. 복귀 값은 조건부 THREAD_FLAGS_COPY_ARGS_ON_RETURN에서 saved register로 복사한다. 이 함수가 별도 cryptographic token을 인증한다고 쓰지 않는다.
FF-A는 다른 transport다
Linux의 FF-A 구현에 이 SMC register 표를 공통 규약으로 적용하지 않는다.
DEEP ANALYSIS
분기별 초기 반환값
| 조건 | 첫 결정 | SMC 반환 | 주의 |
|---|---|---|---|
| guest 설정 실패 | outer entry | ENOTAVAIL | thread 전 |
| FREE thread 없음 | thread allocator | ETHREAD_LIMIT | Linux는 대기 후 재시도 |
| RPC ID/상태 불일치 | thread resume | ERESUME | 새 message 검사 없음 |
| PA/cookie/크기 오류 | message 경로 | EBADADDR | thread 시작 뒤 |
| 미지원 새 SMC ID | inner entry | EBADCMD | thread 시작 뒤 |
| secure RPC 요청 | thread_rpc() | RPC 반환 코드 | Normal World 처리 후 재개 |
OP-TEE SMC 코드 · thread 상태 · Linux call loop에서 확인했다. 사용자 공간의 최종 오류 매핑은 호출자·command별로 따로 검토해야 한다.
OBJECT LIFETIME
객체별 생성·참조 시점
| 객체 | 생성/획득 | 이번 호출에서의 경계 |
|---|---|---|
| thread register frame | SMC entry/secure thread init | 실행·RPC 재개 문맥; message 본문과 별개 |
| thread_ctx | FREE slot 획득 | ACTIVE, RPC 시 SUSPENDED, 완료 후 FREE |
| optee_msg_arg | Normal World가 SHM에 준비 | PA/cookie 범위 확인 뒤 dispatcher 사용 |
| argument mobj | mapped DDR 또는 registered cookie | 획득한 참조를 call 뒤 put; static SHM은 별도 |
| RPC arg | 후행 영역 또는 RPC cache | 호출 형식과 설정에 따라 수명 다름 |
FAILURE PATH
어느 검사가 먼저 실패하는가
| 조건 | 첫 검사 | 반환 | 해석 |
|---|---|---|---|
| FREE slot 없음 | thread pool | ETHREAD_LIMIT | 주소 검사 전; Linux 재시도 |
| PA 정렬/범위 오류 | static SHM 또는 mapped DDR | EBADADDR | PA를 곧바로 struct pointer로 cast하지 않음 |
| 등록 cookie 없음 | registered mobj | EBADADDR | cookie는 PA 아님 |
| num_params/전체 길이 초과 | message 범위 | EBADADDR | RPC arg 공간도 호출별 검사 |
| RPC thread ID/상태 불일치 | resume | ERESUME | 새 thread 할당 안 함 |
EVIDENCE
한 번의 호출에서 기록할 상태
| 경계 | 기록할 값 | 확인할 질문 |
|---|---|---|
| Linux SMC 직전 | a0, a1:a2, a3, SHM 종류 | PA/cookie를 ABI에 맞게 넣었나? |
| thread 분기 | FREE/SUSPENDED slot, ID, 반환값 | message 검사 전에 실패했나? |
| message 검사 | PA/cookie, offset, num_params, 전체 길이 | static/DDR/registered 중 어디서 거절됐나? |
| RPC 왕복 | RPC return, 재개 a3, thread 상태 | 같은 실행으로 복귀했나? |
계측 항목이며 대상 보드에서 이 예를 실행했다는 뜻은 아니다.
LAB
분기를 구별할 재현
- 01유효 PA와 잘못 정렬된 PA
CALL_WITH_ARG의 EBADADDR 경계를 비교한다.
- 02등록 cookie와 임의 cookie
REGD_ARG의 mobj lookup과 cleanup을 비교한다.
- 03thread pool 고갈
주소 검사 전에 ETHREAD_LIMIT가 나오는지 본다.
- 04RPC 정상 재개와 틀린 thread ID
SUSPENDED→ACTIVE와 ERESUME을 구분한다.
PRIMARY REFERENCES