Linux inb() and outb() 的使用方式

639 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。​

  1. 需要root的权限

  2. 需要ioperm()开启对应port的使用权限

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/io.h>

#define BYTE u_int8_t


// waiting for EC Input Buffer Empty
int wait_EC_IBE (void)
{
	while (inb(EC_STATUS_PORT) & EC_IBF);
	return EC_OK;
}

// waiting for EC Output Buffer Full
int wait_EC_OBF (void)
{
	while (!(inb(EC_STATUS_PORT) & EC_OBF));
	return EC_OK;
}

// Write a command to EC port
int WriteECPort(BYTE port, BYTE cmd)
{
	int ret=EC_TIMEOUT;

	if((port==0x62) || (port==0x66))
	{
		ret = wait_EC_IBE();
	  	if (ret == EC_OK)
		{
			outb(cmd, port);
		}
	}
	return  ret;
}

// Read a data from EC 0x68 port
int ReadECPort(BYTE * const data)
{
	int ret;

	ret = wait_EC_OBF();
	if (ret == EC_OK){
		*data = inb(0x68);
	}
	return  ret;
}

int main()
{
	// enable port (0x68 to 0x6c) Read/Write permission for I/O operations
	ret = ioperm(0x68, 5, 1);
	if( ret < 0 ){
		printf("[E]: ioperm set error\n");
		return 1;
	}

    //**************

    add_your_code();

    //**************

    // disable port access
	ret = ioperm(0x68, 5, 0);
	if(ret < 0){
		printf("[E]: ioperm set error\n");
		return 1;
	}

}

  1. 在Linux下使用gcc进行编译