1 / 40

디바이스 드라이버 (Device Driver)

디바이스 드라이버 (Device Driver). Lecture #10. 목 차. (1) Linux Kernel Module Programming (2) Device Driver 정의 (3) Device Driver 종류 (4) Device Driver 작성 (5) 제작한 Device Driver 검증 파일 만들기 (6) Makefile 만들기 (7) Driver 를 커널에 모듈로 등록 및 해제하기. Kernel Module 정의 (1). 리눅스 커널 (Linux Kernel)

trynt
Télécharger la présentation

디바이스 드라이버 (Device Driver)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 디바이스 드라이버(Device Driver) Lecture #10

  2. 목 차 (1) Linux Kernel Module Programming (2) Device Driver 정의 (3) Device Driver 종류 (4) Device Driver 작성 (5) 제작한 Device Driver 검증 파일 만들기 (6) Makefile 만들기 (7) Driver를 커널에 모듈로 등록 및 해제하기

  3. Kernel Module 정의 (1) • 리눅스 커널(Linux Kernel) • 모노리스 커널(Monolithic Kernel) • cf) 마이크로 커널(Micro-kernel) • 커널의 기능을 확장하기 위해서는 커널 재컴파일이 필요 • 디바이스 드라이버를 추가하기 위해서도 커널 재컴파일이 필요 • 일반 사용자의 경우, 커널 재컴파일 과정이 어려움 • 커널 모듈(Kernel Module) • 실행시간에 커널을 확장하기 위해 사용하는 오브젝트 모듈 • 커널이 실행 중에 동적으로 로딩하여 커널과 링크함으로써 커널의 기능을 확장하여 사용할 수 있으며, 불필요 시에 커널과의 링크를 풀고 메모리에서 제거할 수 있다  커널 재컴파일이 필요없이 커널 기능 확장이 가능

  4. Kernel Module 정의 (2) • 커널 모듈(Kernel Module) (계속) • 명시적인 커널 모듈 설치 및 제거 과정이 필요 • Insmod / rmmod 명령어 • 디바이스 드라이버, 파일시스템, 네트워크 프로토콜 스택 등에 적용 • 커널 경량화를 위해 반드시 필요 • 임베디드 시스템의 경우, 제한적인 자원으로 인해 커널 등 시스템 소프트웨어의 최소화가 필요

  5. Kernel Module 정의 (3) • 커널 모듈 프로그래밍 • 커널 모듈은 커널 모드에서 실행됨으로 커널 프로그래밍에 준하여 작성되어야 한다 • 모듈 프로그래밍의 주의 사항 : • 무제한적인 메모리 접근  메모리 접근 오류는 시스템에 치명적인 손상을 줄 수 있음 • 커널 함수 호출에 따른 에러 코드 검사 • 실수 연산 및 MMX 연산 사용 불가 • 제한적인 커널 스택 크기 • 크기가 큰 배열 사용 회피  동적 할당 방법을 이용 • 재귀 호출 회피 • 상이 플랫폼 고려 • 32 bit 및 64 bit 환경 • 바이트 순서 – big-endian 또는 little-endian • 프로세서에 특화된 명령어 사용 회피 • 버전 종속성 - 커널 버전에 따라 모듈 버전이 다름

  6. Kernel Module 정의 (4) • 커널 모듈 버전 종속성(Version Dependency) • 커널 버전에 따라 지원되는 커널 함수의 종류나 프로토 타입이 다르기 때문에 다른 버전의 커널에 모듈을 링크하려면 모듈 재컴파일이 필요 • 모듈을 커널에 설치할 때에 버전 검사 수행 • 커널 버전과 모듈 버전이 일치하지 않는 경우에 모듈을 설치할 수 없음 • 커널 모듈 프로그램의 버전 정의 • 커널 ver.2.0 이상에서는 <linux/module.h> 헤드 파일에서 char kernel_version[ ] 변수에 커널 버전을 정의 • 커널 모듈 프로그램에서 위의 헤드 파일을 including #include <linux/module.h> • 커널 버전 정의는 전체 모듈에서 한번만 정의되어야 함

  7. Kernel Module 정의 (5) • 커널 모듈 버전 종속성(Version Dependency) (계속) • 커널 버전에 따른 종속적인 동작 정의 • <linux/version.h>에서 정의된 매크로 LINUX_VERSION_CODE 사용 #ifdef LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) // 리눅스 ver.2.4.0 이상일 때의 코드 #else // 리눅스 ver.2.4.0 미만일 때의 코드 #endif

  8. Kernel Module 작성 (1) • 커널 모듈 구성 • 커널 기능을 확장한 함수와 자료 구조로 구성 • main() 함수는 없는 독립된 프로그램 모듈 • init_module()/cleanup_module() 함수 존재 • init_module() 함수 • 모듈이 설치될 때에 자동적으로 호출 / 모듈 초기화 등의 기능 수행 • cleanup_module() 함수 • 모듈을 삭제할 때에 자동적으로 호출 / 모듈 제거에 따른 cleanup 작업을 수행 • 기본적인 구성  #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> /* global variables */ … int init_module(void) { } void cleanup_module(void) { } …

  9. Kernel Module 작성 (2) • 커널 모듈 구성 (계속) • 커널 ver.2.4 이상에서는 module_init() / module_exit() 매크로 지원 • 함수 이름에 의한 종속 관계를 해결 • module_init() 매크로 : startup 함수 등록 • module_exit() 매크로 : cleanup 함수 등록 #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> /* global variables */ … int module_start() { /* 모듈이 설치될 때에 초기화를 수행하는 코드 */ } int module_end() { /* 모듈이 제거될 때에 반환작업을 수행하는 코드 */ } module_init(module_start); module_exit(module_end); …

  10. Kernel Module 작성 (3) • 커널 모듈 구성 (계속) • 모듈 프로그램의 Makefile • -c : 링커를 호출하지 않고 오브젝트 모듈만 생성 • -O : 최적화 옵션 지정 (최대 O2) • 컴파일 매크로 : __KERNEL__ , MODULE, LINUX CC = arm_linux_gcc INCLUDEDIR = /kernel_source_dir/include CFLAGS := -c -O –Wall –D__KERNEL__ –DMODULE –DLINUX -I$(INCLUDEDIR) OBJS = hello.o all : $(OBJS) clean : rm –f *.o *.~ 커널 프로그램임을 명시하는 매크로 모듈 프로그램임을 명시하는 매크로 Linux 플랫폼에서 동작하는 모듈임을 정의하는 매크로

  11. 이 름 용 도 insmod module을 설치(install) rmmod 실행중인 modules을 제거(unload) lsmod Load된 module들의 정보를 표시 depmod Module들의 symbol들을 이용하여 Makefile과 유사한 dependency file을 생성 modprobe depmod명령으로 생성된 dependency를 이용하여 지정된 디렉토리의 module들과 연관된 module들을 자동으로 load modinfo 목적 파일을 검사해서 관련된 정보를 표시 Kernel Module 설치 및 제거 (1) • 커널 모듈 설치 및 제거 • 관련 쉘 명령어

  12. Kernel Module 설치 및 제거 (2) • 커널 모듈 설치 및 제거 (계속) • 설치된 모듈은 ‘/proc/modules’파일에 기록된다 • ‘/proc/modules’파일을 이용한 현재 설치된 모듈을 확인 가능 #cat /proc/modules

  13. Kernel Module 프로그래밍 (1) • 커널 모듈 프로그램 작성 • 모듈 적재 및 제거 시에 간단한 메시지 로그를 출력하는 모듈 작성 • 구현 방법 • 모듈 적재 시에 호출되는 init_module() 함수에서 printk() 함수를 이용하여 모듈 로딩(loading) 메시지를 출력한다 • 모듈 제거 시에 호출되는 cleanup_module() 함수에서 같은 방법으로 모듈 언로딩(unloading) 메시지를 출력한다 • 모듈 작성 및 테스트 • 모듈 프로그램 소스 파일 hello_m.c을 작성한다

  14. Kernel Module 프로그래밍 (2) • 커널 모듈 소스(hello_m.c) #include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_ALERT */ int init_module(void){ printk("<1>hello module loaded\n"); // A non 0 return means init_module failed return 0; } void cleanup_module(void){ printk(KERN_ALERT "hello module unloaded\n"); }

  15. Kernel Module 프로그래밍 (3) • 함수 printk()의 인수 : • File "/lib/modules/`uname –r`/build/include/linux/kernel.h"에 정의 #define KERN_EMERG "<0>" /* system is unusable */ #define KERN_ALERT "<1>" /* action must be taken immediately */ #define KERN_CRIT "<2>" /* critical conditions */ #define KERN_ERR "<3>" /* error conditions */ #define KERN_WARNING "<4>" /* warning conditions */ #define KERN_NOTICE "<5>" /* normal but significant condition */ #define KERN_INFO "<6>" /* informational */ #define KERN_DEBUG "<7>" /* debug-level messages */

  16. Kernel Module 프로그래밍 (4) • 매크로 module_init/module_exit 사용 #include <linux/module.h> // Needed by all modules #include <linux/kernel.h> // Needed for KERN_ALERT #include <linux/init.h> // Needed for the macros static int hello_init(void){ printk(KERN_ALERT “hello module loaded\n”); return 0; } static void hello_exit(void){ printk(KERN_ALERT “hello module unloaded\n”); } module_init(hello_init); module_exit(hello_exit);

  17. Kernel Module 프로그래밍 (5) • 모듈 작성 및 테스트 • Makefile을 작성하고 컴파일을 수행한다 TARGET = hello_m WARN = -Wall -Wstrict-prototypes -Wmissing-prototypes INCLUDE = -isystem /lib/modules/`uname -r`/build/include CFLAGS = -O2 -DMODULE -D__KERNEL__ ${WARN} ${INCLUDE} CC = arm_linux_gcc $(TARGET).o: $(TARGET).c clean: rm -rf $(TARGET).o

  18. Kernel Module 프로그래밍 (6) • 모듈 작성 및 테스트 • 모듈 ‘hello_m.o’을 다운로드하고 다음과 같이 테스트한다 • 모듈 load 명령 줄 # insmod hello.o • 모듈 load 확인 명령 줄 # lsmod Module Size Used by hello 368 0 (unused) • 모듈 unload 명령 줄 # rmmod hello • printk() 메시지 확인 # tail -2 /var/log/messages Oct 12 17:54:29 kernel: hello module loaded Oct 12 17:54:45 kernel: hello module unloaded

  19. 리눅스 디바이스 • 디바이스(device)는 키보드, 마우스, 터미널, 프린터, 디스크 등과 같은 하드웨어 주변 장치를 말함 • 리눅스에서 디바이스의 사용 –각 디바이스를 대변하는 디바이스 파일에 파일 입출력 시스템 호출(예: open/read/close 등)을 사용 • 디바이스 분류 - character(문자)/block(블록)/network(네트워크) • 디바이스 번호 - character/block device는 major/minor 번호를 가짐 • 디바이스 특수 파일 생성 - "mknod 파일이름 분류 major minor"

  20. 디바이스 파일 (/dev) lrwxrwxrwx1 rootroot54월 12 21:26mouse -> psaux brw-rw----1 rootdisk3, 01월 30 2003 hda brw-rw---- 1 root disk 3, 64 1월 30 2003 hdb brw-rw---- 1 root disk 8, 0 1월 30 2003 sda brw-rw---- 1 root disk 8, 16 1월 30 2003 sdb brw-rw---- 1 ecl1 floppy 2, 0 1월 30 2003 fd0 brw-rw---- 1 ecl1 floppy 2, 1 1월 30 2003 fd1 crw-rw---- 1 root lp 99, 0 1월 30 2003 parport0 crw-rw---- 1 root lp 99, 1 1월 30 2003 parport1 crw--w---- 1 root root 4, 0 1월 30 2003 tty0 crw------- 1 root root 4, 1 4월 19 18:05 tty1

  21. Device Driver 정의 (1) • 물리적인 hardware 장치를 다루고 관리하는 커널 프로그램 • user application이 driver에게 요청을 하면, driver는 hardware를 구동시켜서 목적을 달성 • 디바이스와 응용 프로그램 사이에 존재하여 데이터 전달 등의 기능을 담당 • 디바이스 파일에 대한 입출력 시스템 호출(예: open/ read/write/close 등)을 제공 • 디바이스의 복잡하고 고유한 특성을 사용자에게 숨기고 디바이스 입출력 프로그래밍을 일반 파일 입출력 프로그램과 유사하게, 쉽게 하게함

  22. User application level task task task task System call interface Kernel level File system DDI (device driver interface) Char Driver Block Driver Network Driver Hardware level ethernet terminal keyboard Hard disk CD-ROM Device Driver 정의 (2)

  23. Driver 종류 설 명 Char Driver device를 file처럼 취급하고 접근하여 직접 read/write를 수행, data 형태는 stream 방식으로 전송 EX) console, keyboard, serial port driver등 등록함수명 Block Driver disk와 같이 file system을 기반으로 일정한 blcok 단위로 data read/write를 수행 EX) floppy disk , hard disk, CD-ROM driver 등 register_chrdev() Network Driver network의 physical layer와 frame 단위의 데이터를 송수신 EX) Ethernet device driver(eth0) register_blkdev() register_netdev() Device Driver 종류

  24. #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/init.h> Header Files Printf와 같은 기능의 커널 코드를 위한 함수 “파일시스템”헤더는 디바이스 드라이버를 쓰는데 필요한 헤더파일 필요한 header. 모듈소스가 include해야함 module_init(init_function) Module 설치 시 초기화 수행 module_exit(cleanup_function) Module 제거 시 반환작업 수행 Module_init()과 module_exit()정의됨 static int device_open(); static int device_release(); ssize_t device_read(); static ssize_t device_write(); int init_function(); void cleanup_function(); Function Prototypes insmod로 모듈을 적재하면 이 함수가 불려진다. 이 함수 안에서 regiseter_chrdev()커널 함수를 뷸러서 모둘을 적재한다. rmmod로 적재된 모듈을 삭제할 경우 이 함수가 불려진다. unregister_chrdev()커널 함수를 불려서 모듈을 삭제한다. static struct file_operations device_fops={ open : device_open, release : device_release, read : device_read, write : device_write,}; Device Opertations application에서 쓰는 함수와 driver에서 쓰는 함수를 mapping Device Driver 작성 (1) • 기본적인 device driver의 형태

  25. Device Driver 작성(2) #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/init.h> #define DEV_NAME "test_dd" int test_major = 0; int result; ///////////// 함 수 정 의 ////////////// int device_open (struct inode *inode, struct file *filp); int device_release (struct inode *inode, struct file *filp); ssize_t device_read (struct file *filp, unsigned int *buf, size_t count, loff_t *f_pos); ssize_t device_write (struct file *filp, unsigned int *buf, size_t count, loff_t *f_pos); int device_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned int arg); int sample_init(); void sample_cleanup(); 모듈을 커널에 적재하는 함수 register_chrdev()의 parameter로써 0으로 설정하면 major값을 뒤에서부터 자동으로 빈자리로 등록시킨다 register_chrdev()함수가 return하는 값을 넘겨받음. 0보다 적으면 모듇 등록 실패 application에서 open()함수로 driver를 호출할때 실행되는 함수 application에서 close()함수로 driver를 닫을때 실행되는 함수 application에서 kernel로부터 넘어온 값을 처리하는 함수

  26. Device Driver 작성 (3) int device_open (struct inode *inode, struct file *filp) { printk("test_open start!!!\n"); MOD_INC_USE_COUNT; return 0; } int device_release (struct inode *inode, struct file *filp) { MOD_DEC_USE_COUNT; return 0; } ssize_t device_read (struct file *filp, unsigned int *buf, size_t count, loff_t *f_pos) { printk("read() ^^\n"); return 0; } ssize_t device_write (struct file *filp, unsigned int *buf, size_t count, loff_t *f_pos) { return 0; } 이 함수가 호출될때마다 count가 증가한다. 이 함수가 호출될때마다 count가 감소한다. Application에서 read함수를 호출하면 terminal에 문자 출력

  27. Device Driver 작성 (4) int device_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned int arg) { printk("ioctl() ^^\n"); return 0; } struct file_operations test_fops = { open: device_open, read: device_read, write: device_write, ioctl: device_ioctl, release: device_release, }; module_init(sample_init); module_exit(sample_cleanup); Ioctl()호출이 성공하면 문자 출력 파일연산구조체는 char device driver에 대한 모든 연산을 포함한다. 즉 여기에 정의된 함수를 통해서 커널이 접근하게 된다. 즉 application에서 open함수를 호출하면 이는 driver의 test_open()과 mapping되어있어 이를 실행하게 된다. insmod로 불려지는 함수 rmmod로 불려지는 함수

  28. Device Driver 작성 (5) int sample_init(void) { result = register_chrdev(test_major, DEV_NAME, &test_fops); if (result < 0) { printk(KERN_WARNING "%s: can't get major %d\n", DEV_NAME, test_major); return result; } printk("<1> init module success!!.. %s major number : %d\n", DEV_NAME, result); return 0; } void sample_cleanup(void) { if( !unregister_chrdev(result, DEV_NAME) ) printk("%s cleanup_module success...\n", DEV_NAME); else printk("%s cleanup_module fail...\n", DEV_NAME); } driver를 커널에 모듈로 등록하는 함수, result에 major 값이 넘어옴 driver를 커널에서 삭제하는 함수

  29. Device Driver 작성 (6) • 구조체 struct file_operations static struct file_operations skeleton_fops = { THIS_MODULE, /* struct module *owner;*/ NULL, /* skeleton_llseek */ skeleton_read, /* skeleton_read */ skeleton_write, /* skeleton_write */ NULL, /* skeleton_readdir */ NULL, /* skeleton_poll */ skeleton_ioctl, /* skeleton_ioctl */ NULL, /* skeleton_mmap */ skeleton_open, /* skeleton_open */ NULL, /* skeleton_flush */ skeleton_release, /* skeleton_release */ NULL, /* skeleton_fsync */ NULL, /* skeleton_fasync */ NULL, /* skeleton_lock */ NULL, /* skeleton_readv */ NULL /* skeleton_writev */ };

  30. Device Driver 검증 프로그램 만들기(1) #include <stdio.h> #include <fcntl.h> #include <string.h> #include <errno.h> int fd; int main(int argc, char **argv) { if( (fd = open("/dev/testdd", O_RDWR)) < 3) { fprintf(stderr, "/dev/testdd device file open error!! .. %s\n",strerror(errno)); return 0; } read(fd, 0, 0); ioctl(fd, NULL,0); close(fd); return 0; } File에 대한 제어와 설정 Error에 관한 header file mknod를 통하여 /dev에 만들어진 node(file)을 open한다.

  31. Device Driver 검증 프로그램 만들기(2) 경고를 다 출력해준다는 의미 • Compile Options %arm-linux-gcc –c –D__KERNEL__ -DMODULE –Wall –O2 –o test_dd.o test_dd.c test_dd는 커널에서 동작하고 모듈에 사용된다는 뜻 모듈은 test_dd.o로 컴파일 되어야 하므로 –c 옵션 사용 Compile과정에서 inlne 함수를 확장할 때 최적화함

  32. Device Driver 검증 프로그램 만들기(3) CC =arm-linux-gcc INCLUDEDIR = /usr/local/pza255/linux-2.4.19-huins/include CFLAGS = -D__KERNEL__ -DMODULE -Wall -O2 CFLAGS2 = -I.. -I$(INCLUDEDIR) All: test_dd test_app test_dd : test_dd.c $(CC) $(CFLAGS) $(CFLAGS2) -c -o test_dd.o test_dd.c test_app : test_app.c $(CC) -o test_app test_app.c clean : rm -rf test_dd.o test_app Macro 부분 C에서 define 역할 target command Command 부분 파일들의 dependency를 설정 주의할 점은 이 공백은 반드시 Tab 공백

  33. Device Driver 등록 및 해제 (1) • Char Device Driver 등록 방법 • 외부와 device driver는 file interface (node를 의미)를 통해 연결 • Device driver는 자신을 구별하기 위해 고유의 major number를 사용 • 장치의 등록과 해제 • 등록 :int register_chrdev(unsigned int major, const char *name, stuct file_operations *fops) • Major : 등록할 major number. 0이면 사용하지 않는 번호 중 자동으로 할당 • Name : device의 이름 • Fops : device에 대한 file 연산 함수들 • 해제 :int unregister_chrdev(unsigned int major, const char *name)

  34. user program open close read write kernel device driver file operations device_open device_close device_read device_write system call device Device Driver 등록 및 해제 (2)

  35. Device Driver 등록 및 해제 (3) • Major number와 minor number • 장치를 구분하는 방법으로 둘을 이용하여 특정 장치를 구별 • Major number : 커널에서 디바이스 드라이버를 구분하는데 사용 • Minor number : 디바이스 드라이버 내에서 필요한 경우 장치를 구분하기 위해 사용 • 새로운 디바이스는 새로운 major number를 가져야 함 • register_chrdev()로 장치를 등록할 때 major number를 지정 • 같은 major number가 등록되어 있으면 등록 실패 • Major와 minor 번호는 파일의 정보를 담고 있는 inode의 i_rdev에 16bit로 저장된다. 상위 8bit는 major, 하위 8bit는 minor이다.

  36. Device Driver 등록 및 해제 (4) • mknod 명령으로 디바이스 드라이버에 접근할 수 있는 장치 파일 생성 • mknod [device file name] [type] [major] [minor] Ex] %mknod testdd c 252 0 • mdev_t : 장치의 major, minor number를 표현하는 자료구조 • MAJOR() : kdev_t에서 major number를 얻어내는 매크로 Ex] MAJOR(inode->i_rdev); • MINOR() : kdev_t에서 minor number를 얻어내는 매크로 • cat /proc/devices 명령으로 현재 로드된 디바이스 드라이버 확인 C는 char device drive의미, block device drive는 b를 사용

  37. Device Driver 등록 및 해제 (5) • /usr/lcoal/pxa255/linux-2.4.19-cd/include/linux/fs.h 앞에서 작성했던 driver에 사용된 파일연산 함수

  38. Device Driver 등록 및 해제 (6) • Device Driver의 동작 과정

  39. Device Driver 등록 및 해제 (7) • 앞에서 만든 드라이버 소스를 test_dd.c, test application은 test_app.c, 그리고 makefile은 Makefile로 작성 후 저장한다. • make 명령어를 이용하여 위의 2 files을 컴파일한다. % make • 생성된 test_dd.o 와 test_app를 target으로 전송한다. 전송방식은 앞에서 배웠던 minicom 또는 nfs방식을 이용한다. 밑에서는 nfs 방식을 통하여 파일을 전송하였다.

  40. Module을 kernel에 적재 Test application에서 open()로 이 nod를 연다. 이 nod로 application과 hardware가 만남 Device Driver 등록 및 해제 (8) major number는 253 ls 명령으로 nod가 잘 만들어졌는지 확인. 253은 major 번호 결과 화면

More Related