SlideShare a Scribd company logo
1 of 50
리눅스 드라이버 실습 #1
2017/May/10
박상호
- 2 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
강의 내용
 Ubuntu 실습
Terminal
Utilities
 간단한 C 프로그램
파일 reader/writer
 커널이란?
본 3주 실습을 위한 간단한 정의
 리눅스 디바이스 드라이버
Character 디바이스 드라이버
echo 디바이스 드라이버
Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Ubuntu 실습
- 4 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
apt
 apt: 패키지 관리 유틸리티
 root 권한 필요: sudo
 apt update: 서버 연결하여 패키지 정보 업데이트
 apt install <package-name>
 apt search <package-name>
 apt upgrade
 실습
 vim 패키지 설치
- 5 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
디렉토리 관리
 ls: 디렉토리 목록
 touch: 빈파일 생성
 rm: 파일/디렉토리 삭제
 mkdir: 디렉토리 생성
 rmdir: 디렉토리 삭제
- 6 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
man
 Manual page
유닉스 시스템(리눅스 포함)에서의 표준 가이드
man <term> or man <section> <term> (ex: man cat, man ls, man printf)
Section
1: Shell command
2. System calls
3. Library calls
4. Special files
5. File formats and conventions
6. Games
7. Miscellaneous (man(7))
8. System administration command (only for root)
9. Kernel routines [Non standard]
- 7 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
vi
 Text Editor
 1976년 Bill Joy가 처음 만듬
- 8 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
vi 모드
- 9 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
vi 명령
https://www.gosquared.com/blog/vi-linux-terminal-help-sheet
- 10 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
vi 실습
 vi로 hello.c 파일 생성
 Cheat Sheet의 명령 실습
 Cursor Navigation
 Insert Text
 Delete Text
 Searching
 Replacing
 .
 저장 & 끝내기
- 11 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Hello, World!
 vi로 “Hello, World!” 프로그램 작성
 gcc로 컴파일하기
 make로 컴파일하기
$ cat Makefile
all:
cc hello.c -o hello
$ make
$ gcc hello.c
$ gcc -o hello hello.c
- 12 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
C 코딩 조언
 함수 spec의 정확한 이해
 man
 msdn
 정의: wikipedia.org
 특정 문제의 해결 방법: google, stackoverflow.com
 Easy come, easy go
 찾은 방법을 자신에게 체화시키길..
Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
reader/writer
매우 간단한 파일 입출력 C 프로그램
- 14 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
C 코딩 조언
 Manual page
유닉스 시스템(리눅스 포함)에서의 표준 가이드
man <term> or man <section> <term> (ex: man cat, man ls, man printf)
Section
1: Shell command
2. System calls
3. Library calls
4. Special files
5. File formats and conventions
6. Games
7. Miscellaneous (man(7))
8. System administration command (only for root)
9. Kernel routines [Non standard]
 정의: wikipedia.org
 특정 문제의 해결 방법: google, stackoverflow.com
Easy come, easy go
찾은 방법을 자신에게 체화시키길..
- 15 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
reader
 reader.c
파일 경로를 argument로 받아
파일의 내용을 화면(standard output)에 출력
- 16 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
writer
 writer.c
파일 경로를 argument로 받아
키보드 입력(standard input)을 파일에 저장
- 17 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Makefile & run
all:
cc reader.c -o reader
cc writer.c -o writer
$ make
$ writer /tmp/a
1234
qwer
asdf
^C
$ reader /tmp/a
1234
qwer
asdf
$
Makefile
- 18 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
코드 흐름
fd = open(argv[1], O_RDONLY);
…
while
ret = read(fd, buf, sizeof(buf));
…
ret = write(STDOUT_FILENO, buf, ret));
…
close(fd);
reader
fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC);
…
while
ret = read(STDIN_FILENO, buf, sizeof(buf));
…
ret = write(fd, buf + i, len - i));
…
close(fd);
writer
● STDIN_FILENO: standard input fd
● STDOUT_FILENO: standard output fd
● Standard input/output
○ Terminal: keyboard & display → Character device in unix system
● 파일 접근을 위한 system call
○ open, read, write, close...
Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
커널 이란…
- 20 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
운영체제(Operating System)의 정의
http://en.wikipedia.org/wiki/Kernel_(operating_system)
Kernel (operating system)
The kernel is a computer program that is the core of a computer's operating system, with complete
control over everything in the system.[1] It is the first program loaded on start-up. It handles the rest of
start-up as well as input/output requests from software, translating them into data-processing instructions
for the central processing unit. It handles memory and peripherals like keyboards, monitors, printers, and
speakers.
A kernel connects the application software to the hardware of a computer.
The critical code of the kernel is usually loaded into a protected area of memory, which prevents it from
being overwritten by applications or other, more minor parts of the operating system. The kernel
performs its tasks, such as running processes and handling interrupts, in kernel space. In contrast,
everything a user does is in user space: writing text in a text editor, running programs in a GUI, etc. This
separation prevents user data and kernel data from interfering with each other and causing instability
and slowness.[1]
The kernel's interface is a low-level abstraction layer. When a process makes requests of the kernel, it is
called a system call. Kernel designs differ in how they manage these system calls and resources.
A monolithic kernel runs all the operating system instructions in the same address space, for speed.
A microkernel runs most processes in user space,[2] for modularity.[3]
- 21 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근
 C:Program FilesInternet Exploreriexplorer.exe 실행하기
- 22 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
커널이 도와주는 부분은?
 커널이 관리하는 것...
드라이브
디렉토리
파일
C:, D:. 드라이브가 어떤 디스크의 파티션에 있는지
디렉토리 이름과 디렉토리의 내용이 디스크의 어디에 있는지
파일의 내용이 어디에 있는지
- 23 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근 (커널이 없다면-1)
 디스크1의 두번째 파티션을 찾아감
- 24 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근 (커널이 없다면-2)
 2. C: 에 있는 “Program Files” 디렉토리를 검색
 3. C:Program Files 에 있는 “Internet Explorer”를 검색
 4. C:Program FilesInternet Explorer 에 있는 “iexplorer.exe” 파일을 검색하고 실행
- 25 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근 (커널이 해주는 건?)
 디렉토리 관리: 디렉토리내 파일 정보를 디스크에 저장
이름, 유형(파일, 디렉토리, 기타)
파일 삭제, 이름 변경
 파일 관리: 파일 정보를 디스크에 저장
이름, 유형, 크기
파일 삭제, 크기 변경
 커널이 해주는 건?
자원(디스크)의 효율적이고 간편한 API 제공
System call: system API by kernel
- 26 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근
마우스 클릭, 키보드 입력
API, System-Call (2)
SCSI commandsData
Data, Action
View, Action
System-Call (2)
● 경로(path)를 통한 human-
readable한 접근 지원
● 크기/개수를 신경쓰지 않아도 되
도록 지원
● 하드디스크, CD, USB stick에
관계없이 동일한 system-call로
접근 가능
- 27 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
파일 접근
마우스 클릭, 키보드 입력
API, System-Call (2)
PCI/PCIe/USB commandsData
Data, Action
View, Action
System-Call (2)
● Socket system-call을 통한 쉬운
TCP/IP 통신 지원
● WiFi, Ethernet에 관계없이 동
일한 system-call을 통해 접근
가능
- 28 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Kernel의 역할
● 자원(Resource) 관리
○ 자원: CPU, Memory, Storage, Network, Graphic Card, etc
■ S/W 자원도 포함됨: 응용 프로그램 ID, TCP 포트 등
○ 자원들을 여러 응용 프로그램이 공유할 수 있도록 제공
■ 배분 정책
● 공정성: Fairness
● 시급성: Time critical
○ 보안
■ 다른 프로그램의 정보가 공유되지 않도록 보호 (hack,
virus)
● Abstracted API 제공
○ H/W 특성에 관계없는 일관된 API(System-call)을 응용 프로
그램에 제공
- 29 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
현존하는 Kernel들
- 30 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
리눅스
 1991년 리누스 토발즈에 의해 개발 시작된 UNIX 계열 커널
 가장 성공적인 open source project 중 하나
 리눅스 커널 기반의 운영체제
RedHat, OpenSUSE, Debian, Ubuntu
Android
Tizen
 http://www.kernel.org
 License: GPLv2
Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Kernel Module Driver
- 32 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
우분투에서 커널 버전 확인하기
- 33 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
커널 빌드
 절차
http://www.kernel.org에서 소스 다운로드
make menuconfig
Kernel configuration
Kernel의 각 특성을 잘 알고 있어야 설정 가능
make
3시간 소요 (in my VirtualBox)
- 34 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
커널 모듈
- 35 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
드라이버 관리
$ insmod echo.ko
$ rmmod echo
$ lsmod
$ cat /proc/modules
…
while
ret = read(fd,
buf, sizeof(buf));
…
ret =
write(STDOUT_FILENO
, buf, ret));
…
close(fd);
드라이버 장착
드라이버 제거
드라이버 검색
$ dmesg Kernel 로그
- 36 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
모듈 코딩
Makefile
# Prerequisite
$ uname -r
3.13.0-generic
$ sudo apt-get install kernel-headers-3.13.0-generic
$ ls -l /lib/modules/3.13.0-generic/build
- 37 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
모듈 코딩
echo.c
모듈을 위한 최소한의 세트
● MODULE_LICENSE
● init_module
○ 모듈초기화시(insmod) 호출
● cleanup_module
○ 모듈삭제시(rmmod) 호출
디버그를 위한 printk
● 커널용 printf
● 앞에 LOG LEVEL이 붙음
Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Echo Driver
- 39 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
장치 유형
 전통적 디바이스 유형
Block: 디스크
특정 offset의 데이터를 접근할 수 있음
Character: 시리얼 포트, 터미널
특정 offset의 개념이 없음
 UNIX는 디바이스 장치를 특수 유형의 파일로 관리
/dev/sda
/dev/console
Network 디바이스는 예외: 이단아
$ ls -l /dev
- 40 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
디바이스 드라이버
 디바이스 드라이버
디바이스를 이용하기 위한 커널 S/W 모듈
 UNIX에서 장치는 파일(/dev/XXX)
장치를 이용하기 위해서는 드라이버가 필요
장치와 드라이버를 어떻게 연결할까?
장치별로 Major/Minor 번호 부여
Major 번호를 담당하는 드라이버 연결
- 41 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Echo 드라이버
 Echo
 Echo 드라이버
장치에 WRITE한 것을 READ할 수 있도록 하는 드라이버
Character device
- 42 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
드라이버 코딩 (1)
- 43 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
드라이버 코딩 (2)
__open(inode, file)
● inode: 특정 노드(파일)을 가
리키는 structure
● file: inode를 open한 뒤, 사용
할 structure (flag, offset 저장
)
○ fd는 *file array의index
__read(file, buf, len, off)
● file: fd에 해당하는 file
structure
● buf: user argument
● len: user argument
● off: offset in the file
- 44 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
드라이버 코딩 (3)
__write(file, buf, len, off)
● file: fd에 해당하는 file
structure
● buf: user argument
● len: user argument
● off: offset in the file
__release_(inode, file)
● close(fd)시 불릴 수 있는 함
수
- 45 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
드라이버 코딩 (4)
$ make
$ sudo insmod echo.ko
$ dmesg
$ ls -al /dev/echo
$ sudo mknod /dev/echo c 250 0
$ ls -al /dev/echo
$ sudo ./writer /dev/echo
1234
^C
$ sudo ./reader /dev/echo
1234
$
- 46 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
프로그램 실행 Flow
reader/writer
VFS(Virtual File Switch): 디바이스 드라이버, 파일 시스템의 file_operations 호출
echo driver
open(“/dev/echo”, O_RDONLY)
__open(inode, file)
read(fd, buf, sizeof(buf))
__read(file, buf, len, off)
close(fd)
__release_(inode, file)
User
Kernel
- 47 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Exercise #1
 Add log in read/write
Print file, function name and line number
String: __FILE__
String: __func__
Integer: __LINE__
- 48 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
Exercise #2
 Add delay in open/read/write/release
#include <linux/delay.h>
…
msleep(1000); /* wait for 1000 msecs */
…
$ sudo ./writer /dev/echo
1234
^C
$ sudo ./reader /dev/echo
1234
$
- 49 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
금일 정리
 커널: 자원 관리, H/W Abstraction 제공
 Simple C 프로그램
 장치 드라이버: Block/Character
 Simple character driver
open/read/write/release
- 50 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential
숙제
 금일 coding한 드라이버로 커널을 죽게 만들기
$ sudo insmod echo.ko
$ sudo mknod /dev/echo c 250 0
$ ????
제출
pasang0000@gmail.com (due: next lecture)

More Related Content

Viewers also liked

동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)
동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)
동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)dgu_DNA
 
PostgreSql vaccum
PostgreSql vaccumPostgreSql vaccum
PostgreSql vaccum승범 현
 
svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드Insub Lee
 
Git는 머꼬? GitHub는 또 머지?
Git는 머꼬? GitHub는 또 머지?Git는 머꼬? GitHub는 또 머지?
Git는 머꼬? GitHub는 또 머지?Ian Choi
 
IoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar
IoT 서비스 아키텍처 분석 및 Case Study-Innovation SeminarIoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar
IoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar영섭 임
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git민태 김
 

Viewers also liked (6)

동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)
동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)
동국대학교 중앙동아리 D.N.A 2014년도 동아리 창립제 발표 자료 - 리눅스 스터디(튜티)
 
PostgreSql vaccum
PostgreSql vaccumPostgreSql vaccum
PostgreSql vaccum
 
svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드
 
Git는 머꼬? GitHub는 또 머지?
Git는 머꼬? GitHub는 또 머지?Git는 머꼬? GitHub는 또 머지?
Git는 머꼬? GitHub는 또 머지?
 
IoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar
IoT 서비스 아키텍처 분석 및 Case Study-Innovation SeminarIoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar
IoT 서비스 아키텍처 분석 및 Case Study-Innovation Seminar
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
 

Similar to 리눅스 드라이버 실습 #1

안드로이드 플랫폼 설명
안드로이드 플랫폼 설명안드로이드 플랫폼 설명
안드로이드 플랫폼 설명Peter YoungSik Yun
 
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전[무료] 시스템해킹(해커스쿨문제풀이) 공개버전
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전James (SeokHun) Hwang
 
Linux ut-broker-install
Linux ut-broker-installLinux ut-broker-install
Linux ut-broker-installJUNHEEKIM27
 
2014 모바일 문서보안 및 통제시스템_시온
2014 모바일 문서보안 및 통제시스템_시온2014 모바일 문서보안 및 통제시스템_시온
2014 모바일 문서보안 및 통제시스템_시온시온시큐리티
 
Hideroot - Inc0gnito 2016
Hideroot - Inc0gnito 2016Hideroot - Inc0gnito 2016
Hideroot - Inc0gnito 2016perillamint
 
시스템 관리자를 위한 리눅스강의 1강 20130203
시스템 관리자를 위한 리눅스강의 1강 20130203시스템 관리자를 위한 리눅스강의 1강 20130203
시스템 관리자를 위한 리눅스강의 1강 20130203doo rip choi
 
20170713 tech day_7th_pxe 부팅-김주한
20170713 tech day_7th_pxe 부팅-김주한20170713 tech day_7th_pxe 부팅-김주한
20170713 tech day_7th_pxe 부팅-김주한ymtech
 
Introduction to Linux #1
Introduction to Linux #1Introduction to Linux #1
Introduction to Linux #1UNIST
 
IoT with Raspberry Pi + Node JS - Chapter 1
IoT with Raspberry Pi + Node JS - Chapter 1IoT with Raspberry Pi + Node JS - Chapter 1
IoT with Raspberry Pi + Node JS - Chapter 1Park Jonggun
 
오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기Jaehwa Park
 
Linux 강의자료 ed10
Linux 강의자료 ed10Linux 강의자료 ed10
Linux 강의자료 ed10hungrok
 
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)Yoonsoo Kim
 
Oracle linux8 solaris_new_features-suk kim
Oracle linux8 solaris_new_features-suk kimOracle linux8 solaris_new_features-suk kim
Oracle linux8 solaris_new_features-suk kimsuk kim
 
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!Sang Yoo
 
클라우독 제안서
클라우독 제안서클라우독 제안서
클라우독 제안서netidshare
 
Clou doc intro_kor_20150403(전자메일첨부용)
Clou doc intro_kor_20150403(전자메일첨부용)Clou doc intro_kor_20150403(전자메일첨부용)
Clou doc intro_kor_20150403(전자메일첨부용)sang yoo
 
caanoo Device driver
caanoo Device drivercaanoo Device driver
caanoo Device driverjumiss
 
Relationship between firmware and module(drvier)
Relationship between firmware and module(drvier)Relationship between firmware and module(drvier)
Relationship between firmware and module(drvier)Jaeock Shim
 
CoreOS를 이용한 Docker 관리툴 소개
CoreOS를 이용한 Docker 관리툴 소개CoreOS를 이용한 Docker 관리툴 소개
CoreOS를 이용한 Docker 관리툴 소개충섭 김
 

Similar to 리눅스 드라이버 실습 #1 (20)

안드로이드 플랫폼 설명
안드로이드 플랫폼 설명안드로이드 플랫폼 설명
안드로이드 플랫폼 설명
 
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전[무료] 시스템해킹(해커스쿨문제풀이) 공개버전
[무료] 시스템해킹(해커스쿨문제풀이) 공개버전
 
Linux ut-broker-install
Linux ut-broker-installLinux ut-broker-install
Linux ut-broker-install
 
2014 모바일 문서보안 및 통제시스템_시온
2014 모바일 문서보안 및 통제시스템_시온2014 모바일 문서보안 및 통제시스템_시온
2014 모바일 문서보안 및 통제시스템_시온
 
Hideroot - Inc0gnito 2016
Hideroot - Inc0gnito 2016Hideroot - Inc0gnito 2016
Hideroot - Inc0gnito 2016
 
시스템 관리자를 위한 리눅스강의 1강 20130203
시스템 관리자를 위한 리눅스강의 1강 20130203시스템 관리자를 위한 리눅스강의 1강 20130203
시스템 관리자를 위한 리눅스강의 1강 20130203
 
20170713 tech day_7th_pxe 부팅-김주한
20170713 tech day_7th_pxe 부팅-김주한20170713 tech day_7th_pxe 부팅-김주한
20170713 tech day_7th_pxe 부팅-김주한
 
palm box ecm
palm box ecmpalm box ecm
palm box ecm
 
Introduction to Linux #1
Introduction to Linux #1Introduction to Linux #1
Introduction to Linux #1
 
IoT with Raspberry Pi + Node JS - Chapter 1
IoT with Raspberry Pi + Node JS - Chapter 1IoT with Raspberry Pi + Node JS - Chapter 1
IoT with Raspberry Pi + Node JS - Chapter 1
 
오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기오픈스택: 구석구석 파헤쳐보기
오픈스택: 구석구석 파헤쳐보기
 
Linux 강의자료 ed10
Linux 강의자료 ed10Linux 강의자료 ed10
Linux 강의자료 ed10
 
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)
오픈 플랫폼 타이젠과 컨트리부션하기(연세대 오픈소스 미니콘서트)
 
Oracle linux8 solaris_new_features-suk kim
Oracle linux8 solaris_new_features-suk kimOracle linux8 solaris_new_features-suk kim
Oracle linux8 solaris_new_features-suk kim
 
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!
문서중앙화, 도면보안, 망분리, 보안로그에는 클라우독!
 
클라우독 제안서
클라우독 제안서클라우독 제안서
클라우독 제안서
 
Clou doc intro_kor_20150403(전자메일첨부용)
Clou doc intro_kor_20150403(전자메일첨부용)Clou doc intro_kor_20150403(전자메일첨부용)
Clou doc intro_kor_20150403(전자메일첨부용)
 
caanoo Device driver
caanoo Device drivercaanoo Device driver
caanoo Device driver
 
Relationship between firmware and module(drvier)
Relationship between firmware and module(drvier)Relationship between firmware and module(drvier)
Relationship between firmware and module(drvier)
 
CoreOS를 이용한 Docker 관리툴 소개
CoreOS를 이용한 Docker 관리툴 소개CoreOS를 이용한 Docker 관리툴 소개
CoreOS를 이용한 Docker 관리툴 소개
 

리눅스 드라이버 실습 #1

  • 1. 리눅스 드라이버 실습 #1 2017/May/10 박상호
  • 2. - 2 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 강의 내용  Ubuntu 실습 Terminal Utilities  간단한 C 프로그램 파일 reader/writer  커널이란? 본 3주 실습을 위한 간단한 정의  리눅스 디바이스 드라이버 Character 디바이스 드라이버 echo 디바이스 드라이버
  • 3. Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Ubuntu 실습
  • 4. - 4 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential apt  apt: 패키지 관리 유틸리티  root 권한 필요: sudo  apt update: 서버 연결하여 패키지 정보 업데이트  apt install <package-name>  apt search <package-name>  apt upgrade  실습  vim 패키지 설치
  • 5. - 5 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 디렉토리 관리  ls: 디렉토리 목록  touch: 빈파일 생성  rm: 파일/디렉토리 삭제  mkdir: 디렉토리 생성  rmdir: 디렉토리 삭제
  • 6. - 6 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential man  Manual page 유닉스 시스템(리눅스 포함)에서의 표준 가이드 man <term> or man <section> <term> (ex: man cat, man ls, man printf) Section 1: Shell command 2. System calls 3. Library calls 4. Special files 5. File formats and conventions 6. Games 7. Miscellaneous (man(7)) 8. System administration command (only for root) 9. Kernel routines [Non standard]
  • 7. - 7 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential vi  Text Editor  1976년 Bill Joy가 처음 만듬
  • 8. - 8 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential vi 모드
  • 9. - 9 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential vi 명령 https://www.gosquared.com/blog/vi-linux-terminal-help-sheet
  • 10. - 10 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential vi 실습  vi로 hello.c 파일 생성  Cheat Sheet의 명령 실습  Cursor Navigation  Insert Text  Delete Text  Searching  Replacing  .  저장 & 끝내기
  • 11. - 11 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Hello, World!  vi로 “Hello, World!” 프로그램 작성  gcc로 컴파일하기  make로 컴파일하기 $ cat Makefile all: cc hello.c -o hello $ make $ gcc hello.c $ gcc -o hello hello.c
  • 12. - 12 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential C 코딩 조언  함수 spec의 정확한 이해  man  msdn  정의: wikipedia.org  특정 문제의 해결 방법: google, stackoverflow.com  Easy come, easy go  찾은 방법을 자신에게 체화시키길..
  • 13. Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential reader/writer 매우 간단한 파일 입출력 C 프로그램
  • 14. - 14 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential C 코딩 조언  Manual page 유닉스 시스템(리눅스 포함)에서의 표준 가이드 man <term> or man <section> <term> (ex: man cat, man ls, man printf) Section 1: Shell command 2. System calls 3. Library calls 4. Special files 5. File formats and conventions 6. Games 7. Miscellaneous (man(7)) 8. System administration command (only for root) 9. Kernel routines [Non standard]  정의: wikipedia.org  특정 문제의 해결 방법: google, stackoverflow.com Easy come, easy go 찾은 방법을 자신에게 체화시키길..
  • 15. - 15 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential reader  reader.c 파일 경로를 argument로 받아 파일의 내용을 화면(standard output)에 출력
  • 16. - 16 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential writer  writer.c 파일 경로를 argument로 받아 키보드 입력(standard input)을 파일에 저장
  • 17. - 17 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Makefile & run all: cc reader.c -o reader cc writer.c -o writer $ make $ writer /tmp/a 1234 qwer asdf ^C $ reader /tmp/a 1234 qwer asdf $ Makefile
  • 18. - 18 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 코드 흐름 fd = open(argv[1], O_RDONLY); … while ret = read(fd, buf, sizeof(buf)); … ret = write(STDOUT_FILENO, buf, ret)); … close(fd); reader fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC); … while ret = read(STDIN_FILENO, buf, sizeof(buf)); … ret = write(fd, buf + i, len - i)); … close(fd); writer ● STDIN_FILENO: standard input fd ● STDOUT_FILENO: standard output fd ● Standard input/output ○ Terminal: keyboard & display → Character device in unix system ● 파일 접근을 위한 system call ○ open, read, write, close...
  • 19. Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 커널 이란…
  • 20. - 20 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 운영체제(Operating System)의 정의 http://en.wikipedia.org/wiki/Kernel_(operating_system) Kernel (operating system) The kernel is a computer program that is the core of a computer's operating system, with complete control over everything in the system.[1] It is the first program loaded on start-up. It handles the rest of start-up as well as input/output requests from software, translating them into data-processing instructions for the central processing unit. It handles memory and peripherals like keyboards, monitors, printers, and speakers. A kernel connects the application software to the hardware of a computer. The critical code of the kernel is usually loaded into a protected area of memory, which prevents it from being overwritten by applications or other, more minor parts of the operating system. The kernel performs its tasks, such as running processes and handling interrupts, in kernel space. In contrast, everything a user does is in user space: writing text in a text editor, running programs in a GUI, etc. This separation prevents user data and kernel data from interfering with each other and causing instability and slowness.[1] The kernel's interface is a low-level abstraction layer. When a process makes requests of the kernel, it is called a system call. Kernel designs differ in how they manage these system calls and resources. A monolithic kernel runs all the operating system instructions in the same address space, for speed. A microkernel runs most processes in user space,[2] for modularity.[3]
  • 21. - 21 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근  C:Program FilesInternet Exploreriexplorer.exe 실행하기
  • 22. - 22 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 커널이 도와주는 부분은?  커널이 관리하는 것... 드라이브 디렉토리 파일 C:, D:. 드라이브가 어떤 디스크의 파티션에 있는지 디렉토리 이름과 디렉토리의 내용이 디스크의 어디에 있는지 파일의 내용이 어디에 있는지
  • 23. - 23 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근 (커널이 없다면-1)  디스크1의 두번째 파티션을 찾아감
  • 24. - 24 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근 (커널이 없다면-2)  2. C: 에 있는 “Program Files” 디렉토리를 검색  3. C:Program Files 에 있는 “Internet Explorer”를 검색  4. C:Program FilesInternet Explorer 에 있는 “iexplorer.exe” 파일을 검색하고 실행
  • 25. - 25 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근 (커널이 해주는 건?)  디렉토리 관리: 디렉토리내 파일 정보를 디스크에 저장 이름, 유형(파일, 디렉토리, 기타) 파일 삭제, 이름 변경  파일 관리: 파일 정보를 디스크에 저장 이름, 유형, 크기 파일 삭제, 크기 변경  커널이 해주는 건? 자원(디스크)의 효율적이고 간편한 API 제공 System call: system API by kernel
  • 26. - 26 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근 마우스 클릭, 키보드 입력 API, System-Call (2) SCSI commandsData Data, Action View, Action System-Call (2) ● 경로(path)를 통한 human- readable한 접근 지원 ● 크기/개수를 신경쓰지 않아도 되 도록 지원 ● 하드디스크, CD, USB stick에 관계없이 동일한 system-call로 접근 가능
  • 27. - 27 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 파일 접근 마우스 클릭, 키보드 입력 API, System-Call (2) PCI/PCIe/USB commandsData Data, Action View, Action System-Call (2) ● Socket system-call을 통한 쉬운 TCP/IP 통신 지원 ● WiFi, Ethernet에 관계없이 동 일한 system-call을 통해 접근 가능
  • 28. - 28 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Kernel의 역할 ● 자원(Resource) 관리 ○ 자원: CPU, Memory, Storage, Network, Graphic Card, etc ■ S/W 자원도 포함됨: 응용 프로그램 ID, TCP 포트 등 ○ 자원들을 여러 응용 프로그램이 공유할 수 있도록 제공 ■ 배분 정책 ● 공정성: Fairness ● 시급성: Time critical ○ 보안 ■ 다른 프로그램의 정보가 공유되지 않도록 보호 (hack, virus) ● Abstracted API 제공 ○ H/W 특성에 관계없는 일관된 API(System-call)을 응용 프로 그램에 제공
  • 29. - 29 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 현존하는 Kernel들
  • 30. - 30 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 리눅스  1991년 리누스 토발즈에 의해 개발 시작된 UNIX 계열 커널  가장 성공적인 open source project 중 하나  리눅스 커널 기반의 운영체제 RedHat, OpenSUSE, Debian, Ubuntu Android Tizen  http://www.kernel.org  License: GPLv2
  • 31. Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Kernel Module Driver
  • 32. - 32 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 우분투에서 커널 버전 확인하기
  • 33. - 33 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 커널 빌드  절차 http://www.kernel.org에서 소스 다운로드 make menuconfig Kernel configuration Kernel의 각 특성을 잘 알고 있어야 설정 가능 make 3시간 소요 (in my VirtualBox)
  • 34. - 34 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 커널 모듈
  • 35. - 35 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 드라이버 관리 $ insmod echo.ko $ rmmod echo $ lsmod $ cat /proc/modules … while ret = read(fd, buf, sizeof(buf)); … ret = write(STDOUT_FILENO , buf, ret)); … close(fd); 드라이버 장착 드라이버 제거 드라이버 검색 $ dmesg Kernel 로그
  • 36. - 36 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 모듈 코딩 Makefile # Prerequisite $ uname -r 3.13.0-generic $ sudo apt-get install kernel-headers-3.13.0-generic $ ls -l /lib/modules/3.13.0-generic/build
  • 37. - 37 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 모듈 코딩 echo.c 모듈을 위한 최소한의 세트 ● MODULE_LICENSE ● init_module ○ 모듈초기화시(insmod) 호출 ● cleanup_module ○ 모듈삭제시(rmmod) 호출 디버그를 위한 printk ● 커널용 printf ● 앞에 LOG LEVEL이 붙음
  • 38. Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Echo Driver
  • 39. - 39 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 장치 유형  전통적 디바이스 유형 Block: 디스크 특정 offset의 데이터를 접근할 수 있음 Character: 시리얼 포트, 터미널 특정 offset의 개념이 없음  UNIX는 디바이스 장치를 특수 유형의 파일로 관리 /dev/sda /dev/console Network 디바이스는 예외: 이단아 $ ls -l /dev
  • 40. - 40 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 디바이스 드라이버  디바이스 드라이버 디바이스를 이용하기 위한 커널 S/W 모듈  UNIX에서 장치는 파일(/dev/XXX) 장치를 이용하기 위해서는 드라이버가 필요 장치와 드라이버를 어떻게 연결할까? 장치별로 Major/Minor 번호 부여 Major 번호를 담당하는 드라이버 연결
  • 41. - 41 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Echo 드라이버  Echo  Echo 드라이버 장치에 WRITE한 것을 READ할 수 있도록 하는 드라이버 Character device
  • 42. - 42 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 드라이버 코딩 (1)
  • 43. - 43 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 드라이버 코딩 (2) __open(inode, file) ● inode: 특정 노드(파일)을 가 리키는 structure ● file: inode를 open한 뒤, 사용 할 structure (flag, offset 저장 ) ○ fd는 *file array의index __read(file, buf, len, off) ● file: fd에 해당하는 file structure ● buf: user argument ● len: user argument ● off: offset in the file
  • 44. - 44 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 드라이버 코딩 (3) __write(file, buf, len, off) ● file: fd에 해당하는 file structure ● buf: user argument ● len: user argument ● off: offset in the file __release_(inode, file) ● close(fd)시 불릴 수 있는 함 수
  • 45. - 45 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 드라이버 코딩 (4) $ make $ sudo insmod echo.ko $ dmesg $ ls -al /dev/echo $ sudo mknod /dev/echo c 250 0 $ ls -al /dev/echo $ sudo ./writer /dev/echo 1234 ^C $ sudo ./reader /dev/echo 1234 $
  • 46. - 46 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 프로그램 실행 Flow reader/writer VFS(Virtual File Switch): 디바이스 드라이버, 파일 시스템의 file_operations 호출 echo driver open(“/dev/echo”, O_RDONLY) __open(inode, file) read(fd, buf, sizeof(buf)) __read(file, buf, len, off) close(fd) __release_(inode, file) User Kernel
  • 47. - 47 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Exercise #1  Add log in read/write Print file, function name and line number String: __FILE__ String: __func__ Integer: __LINE__
  • 48. - 48 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential Exercise #2  Add delay in open/read/write/release #include <linux/delay.h> … msleep(1000); /* wait for 1000 msecs */ … $ sudo ./writer /dev/echo 1234 ^C $ sudo ./reader /dev/echo 1234 $
  • 49. - 49 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 금일 정리  커널: 자원 관리, H/W Abstraction 제공  Simple C 프로그램  장치 드라이버: Block/Character  Simple character driver open/read/write/release
  • 50. - 50 -Copyright © 2015 S-Core Co., Ltd. All rights reserved | Confidential 숙제  금일 coding한 드라이버로 커널을 죽게 만들기 $ sudo insmod echo.ko $ sudo mknod /dev/echo c 250 0 $ ???? 제출 pasang0000@gmail.com (due: next lecture)