Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
최신커널의특징과디바이스드라이버개발에대한이해
Contents
1. 최신 커널의 특징
2. 커널 최적화
3. 커널 핸들링
4. 커널 해킹
5. 디바이스 드라이버 구조
6. 커널 동기화 개요 및 기법
7. Unified device model 기반의 디바이스 드라이버
8. Interrupt Handling과 지연작업
1. 최신 커널의 특징
GeneralPreemptable Kernel
O(1) Scheduler
New Kernel Device Structure (kdev_t)
Improved Posix Threading Support (NGPT and NPTL)
New Driver Model & Unified Device Structure
Faster Internal Clock Frequency
Paring Down the BKL (Big Kernel Lock)
Better in Place Kernel Debugging
Smarter IRQ Balancing
ACPI Improvements
Software Suspend to Disk and RAM*
Support for USB 2.0
ALSA (Advanced Linux Sound Architecture)
LSM (Linux Security Module)
Hardware Sensors Driver (lm-sensors)
1. 최신 커널의 특징
General
CPU Clock and Voltage Scaling
Setting Processor Affinity
Improved NUMA Support
Reverse Mapping VM System (rmap)
Large Page Support
High Resolution Posix Timers
New Serial Port Driver Rewrite and API
Other New Items
New Module Implementation and Utilities
New System Call Mechanism
1. 최신 커널의 특징
I/O LayerRewrite of Block I/O Layer (BIO)
Asynchronous I/O
IDE Layer Update
ACL Support (Access Control List)
New NTFS Driver
NetworkingNFS v4
Zero-Copy NFS
TCP Segmentation Offload*
SCTP Support (Stream Control Transmission Protocol)
Bluetooth Support (not experimental)
NAPI (Network Interrupt Mitigation)
1. 최신 커널의 특징
Removed Features
Export of sys_call_table
End of Task Queues
2. 커널 최적화
• 리눅스 성능 측정 도구– LMBench
• 운영체제, disk I/O, Memory등의 Bandwidth와Latency 측정 도구
– HackBench
• 스케쥴러 비교
• 리눅스 지연 요소 (실시간 성능 측정)– 인터럽트 지연(Interrupt Latency),
– 커널 선점지연(Kernel Preemption Latency),
– 문맥교환지연(Context Switch Latency)
2. 커널 최적화
커널 최적화 기법
파라미터 기반 최적화
부팅 최적화
컴파일러 기반 최적화
Linux-2.6/Documentation/kernel-parameters.txt
CONFIG_PRINTK_TIMEConfigure it in the Kernel Hacking Section
Adds timing information to kernel messages. Simple and robust
Disable console outputThe output of kernel bootup messages to the console time
Even worse : scrolling up in framebuffer consoles
Console output no needed in production systems
Console output can be disabled with the quiet argument in the Linux kernel command line (bootloader settings)
Example : root=/dev/ram0 rw init=/startup.sh quiet
Benchmarks: can reduce boot time by 30 or even 50%
2. 커널 최적화
Preset loops_per_jiffyAt each boot, the Linux kernel calibrate a delay loop (for the udelay function). This measures a loops_per_jiffy(lpj) value. This takes about 25 jiffies (1 jiffy = time between 2 timer interrupts)
At the boot, start Linux with the below option: lpj=<value>
Kernel XIPExecutes the kernel “in place”, i.e. directly from flash
Saves time reading the kernel from flash, uncompressing it and copying it to RAM
Savings depend on the kernel size
Faster rebooting (1)Kexec system call: executes a new kernel from a running one.
Useful for automatic rebooting after kernel panics
2. 커널 최적화
Faster rebooting (2)Use reboot=soft in the kernel command line
When you reboot, the firmware will be skipped.
Supported platforms : i386, x86)64, arm, arm26
Skip memory allocationIdea : spare memory at boot time and manage it by yourself
Assume you have 32M of RAM
Boot your kernel with mem=30M
Copy kernel from flash to Ram using DAM
Reducing probe time on some IDE operations
Multithreaded device probing
2. 커널 최적화
SysV init Initng: http://initng.thinktux.netSome takes can be run in parallel
Reading aheadLinux keeps the contents of all the files it reads in RAM(in the page cache), as long as it doesn’t need the RAM pages for something elseLoad files in RAM cache before using themReadahead-list utilityhttp://freshmeat.net/projects/readahead-listUsing busybox, you can use the readahead command
Application XIPLoad files directly from flash or ROMDon’t copy them to RAM first
2. 커널 최적화
Compiler speed optimizationsBy default, most tools are compiled with compiler optimizations.-O2 is the most common optimization switch of gcc. -O3 can be also be used for speed critical executables. However, there is done at the expense of code size (example : inline function)
Using processor acceleration instructionsLiboil – http://liboil.freedesktop.orgLibrary of functions optimized for special instructions from several processors (Altivec, MMX, SSE, etc)
Prelinkinghttp://people.redhat.com/jakub/prelinkPrelink modifies executables and shared libraries to simplify the dynamic linker relocation work
2. 커널 최적화
커널 컴파일 과정 이해
커널 컴파일 옵션 및 커널 내부 구조와의 관계
커널 이미지 구축 및 이미지 구축 과정 이해
커널 소스 기반 부팅 과정 이해
부팅 메시지 분석
3. 커널 핸들링
커널 Panic 핸들링
Call Tracing
커널 디버깅 핸들링
커널 심볼 관리
nm 유틸리티
System.map 파일 – 커널 컴파일시에 생성
vmlinux.lds 스크립트
ksymtab 커널 심볼 테이블
심볼 export 매크로
4. 커널 해킹
커널 패닉 개요
시스템이 부팅할 경우 혹은 특정 서비스를 하는 동안에 발생하는일종의 오류
커널 패닉 종류
소프트 패닉
Oops
소프트웨어 기반의 커널 패닉
하드 패닉
Aieee
하드웨어 기반의 커널 패닉
시스템 운용 중의 커널 패닉
커널 패닉
Call Tracing
트랩을 받았을 경우에 발생하는 시스템 호출 트레이싱의 일종
arch/ARCH/kernel/traps.c의 die() 함수에 정의
레지스터, 스택, 호출 단계를 출력하는 기법
출력 메시지 분석을 통해 원인 분석 가능
Call Tracing
질의를 통한 디버깅
proc 프로그래밍 기법
seq 인터페이스 사용
ioctl 사용
Tool을 사용한 디버깅
strace / ltrace
kdb kernel debugger 사용
ltt사용
커널 디버깅
상황 개요
시스템의 메모리가 모두 소진된 상태에서 중요한 프로세스가 oom killer에게 죽는 현상이 발생 가능
oom killer 개요
Out of Memory killer
특정 메모리가 부족한 상황에서 동작하고
특정 알고리즘에 의해 프로세스를 선택하고
해당 프로세스를 kill해서 메모리를 확보
Overcommit
실제로 필요로 하는 메모리보다 더 많은 메모리를 가상적으로 할당하는정책을 사용
프로세스는 자신이 요청한 메모리를 모두 사용하지 않는다는 가정
최대한 할당은 늦게 하고 한번 할당하면 계속 사용한다는 가정
oom killer 해결 방안은?
oom killer
5. 디바이스 드라이버 모델 (2.6)
New Driver Model and & Unified Device StructureTreat all devices in a unified fashiondriverfs virtual filesystem can be mounted and seen as a tree by busNew API
void device_init_dev(struct device *)struct device *device_alloc();int device_register(struct device *);void get_device (struct device *);void put_device (struct device *);int valid_device (struct device *);void lock_device (struct device *);void unlock_device (struct device *);
New Driver Model and & Unified Device StructureInitializing, Exiting
int device_driver_init();void device_driver_exit();
New data structuresstruct devicestruct device_driver
Wait Queue
Semaphore
Spinlock
Memory barrier
Completion Functions
Atomic Operations
Bit Operations
Big kernel lock
Big kernel semaphore
Work queue
Linked List
Deferred functions
Dynamic Timers
6. 커널 동기화 개요 및 기법
리눅스 디바이스 드라이버 개요
디바이스 등록 및 해제
드라이버 등록 및 해제
문자 디바이스 드라이버
디바이스 드라이버의 객체 개념
kref, kobject, ktype, kset, …
hotplug
udev
firmware
7. Unified device model 디바이스 드라이버
디바이스 드라이버의 객체 개념
Device Model은 왜 필요한가?
Power management and system shutdown
Communications with user space
Hotpluggable devices
Device classes
Object lifecycles
출처:http://lwn.net/Kernel/LDD3/
디바이스 드라이버의 객체 개념
kobject
kset
ktype
subsystem
class
sysfs
hotplug
udev
subsystem
kset kset kset
kobj kobj kobj
ktype
udev
udev의 목표
/dev를 대체하여 동적으로 생성 ->udev
디바이스 이름을 생성 -> namedev
시스템 디바이스 (sysfs)에서 정보를 취합할 API 제공 -> libsysfs
Top Half와 Bottom Half
Interrupt Handler Handling
Deferred Processing – softirq 구조
8. Interrupt Handling과 지연작업
Interrupt 개요
interrupt 처리의 조건
kernel이 가능한 빨리 인터럽트에서 벗어나야 한다.
interrupt는 언제든지 발생할 수 있으므로 가능한 많이 허용해야 한다.
interrupt 처리 코드는 임계영역이므로 가능한 제한되어 있어야 한다.
인터럽트 타임 때 할 수 없는 일들
인터럽트는 프로세스 컨텍스트내에 있지 않기 때문에 current를 이용하여task_struct 필드에 접근할 수 없다.
sleep() 함수를 사용할 수 없다.
schedule() 함수를 호출할 수 없다.
semaphore 루틴 down()을 호출할 수 없다. 하지만 wake_up()이나 up()을 할수 있다.
request_module()로 module loading 요청을 할 수 없다.
사용자 space와 커널 space 사이에 데이터 전송을 할 수 없다.
Interrupt 핸들러
타이머 인터럽트를 제외한 모든 인터럽트를 쓰레드화
serialize된 인터럽트 처리를 우선순위화
각 인터럽트 쓰레드에게 실시간 우선순위와 SCHED_FIFO 스케줄링 policy를 할당
스케줄링을 통한 예측가능성
Bottom Half와 지연작업
Bottom Half란?
인터럽트 핸들러에 의해 처리되지 않는 인터럽트 관련 작업을 처리
작업 지연 개요
왜 작업을 지연하는가?
softirq와 tasklet
softirq : 정적으로 할당된 하반부 작업으로 어떤 CPU에서든지 동시에실행이 가능하다.
tasklet : softirq를 기반으로 하여 동적으로 생성된 하반부 작업