2.14k likes | 2.75k Views
㈜ 레 드 닉 스 정보통신. 2001. 8. 1 ~ 3. Linux Device Driver 설계 기술. 대전광역시 유성구 봉명동 538-8, 동아오피스텔 617 호 TEL: (042) 828-7369 FAX : (042) 828-7364. 차례. 리눅스 개요 커널 개요 커널 인터페이스 디바이스 드라이버 개요 문자 디바이스 드라이버 인터럽트와 폴링 블록 디바이스 드라이버 네트워크 디바이스 드라이버 실습. 리눅스 개요. 리눅스란 ?. Linus Torvalds( 핀란드 ) 가 개발
E N D
㈜ 레드닉스 정보통신 2001. 8. 1 ~ 3 Linux Device Driver 설계 기술 대전광역시 유성구 봉명동 538-8, 동아오피스텔 617호 TEL: (042) 828-7369 FAX : (042) 828-7364 Embedded System based on BSD & Linux - 1 - www.rednix.com
차례 • 리눅스 개요 • 커널 개요 • 커널 인터페이스 • 디바이스 드라이버 개요 • 문자 디바이스 드라이버 • 인터럽트와 폴링 • 블록 디바이스 드라이버 • 네트워크 디바이스 드라이버 • 실습 Embedded System based on BSD & Linux - 2 - www.rednix.com
리눅스 개요 Embedded System based on BSD & Linux - 3 - www.rednix.com
리눅스란? • Linus Torvalds(핀란드)가 개발 • 1991년 0.01 버전 발표 • Minix 기반 • GPL(GNU Public License) • Everyone has the right to use, copy, and modify the programs free of charge. • 현재 커널 버전 2.4.7 • 배포판들 • Redhat, alzza, wow, suse, devian, … Embedded System based on BSD & Linux - 4 - www.rednix.com
리눅스의 특징 • UNIX-like 운영체제 • Multi-tasking • Multi-user access • Multi-processing • since version 2.0 • SMP(Symmetric Multi Processing) • Architecture independent • x86, sparc, mips, arm, alpha, … • Demand load executables • Copy-on-write: only those parts of a program actually required for execution are loaded into memory. Embedded System based on BSD & Linux - 5 - www.rednix.com
리눅스의 특징 • Paging • 4Kbyte memory page • Cf. swapping • Dynamic cache for hard disk • Dynamically adjusts the size of cache memory in use to suit the current memory usage situation • Shared libraries • Support for POSIX 1003.1 standard and in part System V and BSD • POSIX defines a minimun interface to a UNIX-type operating system • Variouse formats for executable files • Elf, coff, MS-Windows emulator Embedded System based on BSD & Linux - 6 - www.rednix.com
리눅스의 특징 • Memory protected mode • Support for national keyboards and fonts • Different file systems • Ext2, FAT, NFS. … • Various network protocols • TCP/IP, SLIP, and PPP support Embedded System based on BSD & Linux - 7 - www.rednix.com
리눅스 버전 2 . 2 . 17 주번호 패치 레벨 부번호 짝수 : 안정 버전 홀수 : 개발 버전 Embedded System based on BSD & Linux - 8 - www.rednix.com
Embedded Linux • Embedded System • Small computing systems that contains various peripheral for special purpose on the small PCB. • Embedded OS • Considering point • Image size • Easy to develepment • Developing emvironment • Real time funtionality • Custom embedded OS’s • VxWorks(Wind River) • Nucleos(ATI) • pSOS(ISI/Wind River) • WinCE(Microsoft) • SuperTask, VRTX, Lynx, QNX. … Embedded System based on BSD & Linux - 9 - www.rednix.com
Embedded Linux • What is the Embedded Linux? • Embedded system에 포팅된 Linux • 별도의 real time 기능을 제공하지 않음 • RTLinux • Linux에 hard real time 기능 부여 • 기존 커널을 RTLinux상에서 돌아가는 하나의 task로 인식 Embedded System based on BSD & Linux - 10 - www.rednix.com
Embedded Linux • Advantages • Open source • No license free, no running royalty • No limit to use(GPL) • Stable(?), reliable, and scalable • TCP/IP connectivity • Easy to port driver, and application • Open documents on internet • Disadvantages • Lack of debugger • Large code size • Need large size of flash and DRAM • Embedded Linux is not RTOS Embedded System based on BSD & Linux - 11 - www.rednix.com
커널 개요 Embedded System based on BSD & Linux - 12 - www.rednix.com
커널 규격 • Proportion of source text accounted for by the individual component(as of v2.0) • Central routine for process and memory management only take up around 5% Embedded System based on BSD & Linux - 13 - www.rednix.com
커널 구성 • Linux 디렉토리 구조 Embedded System based on BSD & Linux - 14 - www.rednix.com
커널 구성 • 디렉토리별 분류 • arch: machine dependent kernel code • include: header files • init: kernel 초기화 • mm: architecture independent memory management • arch/*/mm: system dependent memory management • driver: device drivers • char/, block/, cdrom/, net/, scsi/, ... • ipc: interprocess communication code • modules: 컴파일된 모듈 • fs: file system • ext2/, vfat/, hpfs/, msdos/, ... Embedded System based on BSD & Linux - 15 - www.rednix.com
커널 구성 • kernel: architecture independent kernel code • arch/*/kernel: architecture dependent kernel code • net: network code • lib: library code • arch/*/lib: architecture dependent libraries • scripts: 커널 구성을 위한 스크립터 Embedded System based on BSD & Linux - 16 - www.rednix.com
커널의 주요 함수 • 시스템 시작 및 초기화 • arch/i386/kernel/head.S • 일련의 시스템 구조 의존적인 초기화를 수행한 후, init/main.c의 start_kernel() 함수 호출 • start_kernel() start_kernel() { setup_arch(); paging_init(); trap_init(); init_IRQ(); sched_init(); time_init(); ... kernel_thread(init); cpu_idle() } init() { setup(); ... execve(“/sbin/init”); ... } Embedded System based on BSD & Linux - 17 - www.rednix.com
커널의 주요 함수 • 메모리 관리 • 페이지 폴트 핸들링: mm/memory.c • 메모리 매핑 및 페이지 캐슁: mm/filemap.c • 버퍼 캐쉬: mm/buffer.c • 스왑 캐쉬: mm/swap_state.c, mm/swapfile.c • 커널 기능 • 스케쥴러: kernel/sched.c • Fork: kernel/fork.c • Bottom half of interrupt handling: include/linux/interrupt.h • Process table: include/linux/sched.h • Interrupt handling • 대부분 architecture dependent • arch/i386/kernel/irq.c Embedded System based on BSD & Linux - 18 - www.rednix.com
커널의 주요 함수 • 네트워크 • Networking code in net/ • Header files in include/net • BSD socket code: net/socket.c • IP version 4 INET code: net/ipv4/af_inet.c • Generic protocol support code: net/core • TCP/IP networking code: net/ipv4 Embedded System based on BSD & Linux - 19 - www.rednix.com
커널 컴파일 • Step 1: Kernel configuration % make config | make menuconfig | make xconfig • Read arch/$ARCH/config.in and run scripts/Configure • Create <linux/autoconf.h> and .config • linux/autoconf.h: conditional compiling within the kernel • .config: controls the sequencing of the compilation • Step 2: Dependency calculation % make dep • .depend files are created in each directory • Step 3: Kernel compile % make • To create vmlinux file % make boot | make zImage | make bzImage • To make compressed bootable linux kernel • arch/i386/boot/compressed/zImage(or bzImage) Embedded System based on BSD & Linux - 20 - www.rednix.com
커널 인터페이스 Embedded System based on BSD & Linux - 21 - www.rednix.com
Timer • Timer • init_timer(struct timer_list *timer) • timer_list구조의 전후방 포인터 nullify • add_timer(struct timer_list *timer) • timeout 설정 • del_timer(struct timer_list *timer) • timeout 해제 timer_list *next *prev expires data (*function)() Embedded System based on BSD & Linux - 22 - www.rednix.com
Port I/O • Port I/O • inb(unsigned short port), inb_p(unsigned short port) • Port로부터 1byte 읽음 • outb(char value, unsigned short port) outb_p(char value, unsigned short port) • Port에 1byte의 value를 출력함 • inb_p(), outb_p(): inb()/outb() and pause의 의미 • inw(), inw_p(), outw(), outw_p() • Port로부터 short int(2byte) 읽거나 출력함 • inl(), inl_p(), outl(), outl_p() • Port로부터 long int(4byte) 읽거나 출력함 • insb(unsigned int port, void *to, int len) • Port로부터 len bytes를 읽어, to가 가리키는 메모리에 저장 • insb_p(), outsb(), outsb_p(), insw(), insw_p(), outsw(), outsw_p(), insl(), insl_p(), outsl(), outsl_p() Embedded System based on BSD & Linux - 23 - www.rednix.com
Interrupt • Interrupt • cli()/sti() • Clear/set interrupt enable • save_flags(), restore_flags() • Status register의 내용을 저장하고 복원한다. • request_irq(unsigned int irq, void (*handler)(int), unsigned long flags, const char *device) • 커널로부터 IRQ를 요청하여, IRQ interrupt handler를 install한다. • free_irq(unsigned int irq) • request_irq()에서 획득한 irq를 반납함 register unsigned long flags; save_flags(flags); cli(); ... restore_flags(flags); Embedded System based on BSD & Linux - 24 - www.rednix.com
Memory • Memory • kmalloc(unsigned int len, int priority) • 커널 메모리 할당. 128 ~ 131056 byte까지 가능 • Priority: GFP_BUFFER, GFP_ATOMIC, GFP_USER, GFP_KERNEL • kfree(void *obj) • kmalloc()에서 할당받은 커널 메모리(obj)를 반납 • vmalloc(unsigned int len), vmfree(void *addr) • 커널 메모리 할당/반납. 크기 제한 없음. • memcpy_xxfs(void *to, const void *from, unsigned long n) • 커널주소공간과 사용자주소공간 사이에 memory copy • xx = from/to • memset(void *s, char c, sizt_t count) • 메모리 s에 c를 count만큼 복사 Embedded System based on BSD & Linux - 25 - www.rednix.com
동기화 • 동기화 • sleep_on(struct wait_queue **q) • q의 번지를 event로 sleep하며, uninterruptible이다. • sleep_in_interruptible(struct wait_queue **q) • q의 번지를 event로 sleep하며, interruptible이다. • wake_up(struct wait_queue **q) • sleep_on(q)에 의해 sleep한 task를 wakeup한다. • wake_up_interruptible(struct wait_queue **q) • sleep_on_interruptible(q)에 의해 sleep한 task를 wakeup한다. Embedded System based on BSD & Linux - 26 - www.rednix.com
Print • Print • printk(const char *fmt, …) • printf의 커널 버전 • printk(LOG_LEVEL message) • LOG_LEVEL: KERN_EMERG, KERN_ALERT, KERN_ERR, KERN_WARNING, KER_INFO, KERN_DEBUG • 예 • printk(“<1>Hello, World”); • printk(KERN_WARNING “warning…\n”); • sprintf(char *str, const char *fmt, …) • print to string Embedded System based on BSD & Linux - 27 - www.rednix.com
Driver • Driver register • register_xxxdev(unsigned int major, const char *name, struct file_operations *fops) • Character/block driver를 xxxdevs[major]에 등록 • xxx: blk/chr • unregister_xxxdev(unsigned int major, const char *name) • xxxdevs[major]에 등록되어 있는 device driver를 제거 • MAJOR(a)/MINOR(a) • 장치번호 a로부터 major/minor 번호를 구함 Embedded System based on BSD & Linux - 28 - www.rednix.com
디바이스 드라이버 개요 Embedded System based on BSD & Linux - 29 - www.rednix.com
Overview Embedded System based on BSD & Linux - 30 - www.rednix.com
Device Class • Character device • 자료의 순차성을 지닌 장치 • 일반적으로 위치 포인터 이동 불가 • 장치의 raw data를 사용자에게 제공 • Console, tape, keyboard, sound card, printer, serial/parallel port 등 • Block device • Random access가 가능한 장치 • File system에 의해 mount되어 관리되는 장치 • 블록 단위의 입출력이 가능한 장치 • 디스크, CD-ROM, floppy 등 • Network interface • Network transaction interface • 기타 • SCSI: SCSI 통신 protocol로 구현 • Device modules in kernel: file system 등 Embedded System based on BSD & Linux - 31 - www.rednix.com
Device files • 장치 파일 • 장치 노드를 통해 장치 접근 경로 제공 • Type, major number, minor number에 의해 구분 • 장치 파일 생성 % mknod /dev/scull0 c 127 0 % mknod /dev/sbull0 b 127 0 % ls –l /dev crw-rw-rw- 1 root tty 4, 64 May 6, 1998 ttyS0 crw-rw-rw- 1 root tty 4, 65 May 6, 1998 ttyS1 brw-rw---- 1 root disk 3, 1 May 6, 1998, hda1 brw-rw---- 1 root disk 3, 2 May 6, 1998, hda2 Character/block Major number Minor number Embedded System based on BSD & Linux - 32 - www.rednix.com
Device number • Major/minor number • Major number: device에 관련된 driver 지정 • 0 ~ 255 • include/linux/major.h, Documentation/devices.txt • Minor number: device driver 내에서 한 종류의 여러 개의 device를 구분하기 위해 사용 Embedded System based on BSD & Linux - 33 - www.rednix.com
Device driver functions • Device driver 초기화 함수 • Device 초기화 • Device driver 자료구조 초기화 • Device driver 등록 • Device driver 진입 함수 • Device file을 통로로, system call로 호출 • File operations • Top half, Bottom half • Interrupt service routine Embedded System based on BSD & Linux - 34 - www.rednix.com
Device driver interface user Program open close read write kernel Device driver isr rx_isr tx_isr file operations dev_open dev_close dev_read dev_write System call interrupt device Embedded System based on BSD & Linux - 35 - www.rednix.com
System Call • System call • 소프트웨어 개발자가 UNIX 커널로 들어가기 위한 수단 • System call의 종류 • 파일에 대한 명령 수행: read, write, ioctl • 프로세스에 대한 명령 수행: fork, exec, signal • 기타: 시스템 전체에 대한 정보 제공(날짜, 시간 등) Embedded System based on BSD & Linux - 36 - www.rednix.com
System Call • System call을 사용한 device 접근 #include <fcntl.h> #include <unistd.h> main() { int fd; char buf[20]; fd = open(“/dev/scull0”, O_RDWR); write(fd, “hello, World”, 12); read(fd, buf, 10); close(fd); } Embedded System based on BSD & Linux - 37 - www.rednix.com
장치 자료 구조 fs/devices.c struct device_struct { char *name; struct file_operations *fops; } chrdevs[MAX_CHRDEV], blkdevs[MAX_BLKDEV]; struct file_operations { lseek, read, write, readdir, select, ioctl, mmap, open, release, fsync, ... }; include/linux/blkdev.h struct blk_dev_struct { void (*request_fn)(void); struct request *current_request; ... } blk_dev[MAX_BLKDEV]; Embedded System based on BSD & Linux - 38 - www.rednix.com
Driver 등록 및 삭제 • Deriver 등록 • Driver 초기화시 혹은 동적 모듈 추가시 driver 등록 • register_xxxdev() 함수에서 major number, name, fops를 parameter로 전달 #include <linux/fs.h> int register_xxxdev(unsigned int major, const char *name, struct file_operations *fops) int unregister_xxxdev(unsigned int major, const char *name) file_operations blkdevs[] chrdevs[] 0 dev_lseek, dev_read, dev_write, NULL, dev_ioctl, ... “dev_name” name major fops MAX_xxxDEV-1 Embedded System based on BSD & Linux - 39 - www.rednix.com
file_operations • file_operations • linux/include/linux/fs.h struct file_operations { int (*lseek) (struct inode *, struct file *, off_t, int); int (*read) (struct inode *, struct file *, char *, int); int (*write) (struct inode *, struct file *, const char *, int); int (*readdir) (struct inode *, struct file *, void *, filldir_t); int (*select) (struct inode *, struct file *, int, select_table *); int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long); int (*mmap) (struct inode *, struct file *, struct vm_area_struct *); int (*open) (struct inode *, struct file *); void (*release) (struct inode *, struct file *); int (*fsync) (struct inode *, struct file *); int (*fasync) (struct inode *, struct file *, int); int (*check_media_change) (kdev_t dev); int (*revalidate) (kdev_t dev); }; Embedded System based on BSD & Linux - 40 - www.rednix.com
file_operations • lseek • 파일에서 현재의 read/write 위치를 옮긴다. • read • Device에서 data를 가져옴 • write • Device에 data를 보낸다. • readdir • 디바이스 노드에서는 사용 안함. 디렉토리에 대해서만 사용. • select • 현재의 프로세스를 대기큐에 넣는다. • ioctl • 디바이스에 종속적인 명령을 만들 수 있도록 한다. • mmap • 디바이스 메모리를 프로세스의 메모리에 맵핑시키도록 요청 • open • 디바이스 노드에 대해 수행되는 첫번째 동작 Embedded System based on BSD & Linux - 41 - www.rednix.com
file_operations • release • 노드를 닫을 때 수행된다. • fsync • 데이터 중에서 버퍼에 있는 것은 모두 디바이스에 쓴다. • fasync • FASYNC 플래그에 변화가 있는 디바이스를 확인하기 위해 사용한다. • check_media_change • 물리적 미디어가 마지막 동작 후에 교체되었늕지, 그대로 있는지 판단하기 위해 커널이 호출한다. 블록 디바이스에서 사용 • revalidate • 버퍼캐쉬의 관리를 한다. 블록 디바이스에서 사용 Embedded System based on BSD & Linux - 42 - www.rednix.com
file 구조체 • File 구조체 • linux/include/linux/fs.h struct file { mode_t f_mode; loff_t f_pos; unsigned short f_flags; unsigned short f_count; unsigned long f_reada, f_ramax, f_raend, f_ralen, f_rawin; struct file *f_next, *f_prev; struct fown_struct f_owner; struct inode * f_inode; struct file_operations * f_op; unsigned long f_version; void *private_data; }; Embedded System based on BSD & Linux - 43 - www.rednix.com
file 구조체 • f_mode • FMODE_READ/FMODE_WRITE. 커널이 드라이버를 구동하기 전에, read/write 권한을 위해 이 field를 검사한다. • f_pos • 현재의 읽기/쓰기 위치. • f_flags • O_RDONLY/O_NONBLOCK/O_FASYNC 과 같은 file flag들. • f_op • 파일과 관련된 동작들. • private_data • 드라이버가 자체적으로 사용할 데이터 영역. Embedded System based on BSD & Linux - 44 - www.rednix.com
kdev_t • 디바이스 타입을 나타냄 • inode 구조체의 i_rdev 필드 사용 struct inode { ... kdev_t i_rdev; ... }; Embedded System based on BSD & Linux - 45 - www.rednix.com
kdev_t • kdev_t에 관련된 macro와 함수들 • MAJOR(kdev_t dev): 주번호 추출 • MINOR(kdev_t dev): 부번호 추출 • MKDEV(int ma, int mi): 주번호와 부번호로부터 kdev_t를 만듬 • kdev_t_to_nr(kdev_t dev): kdev_t 타입을 숫자로 변환 • to_kdev_t(int dev): 숫자를 kdev_t로 변환 • Major/minor number 추출 • major = MAJOR(inode->i_rdev); • minor = MINOR(inode->i_rdev); Embedded System based on BSD & Linux - 46 - www.rednix.com
문자 디바이스 드라이버 Embedded System based on BSD & Linux - 47 - www.rednix.com
문자 드라이버 작성 순서 • Device 구조를 나타내기 위한 자료구조 정의 • Device에 대한 major number 결정 • 파일 연산자(file operations) 정의 • Device driver 초기화 함수 작성 • Device driver의 등록, • Device 자료구조 초기화 • Driver를 커널에 등록 • Device node 파일 작성 Embedded System based on BSD & Linux - 48 - www.rednix.com
Scull • Simple Character Utility for Loading Localities • 메모리 영역을 디바이스처럼 취급하는 문자드라이버 • Scull device의 구조 Scull_Dev Scull_Dev Scull_Dev next data next data next data quantum typedef struct Scull_Dev { void **data; struct Scull_Dev *next; int quantum; int qset; unsigned long size; unsigned int access_key; unsigned int usage; } Scull_Dev; Scull_Dev *scull_devices; qset Embedded System based on BSD & Linux - 49 - www.rednix.com
Scull device driver의 구조 struct file_operations scull_fops = { scull_lseek, scull_read, scull_write, NULL, ... scull_open, scull_release } int scull_lseek() { ... } int scull_read() { ... } int scull_write() { ... } int scull_open() { ... } int scull_release() { ... } ... scull_init(void) { register_chrdev(scull_major, “scull”, &scull_fops); } scull_close(void) { unregister_chrdev(scull_major, “scull”); } Embedded System based on BSD & Linux - 50 - www.rednix.com