본문 바로가기

Kernel20

misc device 例 기본적인 read(), write(), ioctl(), poll() 종류의 system call 작업이 가능한 misc device 예제를 작성한다. Driver Source/* file: xxx_device.c */#include #include #include #include #include #define DEVICE_NAME "xxx"#define XXX_IOCTL_CMD_READ _IOR('j', 1, int)#define XXX_IOCTL_CMD_WRITE _IOW('j', 2, int)#define XXX_IOCTL_CMD_WAKE_UP _IO('j', 3)int xxx_var = 1123;atomic_t xxx_poll_ready = ATOMIC_INIT(0);struct wait_queue.. 2024. 9. 21.
module signing Device driver 설치 과정에서 아래의 Error Message가 출력되는 경우my_driver: module verification failed: signature and/or required key missing - tainting kernel 아래 2개의 Configuration 활성화 되어 있으면, signing 되지 않은 module의 install을 허용하지 않는다.CONFIG_MODULE_SIG=yCONFIG_MODULE_SIG_SHA512=y 다음 명령어를 이용해서 Kernel build 時 생성된 key를 이용해서 signing 가능하다.kernel_path/scripts/sign-file kernel_path/sha512 certs/signing_key.pem kernel_pat.. 2024. 9. 21.
Scatter Gather List scatterlist CPU 및 Device 관점에서의 address와 length 정보 (page 內 offset 정보 포함) page_link 기능 SG_CHAIN 설정 時, 현재 sgl은 데이터를 포함하지 않은 link 用 sgl SG_END 설정 時, 현재 sgl은 마지막 sgl이며 data를 가르키고 있음 CHAIN이 아닌 경우, page_link는 첫번째 page 정보를 가르킴 SGL Type non-chained SGL 여러개의 SGL이 연속적으로 위치 SG_MAX_SINGLE_ALLOC : non-chained SGL의 최대 크기 해당값 초과 時, 자동으로 chained-SGL 적용 chained SGL 하나의 chain 內 SGL은 연속적으로 위치 마지막 SGL은 chain을 연결하는 기.. 2024. 4. 10.
Block IO 분석 Kernel의 Block Layer 내용 정리 Storage IO Framework File System Layer Disk와 Memory 사이의 Mapping 작업 수행 Search 및 Access를 위한 Data 저장 未 구성 Block Layer File System 요청에 따라 Data를 전달 IO Scheduling 기능을 이용하여 요청을 병합/분할 SCSI Layer Data 전송 기능을 수행하며 SCSI Disk 식별 일반적인 임베디드 환경에서는 SCSI Layer 도움 없이 Device로 바로 연결 LLDD (Low Level Device Dirver) Data 전송 기능을 수행하며 특정 Device 구동 기능 제공 IO submit/complete 각 Layer는 하위에 요청을 전달할때 .. 2024. 3. 24.
kernel - make cscope tags make ARCH=arm64 -j$(nproc) CROSS_COMPILE=aarch64-linux-gnu- tags cscope 2024. 2. 2.
kernel arm64 用 ctags & cscope 아래의 스크립트를 이용해서 특정 arch의 파일만 골라서 데이터 베이스를 만들도록 하자. 아래 스크립트는 arm64만 검색을 하도록 한 것이다. 만약 다른 arch를 제외하고 싶다면, 아래 파일을 사용해서 특정 arch를 제외 시키자. # mk_cscope_ctags_arm64.sh # use like below # # $ ls # linux # $ mk_cscope_ctags_arm64.sh linux echo "kernel root directory: $1" if [ "$1" = "" ]; then echo "input kernel directory" exit 0 else kdir=$(basename $1) fi rm -vrf cscope.files cscope.in.out cscope.out csc.. 2024. 2. 2.
라즈베리파이4 arm64 빌드 및 설치스크립트 만약 처음으로 빌드 하는 경우에는 의존성이 있는 패키지들 설치해 주어야 한다 다음 명령어를 실행한다 sudo apt install git bc bison flex libssl-dev make 빌드 스크립트 (version 정보에 현재 시간 및 날짜를 추가) # # file name : build_rpi_kernel.sh # #!/bin/bash # should run with sudo # should run at directory like below # # $ ls # linux build_rpi_kernel.sh install_rpi_kernel.sh KERNEL_TOP_PATH="$( cd "$(dirname "$0")"; pwd -P )" OUTPUT="$KERNEL_TOP_PATH/out" KER.. 2024. 2. 2.
kwork 사용 例 kernel work interface를 이용하여 worker thread를 생성하는 방법 (kernel module)매 1초마다 thread 실행 /* * example_work.c */#include #include #include #define TEST_WORK_QUEUE_NAME "Test_Work_Queue"#define TEST_WORK_PERIOD (1 * HZ) // every 1 secstatic ulong test_number_iteration;static bool test_work_die;static void test_work_handler(struct work_struct * wrk);static struct workqueue_struct *test_workqueue;static D.. 2024. 2. 2.
hrtimer 사용 例 hrtimer를 이용하여 timer interrupt 발생하는 예 (kernel module)매 1000ms 마다 interrupt 발생 /* * example_hrtimer.c */#include #include #include #define TEST_HRTIMER_PERIOD_MS (1000)struct hrtimer test_timer;ulong test_nr_iteration = 0;enum hrtimer_restart test_irq_timer_handler(struct hrtimer *timer){ BUG_ON(!in_interrupt()); /* * DO SOMETHING */ test_nr_iteration++; // reset expire time .. 2024. 2. 2.
process 생성/종료 ftrace 얻기 ftrace 설정 #!/bin/bash echo 0 > /sys/kernel/debug/tracing/tracing_on sleep 1 echo "tracing_off" echo 0 > /sys/kernel/debug/tracing/events/enable sleep 1 echo "events disabled" echo secondary_start_kernel > /sys/kernel/debug/tracing/set_ftrace_filter sleep 1 echo "set_ftrace_filter init" echo function > /sys/kernel/debug/tracing/current_tracer sleep 1 echo "function tracer enabled" echo 1 > /sys/k.. 2024. 2. 2.
debugfs 생성 ( /sys/kernel/debug/) 다음과 같은 경로에 read/write 가능한 debug fs를 생성한다 cat /sys/kernel/debug/rpi_debug/val 아래의 코드를 module로 생성하여 빌드한다. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include uint32_t my_debug_state = 0x1000; static struct dentry *my_debugfs_root; static int my_stat_get(void *data, u64 *v.. 2024. 2. 2.
함수 ftrace 얻기 ftrace를 완전히 사용하기 위한 configuration 활성화 CONFIG_FTRACE=y CONFIG_DYNAMIC_FTRACE=y CONFIG_FUNCTION_TRACER=y CONFIG_FUNCTION_GRAPH_TRACER=y CONFIG_IRQSOFF_TRACER=y CONFIG_SCHED_TRACER=y CONFIG_FUNCTION_PROFILER=y CONFIG_STACK_TRACER=y CONFIG_TRACER=SNAPSHOT=y 먼저 아래의 명령어로 trace 가능한 함수 확인 cat /sys/kernel/debug/tracing/available_filter_functions show_interrupt() 함수 정보를 얻기위해 아래 스크립트 사용 #!/bin/bash # how t.. 2024. 2. 2.
Device Tree 분석 (Kernel Source) .dts파일은 컴파일 후, HexFile로 생성된다. 해당 HexFile을 Linux Kernel이 Parsing 하면 아래그림과 같이 Tree 구조를 가진다. Linux Source Code 흐름을 따라가보면 아래 그림과 같다. 동일한 내용을 텍스트로 작성. setup_arch(&command_line) setup_machine_fdt(__atags_pointer) | 인수로 전달받은 디바이스 트리(fdt)가 물리 주소에 있는지 검색 | 해당 machine을 찾고 machine_desc구조체 포인터로 알아온다 | 디바이스 트리로부터 초기 부트업 과정에 미리(early) 설정해야 정보를 얻어온다 | 초기 정보에는 커맨드 라인 정보나 메모리 정보가 있다 early_init_dt_verify(phys_to_.. 2024. 2. 2.
Device Tree 문법 개요 PC에서는 BIOS가 있어서 하드웨어 장치가 변경되면 자동적으로 검출하여 동작하도록 해주는 작업이 쉽다. ARM 프로세서는 BIOS가 없어서 리눅스 커널이 모든 역할을 다해주고 있어서 리눅스 커널을 믿는 수밖에 없다. 그러므로, 리눅스 커널에 도입된 해결책이 디바이스 트리(Device Tree)이며, Open Firmware(Abbreviated OF) 혹은 Flattened Device Tree(FDT)라고 언급되기도 한다. Device Tree는 정해진 API가 특정 데이터에 접근하도록 표준화된 Tree 구조체를 사용하도록 한다. 주변장치들의 버스, 주소, 인터럽트, 변수들은 정해진 관례를 지켜서 Device Tree에 표현한다. 디바이스 트리는 커널의 일부분으로서 하드웨어 정보를 추가, 제거,.. 2024. 2. 2.
ZRAM 분석 . zram은 memory swap 시, flash가 아닌 ram을 사용하는 방법이다. 이때, block device의 구조를 가지고 동작하며 메모리 압축기법을 사용한다. 자세한 개념은 아래의 링크를 참고하기 바라며, 해당 포스팅 에서는 source code 분석에 대해서 얘기하고자 한다. zram - Wikipedia From Wikipedia, the free encyclopedia Linux module for compressed RAM This article is about the Linux kernel feature. For the memory hardware technology, see Z-RAM. For the Linux kernel compressed swap cache, see zswap.. 2024. 2. 2.
ELF 실행 & execve ELF 실행되는 과정 요약 Source Code 분석 먼저 실행가능한 파일(ELF)에 대한 정보를 담게될 linux_binprm에 대해서 살펴보자. /* * This structure is used to hold the arguments that are used when loading binaries. */ struct linux_binprm { char buf[BINPRM_BUF_SIZE]; // ELF Header의 128개 문자르 저장한다 #ifdef CONFIG_MMU struct vm_area_struct *vma; unsigned long vma_pages; #else # define MAX_ARG_PAGES32 struct page *page[MAX_ARG_PAGES]; #endif stru.. 2024. 2. 2.
Bootloader 개요 Linux Documentation을 정리하였다. (Kernel/Document/arm/Booting) Booting ARM Linux ARM Linux를 Booting 하기 위해서는 boot loader가 필요하다. boot loader는 main kernel이 수행되기 전에 동작하는 작은 프로그램을 말한다. 여러 가지 device들이 boot load를 통해 초기화되며, 최종적으로 linux kernel을 실행하며, kernel에게 필요한 정보를 전달한다. ​ BL(Boot loader)는 간단하게 아래의 수행 과정을 거친다. 1. RAM을 설정하고 초기화한다. 2. 하나의 시리얼 포트를 초기화한다. 3. machine type을 감지한다. 4. kernel tage list를 설정한다. 5. ini.. 2024. 2. 2.
[sched] Pressure Stall Information (PSI) Linux에서는 CPU, Memory, IO 등 자원을 사용하기 위한 경쟁 및 자원의 고갈로 인한 성능 영향도를 측정할 수 있는 인터페이스를 제공한다. 즉, 자원을 얻기위해 프로세스가 동작하지 못하고 얼마나 대기(stall) 하였는지 측정이 가능하다. 이 기능은 Pressure Stall Information(PSI) 이름으로 Kernel에 추가되었고, 아래에서는 그 의미와 사용 방법을 간단하게 작성하였다. ※ PSI 인터페이스 ※ 아래처럼 커맨드를 입력하여 PSI 값을 읽을 수 있다. $ cat /proc/pressure/cpu some avg10=2.98 avg60=2.81 avg300=1.41 total=268109926 $ cat /proc/pressure/memory some avg10=0.30.. 2024. 2. 2.
[mm][fs] File/Anon + VMA/Page ※ File 및 Anon의 VMA와 Page 구조 File Page = Dirty Cache + Clean Cache File VMA = Anone Page + File Page Anon VMA = Anon Page ( 즉, File-VMA에도 Anon Page가 존재할 수 있다. ) ※ 주요 사용 API int PageAnon(struct page *page); int page_is_file_lru(struct page *page); bool vma_is_anonymous(struct vm_area_struct *vma); ※ KSWAPD Reclaim Path kswapd(void *p); /**/ balance_pgdat(pg_data_t *pgdat, int order, int highest_zo.. 2024. 2. 2.
ARM64 (ARMv8) Assembly 참고 자료 https://modexp.wordpress.com/2018/10/30/arm64-assembly/ A Guide to ARM64 / AArch64 Assembly on Linux with Shellcodes and Cryptography Introduction The Cortex-A76 codenamed “Enyo” will be the first of three CPU cores from ARM designed to target the laptop market between 2018-2020. ARM already has a monopoly on handheld… modexp.wordpress.com https://developer.arm.com/documentation/dui0473/m Docume.. 2024. 2. 2.