现在的位置: 首页 > 综合 > 正文

linux/err.h

2018年04月17日 ⁄ 综合 ⁄ 共 2111字 ⁄ 字号 评论关闭

<linux/err.h>文件的代码

#ifndef _LINUX_ERR_H
#define _LINUX_ERR_H

#include <linux/compiler.h>

#include <asm/errno.h>

/*

 * Kernel pointers have redundant information, so we can use a

 * scheme where we can return either an error code or a dentry

 * pointer with the same return value.

 *

 * This should be a per-architecture thing, to allow different

 * error and pointer decisions.

 */

#define MAX_ERRNO    4095

#ifndef __ASSEMBLY__

#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-MAX_ERRNO)

static inline void *ERR_PTR(long error)
{

    return (void *) error;
}

static inline long PTR_ERR(const void *ptr)
{

    return (long) ptr;
}

static inline long IS_ERR(const void *ptr)
{

    return IS_ERR_VALUE((unsigned long)ptr);
}

/**

 * ERR_CAST - Explicitly cast an error-valued pointer to another pointer type

 * @ptr: The pointer to cast.

 *

 * Explicitly cast an error-valued pointer to another pointer type in such a

 * way as to make it clear that's what's going on.

 */

static inline void *ERR_CAST(const void *ptr)
{

    /* cast away the const */

    return (void *) ptr;
}

#endif

#endif /* _LINUX_ERR_H */



内核函数返回一个指针给调用者,而这些函数中很多可能会失败。在大部分情况下,失败是通过一个NULL指针值来表示的,所以只要将返回指针和NULL进行比较,就可以知道函数调用是否成功,如kmalloc。这种方法虽然用起来方便,但它有个缺点:无法知道函数调用失败的原因。因此,许多内核接口通过错误值编码(怎么编码呢?后面讲)到一个指针值来返回错误信息。我们可以得用err.h中的函数,来获取导致函数调用失败的原因。

我们首先来看下错误值是怎么编码的。
http://apps.hi.baidu.com/share/detail/19833514
http://linux.chinaunix.net/bbs/thread-1019406-1-1.html

我们知道,一般的内核出错代码是一个小负数,在-1000和0之间(最大的也在-MAX_ERRNO,0,其中MAX_ERRNO在err.h中定义,刚好在2的12次方之内)。

我们还知道,负数是以补码的方式存储在计算机中的,故-4095在内存中的十六进制为:0xfffff000。
内核返回的指针一般是指向页面的边界(4K边界),即ptr && 0xfff == 0

也就是说,ptr的值不可能落在(0xfffff000, 0xffffffff)之间。所以,如果返回的指针值在上述区间之间,则应该是返回的错误值的补码。
因此,可以根据一个指针指针值是否大于-MAX_ERRNO,即0xfffff000,来判断这个指针值是否是错误的,自然也就知道这个函数调用是否成功。

#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-MAX_ERRNO)

再来分别看下几个内联函数

static inline void *ERR_PTR(long error)
{

    return (void *) error;
}

它是将有符号的错误码转换成指针。


static inline long PTR_ERR(const void *ptr)
{

    return (long) ptr;
}

它是将错误码指针转换成错误码,因为一个错误指针的值在(0xfffff000, 0xffffffff)之间,错误码的补码也在这个区间之间,故只需要强制转换一下即可。


static inline long IS_ERR(const void *ptr)
{

    return IS_ERR_VALUE((unsigned long)ptr);
}

这个函数的意思是显而易见的。

注意下使用问题:应该先使用IS_ERR对一个指针进行判断,在其返回真,也是就确实是一个错误指针时,才用PTR_ERR函数进行把错误编码提取出来。

抱歉!评论已关闭.