I/O操作函数inb, outb, inw, outw

; Copyright (C) 2011 Alen D. Archuleta (zeafoo@gmail.com) ;
设备和芯片的I/O端口操作实现,其实没有复杂的东西在里边 ; 
I/O端口操作主要是看一堆文档,把整个X86架构的PC机所有I/O端口记住, ;
并记住它们每一个数据寄存器、命令寄存器等操作访问标准(也可以称之协议) ; 
记住之后,整个过程中就是按标准使用I/O指令: ;
in, out(只能与DX,AX,AL寄存器结合使用) ;
下面的实现是提供给C使用,因为不太喜欢GNU的inline asm,语法太 ;
晦涩,所以直接使用汇编实现。 ;
inb 从I/O端口读取一个字节(BYTE, HALF-WORD) ;
outb 向I/O端口写入一个字节(BYTE, HALF-WORD) ;
inw 从I/O端口读取一个字(WORD,即两个字节) ;
outw 向I/O端口写入一个字(WORD,即两个字节) ;
byte inb(word port); ;
word inw(word port); ;
void outb(word port, byte value); ;
void outw(word port, word value); ;
编译: ;
nasm -f elf -o io.o io.asm ;
与内核一起链接使用 
global inb, outb, inw, outw 
[section .text] 
inb: 
xor eax, eax ; 在C语言中,都是以EAX寄存器作为返回值 
push dx ; 这个过程要对DX修改,所以先保存一下 
; 返回地址占加个字节,所以偏移4开始读取,第一个参数 
; 对于参数传递过程不作详细的记录,另写日志详细介绍 
mov dx, [esp + 4] 
in al, dx 
pop dx ; 恢复DX寄存器 
ret 
 
outb: 
push dx 
mov dx, [esp + 4] 
mov al, [esp + 6] 
out dx, al 
pop dx 
ret 
inw: 
xor eax, eax 
push dx 
 
mov dx, [esp + 4] 
in ax, dx 
pop dx 
ret 
 
outw: 
push dx 
mov dx, [esp + 4] 
mov ax, [esp + 6] 
out dx, ax 
 
pop dx 
ret 
来源:http://www.live83.cn/?p=103 
以下是一个简单的内核模块,实现了申请 I/O 端口、读写 I/O 端口、释放 I/O 端口并打印输出相关信息: ```c #include <linux/init.h> #include <linux/module.h> #include <linux/ioport.h> #include <asm/io.h> #define IOPORT_BASE 0x3f8 #define IOPORT_SIZE 8 static int __init ioport_init(void) { int ret; struct resource *port; printk(KERN_INFO "ioport: init\n"); /* 申请 I/O 端口 */ port = request_region(IOPORT_BASE, IOPORT_SIZE, "my_ioport"); if (port == NULL) { printk(KERN_ERR "ioport: request_region failed\n"); return -EBUSY; } /* 读写 I/O 端口 */ outb('H', IOPORT_BASE); outb('i', IOPORT_BASE + 1); printk(KERN_INFO "ioport: read from I/O port: %c%c\n", inb(IOPORT_BASE), inb(IOPORT_BASE + 1)); /* 释放 I/O 端口 */ release_region(IOPORT_BASE, IOPORT_SIZE); return 0; } static void __exit ioport_exit(void) { printk(KERN_INFO "ioport: exit\n"); } module_init(ioport_init); module_exit(ioport_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Your Name"); MODULE_DESCRIPTION("ioport example module"); ``` 在该模块中,我们首先定义了 I/O 端口的基地址和大小。然后在 `ioport_init` 函数中,调用 `request_region` 函数申请 I/O 端口,如果申请失败则返回错误码。接着我们使用 `outb` 函数向 I/O 端口写入数据,使用 `inb` 函数读取 I/O 端口中的数据,并通过 printk 函数打印输出相关信息。最后,我们在 `ioport_exit` 函数中调用 `release_region` 函数释放 I/O 端口。 需要注意的是,在编写内核模块时需要特别注意安全性和稳定性,避免对系统造成不必要的损害。建议在进行实验前备份好系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值