linux 内核驱动保存数据,Linux驱动内核数据结构

我们写的驱动程序,尽力能够运行在多个平台上(如:X86、ARM),为此,我们需要在数据类型、字节对齐、内存分页等多方面进行考虑,使我们的驱动程序有很强的可移植性。

1.数据类型

尽量使用typedef的数据类型,因为可能基础数据类型,如:long类型,在某些平台上可能是4字节,在某些平台上可能是8字节,而的typedef数据类型,为我们规避的这一不确定性。

#include

typedef u8;

typedef u16;

typedef u32;

typedef u64;

2.内存分页

内存分页是在#include 中,通过宏PAGE_SIZE定义的。

3.字节序

Big-endian(大端序):数据的高位字节存放在地址的低端,低位字节存放在地址高端,即:高字节存在低地址,好别扭。

Little-endian(小端序):数据的高位字节存放在地址的高端,低位字节存放在地址低端,即:低字节存在低地址,好顺眼。

记住:别扭的是大端序,顺眼的是小端序。

#include

__LITTLE_ENDIAN

__BIG_ENDIAN

根据体系结构,仅定义两个符号中的一个。可以通过#ifdef来编写你的代码。

u32 __cpu_to_le32 (u32);

u32 __le32_to_cpu (u32);

这两个函数可以在已知字节顺序和处理器字节顺序之间转换的函数,这样的函数有很多。

4.字节对齐

不要一贯的认为4字节对齐,尽管大多数是这样的。

#include

get_unaligned(ptr);

put_unaligned(val, ptr);

有些架构需要使用这些宏来保护未对齐的数据访问。宏扩展到允许访问未对齐数据的体系结构的普通指针取消引用。

5.指针和错误值

许多内核函数返回一个指针给调用者,而这些函数中很多可能导致失败,在大部分情况下,通过NULL返回,但有时也会通过一个err指针返回,可通过下面函数来确定具体错误信息,而这种错误是不能简单的与NULL比较的,需要通过下面的函数处理才能得到具体的错误信息。

#include

void *ERR_PTR(long error);

long PTR_ERR(const void *ptr);

long IS_ERR(const void *ptr);

6.内核链表list

内核链表list,定义在#include 中,是一组非常强大的双向链表,不仅可以应用于内核和驱动的开发,在我们普通应用程序开发中,也可以广泛应用。

#include

list_add(struct list_head *new, struct list_head *head);

list_add_tail(struct list_head *new, struct list_head *head);

list_del(struct list_head *entry);

list_del_init(struct list_head *entry);

list_empty(struct list_head *head);

list_entry(entry, type, member);

list_move(struct list_head *entry, struct list_head *head);

list_move_tail(struct list_head *entry, struct list_head *head);

list_splice(struct list_head *list, struct list_head *head);

list_for_each(struct list_head *cursor, struct list_head *list)

list_for_each_prev(struct list_head *cursor, struct list_head *list)

list_for_each_safe(struct list_head *cursor, struct list_head *next, struct list_head *list)

list_for_each_entry(type *cursor, struct list_head *list, member)

list_for_each_entry_safe(type *cursor, type *next struct list_head *list, member)

内核驱动的数据结构远不止这些,这里仅仅是一个基础中的基础,后面还需要更深入的学习。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值