outb,inb等I/O端口操作函数

功能
如 i386 ,在区别 I/O 空间和内存空间的进程的 I/O 空间写入数据。
  • outb()   I/O 上写入 8 位数据 ( 1 字节 );
  • outw() I/O 上写入 16 位数据 ( 2 字节 );
  • outl () I/O 上写入 32 位数据 ( 4 字节)。
原型
引用
#include <asm/io.h>

void outb ( unsigned char data , unsigned short port);
void outw ( unsigned short data , unsigned short port);
void outl ( unsigned long data , unsigned short port);
变量
  • port  I/O 地址,此处为虚拟地址
  • data 数据

在linux的驱动程序中,都会使用大量的outb、outw、inb、inw等等宏来访问硬件或寄存器。这些宏的定义都在相应处理器体系下的include/asm目录下的io.h中定义。追究下去,这些宏最终就是一个volatile变量的的赋值:
      #define __arch_putb(v,a)      (*(volatile unsigned char *)(a) = (v))
      #define __raw_writeb(v,a)     __arch_putb(v,a)
      #define outb(v,p)                 __raw_writeb(v,__io(p))

      在(*(volatile unsigned char *)(a) = (v))中,a是一个物理地址(实地址,多数是特殊功能寄存器地址)。(volatile unsigned char *)对a进行类型转换,成为一个指向该地址指针,最后*(volatile unsigned char *)(a)引用该指针对该地址赋值v。这样就可以达到访问底层硬件的目的了。

当读入数据时使用in(x),类似inb、inw、inl,参数与out(x)函数一致。

in、out都是对I/O端口进行操作。ioreadb、iowriteb等是对I/O内存操作。(详见博客http://blog.csdn.net/haozhao_blog/article/details/24005323)


  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的内核模块,实现了申请 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、付费专栏及课程。

余额充值