1 / 60

IT 특론 1 : 고급 운영체제 특강 (Linux 커널을 중심으로 )

IT 특론 1 : 고급 운영체제 특강 (Linux 커널을 중심으로 ). 단국대학교 정보 컴퓨터학부 2003 년 1 학기 최종무 choijm@dankook.ac.kr. 강의 교재. 주 교재 강의 노트 참고 교재 M. Beck, H. Bohme, M Dziadzka, U Kunitz, R. Magnus, D. Verworner, “Linux Kernel Internals”, Addison-Wesley

maeve
Download Presentation

IT 특론 1 : 고급 운영체제 특강 (Linux 커널을 중심으로 )

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. IT 특론1 : 고급 운영체제 특강(Linux커널을 중심으로) 단국대학교 정보 컴퓨터학부 2003년 1학기 최종무 choijm@dankook.ac.kr

  2. 강의 교재 • 주 교재 • 강의 노트 • 참고 교재 • M. Beck, H. Bohme, M Dziadzka, U Kunitz, R. Magnus, D. Verworner, “Linux Kernel Internals”, Addison-Wesley • Maurice J. Bach, “The Design of the UNIX Operating System”, Prentice Hall. • Mukesh Singhal and Niranjan G. Shivaratri, “Advanced Concepts in Operating Systems”, McGraw-Hill • W. Richard Steven, “Advanced Programming in the UNIX Environment”, Addison-Wesley • 조유근, 최종무, 홍지만, “리눅스 매니아를 위한 커널 프로그래밍”, 교학사 • http://www.linux.org/http://www.kernel.org/ • Daniel P. Bovet, Marco Cesati, “Understanding the Linux Kernel”, O'Reilly • A. Rubini, “LINUX Device Driver”, O’REILLY • Anonymous, “Maximum Linux Security”, SAMS Publishing • F. Butzen, C. Hilton, “The LINUX Network”, The M&T Books Slackware Series • U. Vahalia, “Unix Internals, The New Frontiers”, Prentice Hall

  3. 목차 (Contents) • 운영체제 소개 • Linux 커널 소스 코드 구조 및 커널 컴파일 방법 • 태스크 관리 • 인터럽트와 트랩, 시스템 호출 • 가상 메모리 • 파일 시스템 • 디바이스 드라이버, 모듈 프로그래밍 • 프로세스 간 통신 • 통신 프로토콜 • 결론 및 향후 운영체제 발전 방향

  4. 1장. 운영체제 소개

  5. 이 장의 강의 목표 • 컴퓨터 구조를 이해한다. • 운영체제 정의를 이해한다. • 운영체제 종류를 알아본다 • 운영체제 구조를 이해한다.

  6. Secondary storage Main memory Output device Input device CPU 컴퓨터 구조 (1/4) • 하드웨어

  7. 컴퓨터 구조 (2/4) • 하드웨어 구성 요소 • 중앙 처리 장치(central processing unit) • 컴퓨터의 두뇌 : 데이터 연산, 논리 연산 (ALU), 제어(control Unit) • 레지스터 (register) • x86, ARM, PPC, Sparc, Alpha, MIPS, SH4, XScale, • 메인 메모리(memory) : 휘발성 • 메모리 셀 : 메모리 내의 개별적인 저장 공간 • 바이트(byte)와 비트(bit) • Address  Memory  Data • 저장 장치(storage device) : 비휘발성 • 디스크, CD-ROM, 플로피, Flash Memory(NOR, NAND 등) • 입출력 장치 • 입력 장치 (input device) : 키보드, 마우스, Key Pad, Touch Screen • 출력 장치 (output device) : 모니터, 프린터, LCD • 통신 장치 • 모뎀(modem), 이더넷(Ethernet), IrDA, CDMA, Bluetooth

  8. 컴퓨터 구조 (3/4) • 소프트웨어 사용자 응용프로그램 운영체제 하드웨어

  9. 컴퓨터 구조 (4/4) • 소프트웨어 구성 요소 • 운영체제 • 응용 프로그램 • 사용자의 특정 목적을 달성하게 하는 소프트웨어 • 워드프로세서, 게임 소프트웨어, 통신 프로그램 • 데이터베이스 • 프로그램 언어, 컴파일러

  10. 운영체제 정의 • 운영체제란? • 자원 관리자 (Resource Manager) • 응용에게 자원에 대한 서비스 제공 (Computing Environment) • 자원의 종류 • 물리적인 자원 : 처리기, 메모리, 디스크, 터미널, 네트웍, ... • 추상적인 자원 : 태스크, 세그먼트/페이지, 파일, 드라이버, 통신 프로토콜, 패킷, 보안, ... • 커널과 운영체제의 차이는?

  11. 운영체제 종류 (1/2) • RTOS • VxWorks, pSOS, LEX, uITRON, EPOCH, PalmOS • UNIX • SVR4, Solaris • BSD, HP-UX • Linux • Windows System • Windows XP • Windows CE.NET • IEEE Spectrum 2001, 12월호에서 발췌

  12. 운영체제 종류 (2/2) • Linux Details • 1991 version 0.01 (November 2002, version 2.4.8) • 핀란드 대학원생 Linus B. Torvalds (23 age) • A. Tanenbaum 교수의 Minix 기반 (http://www.cs.vu.nl/~ast/minix.html) • Philosophy of COPYLEFT(open source) • GNU support • Various Distributions : Redhat, Debian, Slackware, Alzza • MontaVista, Lineo, Gmate, Zaurus, Samsung, IBM, ..

  13. 운영체제 구조 (1/2) process 1 process 2 process 3 process n User Space System Call Interface Filesystem Manager Process Manager Task Management Scheduler Signaling IPC Ext2fs proc xiafs nfs msdos ntfs Memory Manager Paging/Segmentation Kernel Space Buffer Cache Device Manager Network Manager character block socket Ipv6 IrDA Bluetooth Console KBD SCSI CD-ROM PCI ethernet Hardware Interface dev1 dev2 dev3 dev4 devn (Source : Linux Kernel Internals)

  14. 운영체제 구조 (2/2) OS/2 Client Win32 Client POSIX Client Logon Process Applications POSIX Server OS/2 Server Message Protected Subsystem (Servers) Win32 Server Security Server User mode Trap Kernel mode I/O Manager System Services File System VM Mgt. Cache Manager Object Manager Security Ref. Monitor Process Manager LPC Facility NT Executive Device Drivers Network Drivers Kernel Hardware Abstraction Layer(HAL) HW Control Hardware (Source : Inside Windows NT)

  15. 이후 강의 계획 • 운영체제의 기능을 논리적으로 이해한다. • 운영체제의 기능이 실제 Linux에서 어떻게 구현되었는지 이해한다. • Linux가 설치되어 있는 (커널 소스 포함) PC 확보 부탁 • Article 발표 부탁

  16. 2장. Linux 커널 소스 분석

  17. 이 장의 강의 목표 • 커널이 어떻게 구현되어 있는지 이해한다. • Linux 커널의 소스 트리 구조를 이해한다. • Linux 커널의 각 소스 디렉터리의 내용을 이해한다. • Linux 커널의 컴파일 방법을 이해한다. • 새로 컴파일 한 Linux 커널을 이용하여 시스템을 구동 방법을 이해한다. • 우선 질문 하나.. 커널은 어떻게 컴파일 될까?

  18. ipc lib kernel mm scripts block Doc cdrom driver char arch alpha net fs net init include 802 pci arm asm-alpha appletalk coda pnp m68k asm-arm decnet sbus ext2 mips ... ethernet scsi hpfs ppc boot sound asm-i386 ipv4 msdos sparc kernel video unix linux nfs i386 lib sunrpc ... isofs net math-emu x25 ntfs scsi ... mm ... video Linux 커널 소스 트리 구조 • 커널 소스 코드의 주요 디렉토리 /usr/src/linux • 커널의 논리적인 구조와 연관성을 고려…

  19. 각 디렉토리 상세 설명 (1/4) • arch/ • CPU 종속적인 부분, 각 처리기 마다 하위 디렉토리로 구성됨 (arch/i386, arch/alpha, arch/arm… ) • arch/i386/boot/ • 부트스트랩핑 코드 • arch/i386/kernel/ • 하드웨어 종속적인 커널 관리 루틴 • 트랩, 인터럽트 처리 루틴 • 문맥 교환 루틴 • 장치 구성, 초기화 루틴 • arch/i386/mm/ • 하드웨어 종속적인 메모리 관리 루틴 • init/ • 하드웨어 독립적인 커널 초기화 루틴 (start_kernel) • 태스크 0 (init_task or task[0]) 생성 • 태스크 1, 2, 3 등 데몬 프로세스 생성

  20. 각 디렉토리 상세 설명 (2/4) • kernel/ • 리눅스 커널의 가장 중심적인 디렉토리 (central section of the kernel) • 하드웨어 독립적인 커널 관리 루틴 (하드웨어 종속적인 커널 관리 루틴은 arch/i386/kernel 디렉토리에 존재) • fork, exit 등 태스크 관련 시스템 호출 처리 루틴 • 스케줄러 (scheduler) 루틴 • 시그널 처리 (signal handling) 루틴 • 시간 관리 (time management) 루틴 • mm/ • 하드웨어 독립적인 메모리 관리 루틴 (하드웨어 종속적인 메모리 관리 루틴은 arch/i386/mm 디렉토리에 존재) • 가상 메모리 관리 루틴 • 페이징 (paging), 스와핑(swapping) • fs/ • 가상 파일 시스템 (virtual file system ) 관리 루틴 • open, read 등 태스크 관련 시스템 호출 처리 루틴 • 특정 파일 시스템 관리 루틴은 하위 디렉토리에 존재 (ext2, proc, nfs, msdos, coda, .. )

  21. 각 디렉토리 상세 설명 (3/4) • drivers/ • 장치 드라이버 루틴 • drivers/block/ : 블록 장치 드라이버. 예를 들어 IDE 디스크 (hd) • drivers/char/ : 문자 장치 드라이버. 예를 들어 serial ports, tty, modem, ..) • drivers/net : 네트웍 장치 드라이버. 예를 들어 3C509, ... • drivers/pci/ : PCI bus 제어 • drivers/sound/ : sound card 드라이버 • drivers/cdrom/ : CD-ROM 드라이버 • drivers/scsi/ : SCSI 인터페이스 관리 • ipc/ • 프로세스간 통신 루틴 • 세마포어(semaphores), 공유 메모리(shared memory), 메시지 큐(message queues)

  22. 각 디렉토리 상세 설명 (4/4) • net/ • TCP/IP, ARP 등 네트웍 통신 프로토콜 (네트웍 장치 드라이버는 drivers/net에 존재) • 소켓 인터페이스 • include/ • 커널 헤더 • 하드웨어 독립적인 헤더 : include/linux/ • 하드웨어 종속적인 헤더 : include/asm-***/ (예를 들어 Intel CPU 종속적인 헤더는 include/asm-i386/ 디렉토리에 존재) • modules/ • 커널 모듈 루틴 • 모듈은 insmod(modprobe), rmmod 등의 명령으로 동적 적재/제거 가능 • lib/ • 커널 라이브러리 루틴 • Doc/ • 커널 문서 디렉토리.

  23. Linux 커널 컴파일 방법 (1/2) • 커널 컴파일 방법은 다음의 4 단계로 구성 1. 커널 재구성 (configure) : see Documentation/Configuration.help or chapter 3 of “The LINUX Network”) • make config (menuconfig, xconfig, oldconfig) 2. 커널 종속 관계 체크 (dependency check) • make dep (make clean) 3. 실제 컴파일(compile) • make bzImage cf) - make bzdisk (#dd bs=8192 if=$(BOOTIMAZGE) of=/dev/fd0) - make zlilo (#cat $(BOOTIMAGE) > $(INSTALL_PATH)/vmlinuz) /etc/lilo.conf - mkbootdisk --device /dev/fd0 bzImage, 4. 모듈 인스톨 • make modules, make modules_install • insmod (modprobe)

  24. Linux 커널 컴파일 방법 (2/2) • 커널 컴파일 예 /* 커널 소스의 상위 디렉토리로 이동 */ $cd /usr/src/linux/ /* 커널 구성 (configuration) */ $make config /* query and answer */ /* 커널 컴파일 */ $make dep $make clean $make bzImage /* 실제 커널 소스가 컴파일 됨. take some times */ /* 인스톨 */ $make modules $make modules_install

  25. 컴파일 된 커널로 시스템 재구동 시키는 방법 (1/2) • 새로 컴파일 된 커널로 시스템 재구동 시키는 방법 다음의 3 단계로 구성 1. 커널 복사 cp /usr/src/linux/arch/i386/boot/bzImage /boot/newvmlinuz • 2. LILO 파일 편집 • vi /etc/lilo.conf • 3. 시스템 리부팅 시스템 부팅 시 LILO의 프롬프트에서 “linux”라고 입력하면 기존의 리눅스 커널인 /boot/vmlinuz로 부팅되고, “newlinux”라고 입력하면 새로 컴파일 된 리눅스 커널인 /boot/vmlinuz-new로 부팅

  26. 컴파일 된 커널로 시스템 재구동 시키는 방법 (2/2) • /etc/lilo.conf 파일 수정 예 # original lilo.conf file boot=/dev/hda timeout=100 .. image = /boot/vmlinuz label = linux root = /dev/hda1 .... # modified lilo.conf file boot=/dev/hda timeout=100 .. image = /boot/vmlinuz label = linux root = /dev/hda1 .... /* 이 부분을 추가 */ image = /boot/newvmlinuz label = newlinux root = /dev/hda1 ....

  27. 3장. 태스크 관리

  28. 이 장의 강의 목표 • 태스크의 정의를 이해한다. • 태스크의 생성 방법을 이해한다. • 태스크의 상태와 전이 방법에 대하여 이해한다. • 태스크의 구조와 문맥을 이해한다. • 태스크 스케줄링 방법에 대하여 이해한다.

  29. 태스크란? (1/2) • winword.exe를 수행시켰을 때 커널에서 어떤일이?

  30. 태스크란? (2/2) • 태스크 정의 • 수행중인 프로그램 (an instance of a running program) • 프로그램의 수행 환경 (an execution environment of a program) • 스케줄링 단위 (scheduling entity) • 제어 흐름과 주소 공간의 집합 (a control flow and address space) • multitasking을 지원하는 객체 • 커널의 태스크 관리 • 생성과 소멸 (fork, exit) • 수행 (execve) • 문맥 교환 (context switch) • 수면과 깨움 (sleep, wakeup) • 사용자 수준/커널 수준 실행 (user level/kernel level running)

  31. 태스크 상태와 전이 (1/3) • 태스크 상태(State)와 전이(Transition) • 준비(ready) 상태, 실행(running) 상태, 수면(sleep) 상태 exit running fork initial (idle) wait zombie swtch fork sleep, lock ready sleep wakeup, unlock swap swap suspended ready suspended sleep (Source : UNIX Internals)

  32. 태스크 상태와 전이 (2/3) • 실행 상태 구분 : 사용자 수준 실행/커널 수준 실행 User level running user program execution Interrupt Kernel level running return from system call interrupt routine system call Scheduler ready sleep

  33. 태스크 상태와 전이 (3/3) • 태스크 생성과 전이(커널 수준으로 진입/수면)의 예 /* test.c */ int glob = 6; char buf[] = “a write to stdout\n”; int main(void) { int var; pid_t pid; var = 88; write(STDOUT_FILENO, buf, sizeof(buf)); printf(“before fork\n”); if ((pid = fork()) == 0) { /* child */ glob++; var++; } else sleep(2); /* parent */ printf(“pid = %d, glob = %d, var = %d\n”, getpid(), glob, var); exit (0); } (Source : Adv. programming in the UNIX Env., pgm 8.1)

  34. task1 task2 task3 task4 CPU CPU CPU CPU CPU CPU CPU CPU CPU CPU OS 태스크 정리 • 태스크란? 수행중인 프로그램 (생명을 갖게 됨) • 다음 용어의 차이점은? • 다중 태스킹 (Multitasking) 시스템 • 다중 프로그래밍(Multiprogramming) 시스템 • 다중 프로세서 (Multiprocessor) 시스템 Multitasking 시스템은 시분할 (timesharing) 기법 사용 Sleep 상태 Running 상태 Ready 상태 Ready 상태 OS는 각 태스크마다 상태 등의 정보를 유지 (eg. 작업관리자)

  35. 문맥 (Context) • 문맥 (Context) : • 커널이 관리하는 태스크의 자원과 수행 환경 집합 • 3 부분으로 구성 :시스템 문맥 (system context), 메모리 문맥 (memory context), 하드웨어 문맥(hardware context) memory task structure segment table page table system context file table fd thread structure eip swap or a.out eflags sp eax … hardware context cs disk … memory context (TSS)

  36. 시스템 문맥 • 태스크를 관리하는 정보 집합: task struct • 태스크 정보: pid, uid, euid, suid, … • 태스크 상태: 실행 상태, READY 상태, 수면 상태, … • 태스크의 가족 관계: p_pptr, p_cptr, next_task, next_run • 스케줄링 정보: policy, priority, counter, rt_priority, need_resched • 태스크의 메모리 정보: 세그먼트, 페이지 • 태스크가 접근한 파일 정보: file descriptor • 시그널 정보 • 쓰레드 정보 • 그 외: 수행 시간 정보, 수행 파일 이름, 등등 (kernel dependent)

  37. 메모리 문맥 (1/5) • fork internal : compile results gcc … movl %eax, [glob] addl %eax, 1 movl [glob], %eax ... test.c header text glob, buf 0xffffffff data kernel 0xbfffffff bss var, pid stack stack a.out : (ELF format) /*include/linux/elf.h */ data text 0x0 user’s perspective (virtual memory)

  38. 메모리 문맥 (2/5) • fork internal : after loading (after run a.out) & before fork • In this figure, we assume that there is no paging mechanism. memory segment table (vm_area_struct) task_struct text pid = 11 var, pid stack glob, buf data

  39. 메모리 문맥 (3/5) • fork internal : after fork • address space : basic protection barrier memory glob, buf segment task_struct data pid = 11 text var, pid stack task_struct segment glob, buf pid = 12 data var, pid stack

  40. 메모리 문맥 (4/5) • fork internal : with COW (Copy on Write) mechanism after fork with COWafter “glob++” operation segment segment task_struct task_struct data pid = 11 text pid = 11 text stack stack segment segment task_struct task_struct pid = 12 pid = 12 data data memory memory

  41. 메모리 문맥 (5/5) • 새로운 프로그램 수행: execve internal memory task_struct segment data pid = 11 text a.out header stack text data text bss stack data stack

  42. 하드웨어 문맥 (1/4) • Multitasking • 시분할 시스템 : 각 태스크는 시간 할당량(time quantum) 동안 수행 • Linux에서 시간 할당량은 10 clock tick • 다시 수행될 때 어디부터 수행할 것인가? 쓰레드 자료 구조 이용 Where am I ?? time quantum task 1 …….. task 2 task 3

  43. 하드웨어 문맥 (2/4) • brief reminds the 80x86 architecture ALU Control U. IN OUT Registers • eip, eflags • eax, ebx, ecx, edx, esi, edi, … • cs, ds, ss, es, fs, ... • cr0, cr1, cr2, cr3, LDTR, TR, ...

  44. 하드웨어 문맥 (3/4) • 문맥 교환 (Context Switch) CPU restore context save context task TSS task TSS eip eip sp sp eflags eflags … … eax eax ebx ebx … …

  45. 하드웨어 문맥 (4/4) • 문맥 교환 가상 코드 (pseudo-code) • 80*86 CPU 에서 함수의 리턴값이 eax에 저장된다는 것을 이용 ….. /* need context swtch */ if (save_context()) { /* pick another task to run from run_queue */ …. restore_context(new task) /* The control does not arrive here, NEVER !!! */ } /* resuming process executes from here !!! */ …... (Source : The Design of the UNIX OS) • 위 코드에서 comments 처리된 부분의 의미는??

  46. 태스크 스케줄링 (1/4) • 스케줄링 정의 • 자원을 특정 객체가 사용할 수 있도록 할당하는 것. • 태스크 스케줄링에서는 처리기가 자원이 되고 태스크가 객체가 된다. • 태스크 스케줄링 기준 • 공평성(fairness) : 기아 상태(starvation)가 되는 태스크가 없어야 된다. • 효율성(efficiency) : 태스크 선택 과정이 빠르게 수행되어야 한다. • 응답 시간(response time) vs 처리율(throughput) • 태스크 유형 (type of task) • Interactive • Batch (Computation-Bound) • Real-time

  47. 태스크 스케줄링 (2/4) • 스케줄링 유형 (types of scheduling) • 선점형 스케줄링 (Preemptive scheduling) • 비선점형 스케줄링 (Non preemptive scheduling) • 스케줄링 알고리즘의 예 • FCFS (First Come First Service) • 라운드-로빈(Round-Robin) • SJF (Short Job First) • 다단계 피드백 큐(Multilevel Feedback Queue) • EDF (Earliest Deadline First) • RM (Rate Monotonic) • Fair Queuing • Gang Scheduling • Scheduling for Clustering System • Process Migration

  48. 태스크 스케줄링 (3/4) • UNIX 스케줄링 • Round Robin time quantum Run Queue CPU T3 T2 T1

  49. 태스크 스케줄링 (4/4) • Multilevel Feedback Queue • interactive task의 효과적인 처리 가능 Run Queue 1 CPU T8 T7 T6 Run Queue 2 CPU T5 T4 higher priority less time quantum …... Run Queue n CPU T3 T2 T1

  50. Linux 구현 내용 분석 (1/11) • task_struct 자료 구조 /* include/linux/sched.h */ • task identification : pid, pgrg, session, uid, euid, suid, fsuid • state : TASK_RUNNING, TASK_ZOMBIE, TASK_INTERRUPTABLE, TASK_UNINTERRUPTABLE, TASK_STOPPED • task relationship : p_pptr, p_cptr, next_task, next_run • scheduling information : policy, priority, counter, rt_priority, need_resched • memory information : mm_struct • signal information : signal_struct, sigpending, signal, blocked • file information : files_struct, fs_struct • thread information : tss • time information : start_time, times, timer_list • executable format : personality, exec_domain • resource limits : rlim • miscellaneous : flag, comm, maj_flt, min_flt, exit_code 등 시스템 문맥에서 가장 핵심적인 자료 구조

More Related