Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核存取周邊 I/O 資源的兩種方式

周邊的 I/O 資源(如 SRAM 或硬體暫存器)預設不在 Linux 內核位址空間中,若要存取,必須先把它的位址對映到內核空間。

一、動態對映(ioremap)

這是最常用也最簡單的方式:直接呼叫內核提供的 ioremap,動態建立一段周邊 I/O 記憶體到內核虛擬位址的對映,之後就能在內核空間存取這段資源。

Ioremap 巨集定義在 asm/io.h:

#define ioremap(cookie,size) __ioremap(cookie,size,0)

__ioremap 的函式原型(arm/mm/ioremap.c):

void __iomem * __ioremap(unsigned long phys_addr, size_t size, unsigned long flags);

phys_addr:要對映的起始 I/O 位址;size:要對映的空間大小;flags:與 I/O 空間權限相關的標誌。函式回傳對映後的內核虛擬位址(3G–4G),接著就能用讀寫該位址的方式存取這段 I/O 資源。

以 s3c2410 的 IIS 音訊驅動為例,查 datasheet 可知 IIS 的實體位址為 0x55000000,先定義成巨集:

#define S3C2410_PA_IIS    (0x55000000)

在內核(iis 驅動)中存取這段暫存器前先建立對映:

our_card->regs = ioremap(S3C2410_PA_IIS, 0x100);

if (our_card->regs == NULL) {

err = -ENXIO;

goto exit_err;

}

之後就能用 readl(our_card->regs) 或 writel(value, our_card->regs) 等 I/O 介面函式存取。

二、靜態對映(map_desc)

內核也提供在開機時以 map_desc 結構靜態建立 I/O 資源到內核位址空間的線性對映表(page table),這種對映是一對一的關係,程式設計者可自行定義對映後的虛擬位址。建好靜態對映表後,驅動中存取該 I/O 資源就不必再 ioremap,直接用對映後的虛擬位址即可。

關鍵在 struct machine_desc——這個結構在內核移植中舉足輕重,內核透過它控制系統架構相關部分的初始化。成員包含架構相關最重要的幾個初始化函式:map_io、init_irq、init_machine,以及 phys_io、timer 等。

struct machine_desc {

/*
* Note! The first four elements are used
* by assembler code in head-armv.S
*/

unsigned int        nr;        /* architecture number    */

unsigned int        phys_io;    /* start of physical io    */

unsigned int        io_pg_offst;    /* byte offset for io page table entry */

const char        *name;        /* architecture name    */

unsigned long        boot_params;    /* tagged list        */

unsigned int        video_start;    /* start of video RAM    */

unsigned int        video_end;    /* end of video RAM    */

unsigned int        reserve_lp0 :1;    /* never has lp0    */

unsigned int        reserve_lp1 :1;    /* never has lp1    */

unsigned int        reserve_lp2 :1;    /* never has lp2    */

unsigned int        soft_reboot :1;    /* soft reboot        */

void            (*fixup)(struct machine_desc *, struct tag *, char **, struct meminfo *);

void            (*map_io)(void);/* IO mapping function    */

void            (*init_irq)(void);

struct sys_timer    *timer;        /* system tick timer    */

void            (*init_machine)(void);

};

實作靜態對映時,就是自行定義 map_io 函式,在其中填入一組 map_desc 描述周邊 I/O 的虛擬位址、實體位址與大小,開機階段便會建立好對映表。

Copyright © Linux教程網 All Rights Reserved