RPC가 Linux에 돌아왔을 때 이어지는 처리
Linux의 optee_smc_do_call_with_arg는 반환값이 RPC인지 검사합니다. 드라이버가 처리할 요청은 직접 처리하고, 사용자 공간 서비스가 필요한 요청은 tee-supplicant에 전달합니다. 이후 RETURN_FROM_RPC 호출로 중단된 보안 작업을 이어갑니다. RPC 반환, SMC 최종 반환, 메시지 안의 TA 결과 ret/ret_origin은 서로 구분합니다.
QUESTION
RPC에서 누가 멈추고, 어떤 요청만 tee-supplicant까지 가는가?
thread_rpc_cmd()는 shared optee_msg_arg를 만들고 RPC SMC로 제어권을 돌려준다. AArch64 thread_rpc_spsr가 현재 secure thread의 레지스터와 stack 위치를 저장하고 thread_state_suspend()가 ACTIVE를 SUSPENDED로 바꾼다. Linux가 요청을 처리한 뒤 RETURN_FROM_RPC로 해당 thread를 재개한다.
모든 RPC가 사용자 공간으로 가는 것은 아니다. Linux 드라이버는 RPC function과 command를 분기해 SHM 할당/해제와 일부 서비스를 직접 처리한다. 그 밖의 명령은 tee-supplicant 요청 큐로 보낼 수 있다. 이 글은 OP-TEE OS 4.10.0의 SMC 경로를 기준으로, Normal World 분기만 Linux v6.18 소스와 대조한다.
OP-TEE 메시지 460–580 · AArch64 suspend 180–238 · Linux 분기 784–872.
STRUCTURE
명령 버퍼와 제어 상태를 따로 보기
Shared RPC message
thr->rpc_arg → optee_msg_argcmd, num_params, params, ret. Normal World가 접근하는 shared memory.rpc_mobj / cookie호출자가 제공한 RPC arg가 없으면 RPC_ALLOC로 확보. 제공된 arg면 그 버퍼 사용.Secure execution state
thread_ctx.regs + stackAArch64 어셈블리에서 보존. thread_state_suspend가 SUSPENDED로 변경하고 thread index 반환.RETURN_FROM_RPC의 thread IDthread_resume_from_rpc가 범위와 SUSPENDED 상태를 검사한 뒤 ACTIVE로 되돌림.shared argument cookie는 버퍼를 찾는 값이고 thread ID는 재개할 실행 문맥을 고르는 값이다. 둘을 하나의 “resume token”으로 묶지 않는다.
CALL PATH
SMC 반환 뒤 Linux에서 갈라지는 경로
RPC_CMD 왕복과 선택적 tee-supplicant 전달get_rpc_argcommand·params 기록, ret=TEE_ERROR_GENERIC 초기화.thread_rpc → suspendOPTEE_SMC_RETURN_RPC_CMD와 arg cookie를 전달.optee_handle_rpcRPC function별 분기. CMD면 arg->cmd를 다시 분기.드라이버가 직접
handle_rpc_func_cmd에서 처리.optee_rpc_cmd 내부 handler.설정에 따라
in_kernel_rpmb_routing이면 커널, 아니면 supplicant.tee-supplicant로
handle_rpc_supp_cmd → 요청 큐 → supplicant recv/send.RETURN_FROM_RPC → secure thread 재개 → get_rpc_arg_res반환된 arg->ret와 output parameter를 읽는다. 한 standard call 안에서 RPC가 다시 발생할 수 있다.STATE LEDGER
경계별로 기록할 값
| 경계 | 입력·검사 | 바뀌는 상태 | 다음 소비자 |
|---|---|---|---|
get_rpc_arg | param 개수 ≤ THREAD_RPC_MAX_NUM_PARAMS; attr·mobj type 변환 | shared arg cmd/params, 기본 실패 ret; cookie | thread_rpc_cmd |
AArch64 thread_rpc_spsr | 현재 active thread | regs/SP 저장, ACTIVE → SUSPENDED, thread index 반환 | Normal World SMC handler |
| Linux RPC handler | RPC function → CMD → command 분기 | 직접 처리 또는 supplicant 결과를 shared arg에 기록 | RETURN_FROM_RPC |
thread_resume_from_rpc | thread ID 범위와 SUSPENDED 상태 | SUSPENDED → ACTIVE; 저장된 regs/SP 복귀 | RPC 호출 다음 명령 |
get_rpc_arg_res | 원래 parameter attr | VALUE OUT/INOUT a,b,c 또는 MEMREF OUT/INOUT size 복사; arg->ret 반환 | secure service |
RPC arg의 ret, outer SMC의 return code, 원래 TA call message의 결과는 서로 다른 층이다.
VISUAL WALKTHROUGH
중단·재개의 두 가지 관찰 지점
rv[]에 RPC function 및 cookie 저장.thread_state_suspend; 반환값은 thread index.RETURN_FROM_RPC 호출..thread_rpc_return재개된 stack에서 w0–w3을 rv[]에 저장하고 C 호출자로 반환.resume 함수는 thread ID가 범위 안이고 실제 SUSPENDED인지 검사한다. 그 밖의 경우 정상 재개하지 않고 ERESUME가 반환된다. 이것이 command result의 검증과는 별도다.
outer SMC
OPTEE_SMC_RETURN_RPC_*Linux가 RPC 요청으로 식별하는 반환값.RPC message
arg->retNormal World RPC command의 결과. 기본값은 GENERIC.원래 TA call
ret/ret_originRPC 처리 후 이어지는 TA 호출의 결과. RPC message와 별개.get_rpc_arg_res() 자체는 모든 output length를 범용으로 재검증하지 않는다. SHM_ALLOC처럼 command별 후속 함수가 ret, parameter 개수/type, size를 검사하는 경우와 구분한다.
UPSTREAM SOURCE
원본 코드
아래 코드는 OP-TEE OS 4.10.0의 core/arch/arm/kernel/thread_optee_smc.c에서 537-625줄을 그대로 가져온 것이다.
537 for (size_t n = 0; n < num_params; n++) {
538 switch (params[n].attr) {
539 case THREAD_PARAM_ATTR_VALUE_OUT:
540 case THREAD_PARAM_ATTR_VALUE_INOUT:
541 params[n].u.value.a = arg->params[n].u.value.a;
542 params[n].u.value.b = arg->params[n].u.value.b;
543 params[n].u.value.c = arg->params[n].u.value.c;
544 break;
545 case THREAD_PARAM_ATTR_MEMREF_OUT:
546 case THREAD_PARAM_ATTR_MEMREF_INOUT:
547 /*
548 * rmem.size and tmem.size is the same type and
549 * location.
550 */
551 params[n].u.memref.size = arg->params[n].u.rmem.size;
552 break;
553 default:
554 break;
555 }
556 }
557
558 return arg->ret;
559}
560
561uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
562 struct thread_param *params)
563{
564 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
565 void *arg = NULL;
566 uint64_t carg = 0;
567 uint32_t ret = 0;
568
569 /* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
570 plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
571 &thread_rpc_pnum);
572
573 ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
574 if (ret)
575 return ret;
576
577 reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
578 thread_rpc(rpc_args);
579
580 return get_rpc_arg_res(arg, num_params, params);
581}
582
583/**
584 * Free physical memory previously allocated with thread_rpc_alloc()
585 *
586 * @cookie: cookie received when allocating the buffer
587 * @bt: must be the same as supplied when allocating
588 * @mobj: mobj that describes allocated buffer
589 *
590 * This function also frees corresponding mobj.
591 */
592static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
593{
594 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
595 void *arg = NULL;
596 uint64_t carg = 0;
597 struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
598 uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, ¶m,
599 &arg, &carg);
600
601 mobj_put(mobj);
602
603 if (!ret) {
604 reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
605 thread_rpc(rpc_args);
606 }
607}
608
609static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
610 unsigned int bt, size_t size)
611{
612 struct mobj *mobj = NULL;
613 uint64_t cookie = 0;
614 size_t sz = 0;
615 paddr_t p = 0;
616
617 if (arg->ret || arg->num_params != 1)
618 goto err;
619
620 if (arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT &&
621 arg->params[0].attr != (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
622 OPTEE_MSG_ATTR_NONCONTIG))
623 goto err;
624
625 p = arg->params[0].u.tmem.buf_ptr;
READING CONTRACT
원본 발췌가 직접 보여 주는 것
메인 발췌 thread_optee_smc.c:537–625는 get_rpc_arg_res()의 끝, thread_rpc_cmd(), shared-memory free/allocate 결과 검사 시작을 잇는다. 이어진 관련 발췌 648–709는 payload RPC_ALLOC/free wrapper, 524–626 발췌는 get_rpc_arg()의 마지막 return 뒤에 get_rpc_arg_res()의 output 복사, RPC command와 free·할당 결과 검사가 이어진다. parameter를 wire 형식으로 바꾸는 본문은 별도 L492–525를 읽어야 한다. 세 원본 코드 블록은 그대로 유지했다.
thread 상태 전환은 이 C 발췌 안에 없다. AArch64 assembly 180–238와 resume 379–426, suspend 516–565를 함께 읽어야 한다.
RELATED SOURCE
함께 읽어야 하는 원본 코드
첫 코드 조각만으로 동작이 완성되지 않는 경우 호출 매크로, 객체 정의와 실제 실행 목록을 같은 페이지에 묶었다. 각 조각은 같은 기준 commit에서 가져왔다.
01. RPC가 사용할 non-secure shared payload 할당
core/arch/arm/kernel/thread_optee_smc.c 648-709줄이다.
648
649/**
650 * Allocates shared memory buffer via RPC
651 *
652 * @size: size in bytes of shared memory buffer
653 * @align: required alignment of buffer
654 * @bt: buffer type OPTEE_RPC_SHM_TYPE_*
655 *
656 * Returns a pointer to MOBJ for the memory on success, or NULL on failure.
657 */
658static struct mobj *thread_rpc_alloc(size_t size, size_t align, unsigned int bt)
659{
660 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
661 void *arg = NULL;
662 uint64_t carg = 0;
663 struct thread_param param = THREAD_PARAM_VALUE(IN, bt, size, align);
664 uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_ALLOC, 1, ¶m,
665 &arg, &carg);
666
667 if (ret)
668 return NULL;
669
670 reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
671 thread_rpc(rpc_args);
672
673 return get_rpc_alloc_res(arg, bt, size);
674}
675
676struct mobj *thread_rpc_alloc_payload(size_t size)
677{
678 return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_APPL);
679}
680
681struct mobj *thread_rpc_alloc_kernel_payload(size_t size)
682{
683 return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_KERNEL);
684}
685
686void thread_rpc_free_kernel_payload(struct mobj *mobj)
687{
688 if (mobj)
689 thread_rpc_free(OPTEE_RPC_SHM_TYPE_KERNEL,
690 mobj_get_cookie(mobj), mobj);
691}
692
693void thread_rpc_free_payload(struct mobj *mobj)
694{
695 if (mobj)
696 thread_rpc_free(OPTEE_RPC_SHM_TYPE_APPL, mobj_get_cookie(mobj),
697 mobj);
698}
699
700struct mobj *thread_rpc_alloc_global_payload(size_t size)
701{
702 return thread_rpc_alloc(size, 8, OPTEE_RPC_SHM_TYPE_GLOBAL);
703}
704
705void thread_rpc_free_global_payload(struct mobj *mobj)
706{
707 thread_rpc_free(OPTEE_RPC_SHM_TYPE_GLOBAL, mobj_get_cookie(mobj),
708 mobj);
709}
02. RPC response의 shared argument와 parameter를 회수
core/arch/arm/kernel/thread_optee_smc.c 524-626줄이다.
524 return TEE_ERROR_BAD_PARAMETERS;
525 }
526 }
527
528 *arg_ret = arg;
529 *carg_ret = mobj_get_cookie(thr->rpc_mobj);
530
531 return TEE_SUCCESS;
532}
533
534static uint32_t get_rpc_arg_res(struct optee_msg_arg *arg, size_t num_params,
535 struct thread_param *params)
536{
537 for (size_t n = 0; n < num_params; n++) {
538 switch (params[n].attr) {
539 case THREAD_PARAM_ATTR_VALUE_OUT:
540 case THREAD_PARAM_ATTR_VALUE_INOUT:
541 params[n].u.value.a = arg->params[n].u.value.a;
542 params[n].u.value.b = arg->params[n].u.value.b;
543 params[n].u.value.c = arg->params[n].u.value.c;
544 break;
545 case THREAD_PARAM_ATTR_MEMREF_OUT:
546 case THREAD_PARAM_ATTR_MEMREF_INOUT:
547 /*
548 * rmem.size and tmem.size is the same type and
549 * location.
550 */
551 params[n].u.memref.size = arg->params[n].u.rmem.size;
552 break;
553 default:
554 break;
555 }
556 }
557
558 return arg->ret;
559}
560
561uint32_t thread_rpc_cmd(uint32_t cmd, size_t num_params,
562 struct thread_param *params)
563{
564 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
565 void *arg = NULL;
566 uint64_t carg = 0;
567 uint32_t ret = 0;
568
569 /* The source CRYPTO_RNG_SRC_JITTER_RPC is safe to use here */
570 plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_RPC,
571 &thread_rpc_pnum);
572
573 ret = get_rpc_arg(cmd, num_params, params, &arg, &carg);
574 if (ret)
575 return ret;
576
577 reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
578 thread_rpc(rpc_args);
579
580 return get_rpc_arg_res(arg, num_params, params);
581}
582
583/**
584 * Free physical memory previously allocated with thread_rpc_alloc()
585 *
586 * @cookie: cookie received when allocating the buffer
587 * @bt: must be the same as supplied when allocating
588 * @mobj: mobj that describes allocated buffer
589 *
590 * This function also frees corresponding mobj.
591 */
592static void thread_rpc_free(unsigned int bt, uint64_t cookie, struct mobj *mobj)
593{
594 uint32_t rpc_args[THREAD_RPC_NUM_ARGS] = { OPTEE_SMC_RETURN_RPC_CMD };
595 void *arg = NULL;
596 uint64_t carg = 0;
597 struct thread_param param = THREAD_PARAM_VALUE(IN, bt, cookie, 0);
598 uint32_t ret = get_rpc_arg(OPTEE_RPC_CMD_SHM_FREE, 1, ¶m,
599 &arg, &carg);
600
601 mobj_put(mobj);
602
603 if (!ret) {
604 reg_pair_from_64(carg, rpc_args + 1, rpc_args + 2);
605 thread_rpc(rpc_args);
606 }
607}
608
609static struct mobj *get_rpc_alloc_res(struct optee_msg_arg *arg,
610 unsigned int bt, size_t size)
611{
612 struct mobj *mobj = NULL;
613 uint64_t cookie = 0;
614 size_t sz = 0;
615 paddr_t p = 0;
616
617 if (arg->ret || arg->num_params != 1)
618 goto err;
619
620 if (arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT &&
621 arg->params[0].attr != (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT |
622 OPTEE_MSG_ATTR_NONCONTIG))
623 goto err;
624
625 p = arg->params[0].u.tmem.buf_ptr;
626 sz = READ_ONCE(arg->params[0].u.tmem.size);
DETAILS
RPC message의 생성과 결과 복사
arg 확보와 초기화
get_rpc_arg()는 최대 parameter 수를 먼저 제한한다. 현재 thread에 RPC arg가 없으면 별도의 OPTEE_SMC_RETURN_RPC_ALLOC 왕복으로 mobj를 확보한다. 이후 사용한 크기만 0으로 지우고 cmd, num_params, 기본 TEE_ERROR_GENERIC를 기록한다.
attr에 따른 wire 형식
VALUE는 a,b,c를, MEMREF는 non-secure/registered SHM에 맞춰 TMEM 또는 RMEM을 채운다. 지원하지 않는 attr/mobj는 TEE_ERROR_BAD_PARAMETERS를 반환한다. 확보 자체가 실패하면 TEE_ERROR_OUT_OF_MEMORY다.
정상 재개 후 output
get_rpc_arg_res()는 호출 시 원래 attr를 기준으로 VALUE OUT/INOUT의 a,b,c와 MEMREF OUT/INOUT의 size를 옮기고 arg->ret를 반환한다. input-only 필드는 복사하지 않는다.
IMPLEMENTATION NOTES
tee-supplicant가 실제로 필요한 분기
RPC function과 command의 두 단계 분기
optee_handle_rpc()에서 FUNC_ALLOC/FREE와 FOREIGN_INTR는 CMD와 별개다. FUNC_CMD는 handle_rpc_func_cmd()로 들어가 SHM_ALLOC/FREE를 먼저 처리하며 다른 cmd를 optee_rpc_cmd()에 넘긴다.
커널 또는 supplicant
Linux v6.18의 optee_rpc_cmd()는 시간·notification·suspend·I2C를 직접 처리하고, RPMB는 in_kernel_rpmb_routing에 따라 갈린다. 다른 command는 handle_rpc_supp_cmd()를 호출한다. 각 커널 버전의 분기는 별도 확인이 필요하다.
supplicant 요청 큐
optee_supp_thrd_req()는 요청을 큐에 넣고 완료를 기다린다. supplicant의 recv/send가 결과를 되돌리면 요청자가 재개한다. supp_nowait이고 supplicant가 없으면 COMMUNICATION을 반환한다. 이 코드는 고정 timeout을 사용하지 않으므로 “supplicant timeout”을 보편적인 실패로 쓰지 않는다.
DEEP ANALYSIS
고정 소스에서 확인할 세 검증 경계
| 경계 | 검사 | 결과·제한 |
|---|---|---|
| Secure message 생성 | num_params 제한, attr/mobj type 검사 | 실패하면 thread_rpc() 전에 BAD_PARAMETERS 또는 OUT_OF_MEMORY |
| Secure thread 재개 | thread ID < CFG_NUM_THREADS 및 SUSPENDED | 성공 시 ACTIVE; 실패 시 ERESUME |
| Linux CMD 분기 | RPC function과 arg->cmd 분리 | SHM/일부 서비스 직접 처리, 조건부 또는 기본 supplicant 전달 |
| RPC 결과 복사 | 호출 전 attr에 따른 OUT/INOUT만 | VALUE a,b,c / MEMREF size; arg->ret 반환 |
| SHM_ALLOC 후속 검사 | ret, num_params=1, TMEM_OUTPUT type, 받은 size ≥ 요청 size | 유효한 mobj 생성 또는 NULL; 범용 get_rpc_arg_res 검사와 구분 |
Normal World의 shared memory 내용을 신뢰 가능한 secure 내부 상태로 자동 승격하지 않는다. 다만 어떤 크기와 형식을 검사하는지는 RPC command별 후속 코드에서 확인해야 한다.
OBJECT LIFETIME
왕복 동안 남는 객체와 해제 지점
| 대상 | 생성·보존 | 종료·주의 |
|---|---|---|
thread_ctx | ACTIVE thread의 regs/SP 및 session context 보존 | RPC 동안 SUSPENDED, RETURN_FROM_RPC에서 ACTIVE; call 완료 시 free |
thr->rpc_arg | 제공된 RPC arg 또는 RPC_ALLOC로 확보한 shared memory | standard call 완료 시 제공 arg 참조 정리; 캐시 설정에 따라 할당 mobj 유지/해제 |
rpc_mobj cookie | 할당 경로의 mobj 식별자 | 버퍼 수명 관리 값; thread ID와 다름 |
| Linux supp request | supplicant 분기에서 queue·completion 생성 | recv/send 또는 오류 뒤 완료·free; 직접 처리 경로에는 없음 |
| 원래 call message | TA command에 쓰인 별도 optee_msg_arg | RPC arg의 ret와 별개로 TA 결과 보관 |
FAILURE PATH
어느 단계에서 왕복이 끊기는가?
| 증상 | 첫 확인 지점 | 소스 결과 |
|---|---|---|
| RPC 전 BAD_PARAMETERS | num_params 초과, 지원하지 않는 attr/mobj | get_rpc_arg에서 즉시 반환 |
| RPC arg 확보 실패 | 제공된 arg 없음, RPC_ALLOC/mobj mapping 실패 | OUT_OF_MEMORY; 별도 alloc RPC가 선행될 수 있음 |
| 재개 거부 | thread ID 범위 또는 SUSPENDED 상태 | thread_resume_from_rpc 실패 → ERESUME |
| supplicant 사용 불가 | supp_nowait + supplicant ctx 없음, killable wait 중단 | Linux supp request가 COMMUNICATION 반환 |
| SHM_ALLOC 결과 거부 | ret/parameter 개수·attr/size 또는 mobj 생성 | NULL; 받은 size가 요청보다 작은지도 검사 |
| RPC command 오류 | shared arg->ret와 output params | outer SMC status 또는 원래 TA ret와 혼동하지 않음 |
기존의 “resume token 불일치”나 “고정 supplicant timeout”은 이 고정 경로의 직접 진단명으로 쓰지 않는다.
EVIDENCE
실제 빌드에서 확인할 자료
이 리뷰는 고정 소스와 로컬 HTML을 검증했으며 보드 실행이나 새 OP-TEE 빌드는 수행하지 않았다.
| 자료 | 기록 값 | 분리할 질문 |
|---|---|---|
| 빌드 설정 | CFG_PREALLOC_RPC_CACHE, CFG_NUM_THREADS, Linux in_kernel_rpmb_routing | arg 캐시와 thread 한계, RPMB 분기 |
| RPC trace | SMC return RPC function, arg.cmd, thread ID, arg cookie | 제어 문맥 ID와 buffer cookie 분리 |
| 결과 trace | RPC arg.ret, output size, 최종 SMC code, call arg.ret | 세 층의 결과 분리 |
| supplicant trace | req func, recv/send, completion/communication error | 커널 직접 처리인지 사용자 공간 처리인지 |
LAB
분기별 최소 확인
- 01직접 처리와 supplicant 처리 비교
GET_TIME과 파일 서비스 RPC를 각각 실행해 Linux handler와 supplicant recv/send 출현 여부를 비교한다. 사용 중인 커널 소스의 command switch를 먼저 확인한다.
- 02thread ID와 cookie 분리 기록
RPC_CMD 반환의 thread index와 arg cookie를 별도 필드로 기록하고, RETURN_FROM_RPC가 같은 suspended thread를 재개하는지 추적한다.
- 03오류의 층 비교
supplicant 오류와 SHM_ALLOC의 잘못된 size를 별도 사례로 만들고 RPC arg.ret, 최종 SMC 결과, 원래 TA call 결과를 각각 기록한다.
PRIMARY REFERENCES