Android HAL

版权说明:本文为 开开向前冲 原创文章,转载请注明出处;
注:限于作者水平有限,文中有不对的地方还请指教

注: Android O中HAL有新的改动,这篇文章暂时不涉及,后续会有相关文章讲述;

HAL(Hardware Abstract Layer)硬件抽象层,字面意思就是对硬件设备的封装和抽象;
HAL存在的意义:
(1)HAL层屏蔽了不同硬件设备的差异,为Android OS提供了统一的访问硬件设备的接口;
(2)Linux内核遵循GPL协议;HAL层处于用户空间,遵循Apache License 协议,可以不对外公开;这样HAL层可以帮助硬件厂商隐藏了设备相关模块的核心细节。

HAL 数据结构介绍(三个数据结构+两个常量+一个方法)
  1. HAL有三个重要的数据结构:hw_module_t,hw_device_t,hw_module_methods_t;这三个数据结构都是定义在/hardware/libhardware/include/hardware/hardware.h中;
------>/hardware/libhardware/include/hardware/hardware.h
struct hw_module_t;
struct hw_module_methods_t;
struct hw_device_t;

/**
 * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
 * and the fields of this data structure must begin with hw_module_t
 * followed by module specific information.
 */
typedef struct hw_module_t {//该结构体称之为硬件模块,可以将硬件相关信息都定义在这个结构体中,注释中有提到,
//每一个硬件模块都必须要有一个名叫HAL_MODULE_INFO_SYM的数据结构;这就是所谓的HAL Stub的名字
    /** tag must be initialized to HARDWARE_MODULE_TAG */
    uint32_t tag;//必须指定为HARDWARE_MODULE_TAG

    /**
     * The API version of the implemented module. The module owner is
     * responsible for updating the version when a module interface has
     * changed.
     *
     * The derived modules such as gralloc and audio own and manage this field.
     * The module user must interpret the version field to decide whether or
     * not to inter-operate with the supplied module implementation.
     * For example, SurfaceFlinger is responsible for making sure that
     * it knows how to manage different versions of the gralloc-module API,
     * and AudioFlinger must know how to do the same for audio-module API.
     *
     * The module API version should include a major and a minor component.
     * For example, version 1.0 could be represented as 0x0100. This format
     * implies that versions 0x0100-0x01ff are all API-compatible.
     *
     * In the future, libhardware will expose a hw_get_module_version()
     * (or equivalent) function that will take minimum/maximum supported
     * versions as arguments and would be able to reject modules with
     * versions outside of the supplied range.
     */
    uint16_t module_api_version;
#define version_major module_api_version
    /**
     * version_major/version_minor defines are supplied here for temporary
     * source code compatibility. They will be removed in the next version.
     * ALL clients must convert to the new version format.
     */

    /**
     * The API version of the HAL module interface. This is meant to
     * version the hw_module_t, hw_module_methods_t, and hw_device_t
     * structures and definitions.
     *
     * The HAL interface owns this field. Module users/implementations
     * must NOT rely on this value for version information.
     *
     * Presently, 0 is the only valid value.
     */
    uint16_t hal_api_version;
#define version_minor hal_api_version

    /** Identifier of module */
    const char *id; //唯一标识该module的ID号

    /** Name of this module */
    const char *name;//module 的名字

    /** Author/owner/implementor of the module */
    const char *author;//module 的作者

    /** Modules methods */
    struct hw_module_methods_t* methods;//指向函数指针的hw_module_methods_t结构体,这个结构体中有open的函数指针;

    /** module's dso */
    void* dso;

#ifdef __LP64__
    uint64_t reserved[32-7];
#else
    /** padding to 128 bytes, reserved for future use */
    uint32_t reserved[32-7];
#endif

} hw_module_t;

typedef struct hw_module_methods_t {
    /** Open a specific device */
    // Open 函数指针,打开硬件模块hw_module_t
    int (*open)(const struct hw_module_t* module, const char* id,
            struct hw_device_t** device); 
    //硬件模块hw_module_t的open方法返回该硬件模块的 *操作接口*,
    //*操作接口*由hw_device_t结构体来描述 
} hw_module_methods_t;

/**
 * Every device data structure must begin with hw_device_t
 * followed by module specific public methods and attributes.
 */
typedef struct hw_device_t {//硬件操作接口数据结构,可以将操作该硬件的方法都定义在该数据结构中
    /** tag must be initialized to HARDWARE_DEVICE_TAG */
    uint32_t tag;//必须指定为HARDWARE_DEVICE_TAG 

    /**
     * Version of the module-specific device API. This value is used by
     * the derived-module user to manage different device implementations.
     *
     * The module user is responsible for checking the module_api_version
     * and device version fields to ensure that the user is capable of
     * communicating with the specific module implementation.
     *
     * One module can support multiple devices with different versions. This
     * can be useful when a device interface changes in an incompatible way
     * but it is still necessary to support older implementations at the same
     * time. One such example is the Camera 2.0 API.
     *
     * This field is interpreted by the module user and is ignored by the
     * HAL interface itself.
     */
    uint32_t version;

    /** reference to the module this device belongs to */
    struct hw_module_t* module;//硬件操作接口对应的硬件模块

    /** padding reserved for future use */
#ifdef __LP64__
    uint64_t reserved[12];
#else
    uint32_t reserved[12];
#endif

    /** Close this device */
    int (*close)(struct hw_device_t* device);//和open 方法相对的close 函数指针;

} hw_device_t;

关于hw_module_t,hw_device_t,hw_module_methods_t的定义以及注释如上面代码所示,
hw_module_t用于描述硬件模块,只要拿到了硬件模块,就可以调用它的open方法,返回硬件模块的硬件操作接口,然后通过这些硬件操作接口来间接操作硬件(这里硬件操作接口可以通过调用BSP的接口来实现真正操作硬件)。这里的open方法被hw_module_methods_t封装,硬件操作接口被hw_device_t封装。

结构体关系.png
  1. 两个常量+一个方法 (HAL_MODULE_INFO_SYM + HAL_MODULE_INFO_SYM_AS_STR + hw_get_module)
------> /hardware/libhardware/include/hardware/hardware.h
/**
 * Name of the hal_module_info
 */
#define HAL_MODULE_INFO_SYM         HMI

/**
 * Name of the hal_module_info as a string
 */
#define HAL_MODULE_INFO_SYM_AS_STR  "HMI"

/**
 * Get the module info associated with a module by id.
 *
 * @return: 0 == success, <0 == error and *module == NULL
 */
int hw_get_module(const char *id, const struct hw_module_t **module);//用于获取硬件模块,存入module指针

前面hardware.h中hw_module_t的定义处有注释:每一个硬件模块(我们自己定义的硬件模块)都必须有一个HAL_MODULE_INFO_SYM,并且HAL_MODULE_INFO_SYM结构体的第一个变量必须是hw_module_t(相当于我们的模块继承于hw_module_t);

hw_get_module用于根据硬件模块 ID加载硬件模块,理解整个加载过程对HAL_MODULE_INFO_SYM和HAL_MODULE_INFO_SYM_AS_STR 的设计会有更好的理解;

------>/hardware/libhardware/hardware.c
/**
 * There are a set of variant filename for modules. The form of the filename
 * is "<MODULE_ID>.variant.so" so for the led module the Dream variants 
 * of base "ro.product.board", "ro.board.platform" and "ro.arch" would be:
 *
 * led.trout.so
 * led.msm7k.so
 * led.ARMV6.so
 * led.default.so
 */

static const char *variant_keys[] = {//获取这些属性用于拼接硬件模块动态库
    "ro.hardware",  /* This goes first so that it can pick up a different
                       file on the emulator. */
    "ro.product.board",
    "ro.board.platform",
    "ro.arch"
};

static const int HAL_VARIANT_KEYS_COUNT =
    (sizeof(variant_keys)/sizeof(variant_keys[0]));

int hw_get_module(const char *id, const struct hw_module_t **module) 
//这个id是必须要和hw_module_t中定义的模块ID相同;
{
    return hw_get_module_by_class(id, NULL, module); //实际调用hw_get_module_by_class来处理
}

int hw_get_module_by_class(const char *class_id, const char *inst,
                           const struct hw_module_t **module)
{
    int i;
    char prop[PATH_MAX];
    char path[PATH_MAX];
    char name[PATH_MAX];
    char prop_name[PATH_MAX];

    if (inst) //这里inst为NULL
        snprintf(name, PATH_MAX, "%s.%s", class_id, inst);
    else
        strlcpy(name, class_id, PATH_MAX);//根据硬件模块ID来拼接name

    /*
     * Here we rely on the fact that calling dlopen multiple times on
     * the same .so will simply increment a refcount (and not load
     * a new copy of the library).
     * We also assume that dlopen() is thread-safe.
     */

    /* First try a property specific to the class and possibly instance */
    snprintf(prop_name, sizeof(prop_name), "ro.hardware.%s", name);//构造初始化prop_name
    if (property_get(prop_name, prop, NULL) > 0) {//根据prop_name 获取属性存入prop中,这里一般为空
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
            goto found;
        }
    }

    /* Loop through the configuration variants looking for a module */
    for (i=0 ; i<HAL_VARIANT_KEYS_COUNT; i++) {//遍历variant_keys数组中属性存入prop中
        if (property_get(variant_keys[i], prop, NULL) == 0) {
            continue;
        }
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
          //在HAL_LIBRARY_PATH2和HAL_LIBRARY_PATH1中查找相应的硬件库是否存在
            goto found;
        }
    }

    /* Nothing found, try the default */
    if (hw_module_exists(path, sizeof(path), name, "default") == 0) {
        goto found;
    }

    return -ENOENT;

found:
    /* load the module, if this fails, we're doomed, and we should not try
     * to load a different variant. */
    return load(class_id, path, module);//找到硬件动态库后调用load 加载硬件动态库
}

/*
 * Check if a HAL with given name and subname exists, if so return 0, otherwise
 * otherwise return negative.  On success path will contain the path to the HAL.
 */
static int hw_module_exists(char *path, size_t path_len, const char *name,
                            const char *subname)
{
    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH2, name, subname);//拼接硬件模块动态库完整路径
    if (access(path, R_OK) == 0)//判断硬件模块动态库是否存在
        return 0;

    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH1, name, subname);
    if (access(path, R_OK) == 0)
        return 0;

    return -ENOENT;
}

/**
 * Load the file defined by the variant and if successful
 * return the dlopen handle and the hmi.
 * @return 0 = success, !0 = failure.
 */
static int load(const char *id,
        const char *path,
        const struct hw_module_t **pHmi)
{
    int status;
    void *handle;
    struct hw_module_t *hmi;

    /*
     * load the symbols resolving undefined symbols before
     * dlopen returns. Since RTLD_GLOBAL is not or'd in with
     * RTLD_NOW the external symbols will not be global
     */
    handle = dlopen(path, RTLD_NOW);//调用dlopen打开硬件模块动态库
    if (handle == NULL) {
        char const *err_str = dlerror();
        ALOGE("load: module=%s\n%s", path, err_str?err_str:"unknown");
        status = -EINVAL;
        goto done;
    }

    /* Get the address of the struct hal_module_info. */
    const char *sym = HAL_MODULE_INFO_SYM_AS_STR;
    hmi = (struct hw_module_t *)dlsym(handle, sym);
    //通过dlsym从打开的库里查找"hmi"这个符号,如果在so代码里有定义的函数名或变量名为hmi,
    //dlsym返回其地址hmi,最后将该地址转化成hw_module_t类型指针;
    if (hmi == NULL) {
        ALOGE("load: couldn't find symbol %s", sym);
        status = -EINVAL;
        goto done;
    }

    /* Check that the id matches */
    if (strcmp(id, hmi->id) != 0) {
        ALOGE("load: id=%s != hmi->id=%s", id, hmi->id);
        status = -EINVAL;
        goto done;
    }
    //将库的句柄保存到hmi硬件对象的dso成员里
    hmi->dso = handle;

    /* success */
    status = 0;

    done:
    if (status != 0) {
        hmi = NULL;
        if (handle != NULL) {
            dlclose(handle);
            handle = NULL;
        }
    } else {
        ALOGV("loaded HAL id=%s path=%s hmi=%p handle=%p",
                id, path, *pHmi, handle);
    }

    *pHmi = hmi;

    return status;
}

hw_get_module 通过硬件模块ID 最后调用load函数加载特定硬件模块(dlopen 和dlsym)获取到hw_module_t指针,获取到这个指针后就可以对硬件抽象接口进行各种操作了;

HAL 模块代码编写

前面hardware.h中hw_module_t的定义处有注释:每一个硬件模块(我们自己定义的硬件模块)都必须有一个HAL_MODULE_INFO_SYM,并且HAL_MODULE_INFO_SYM结构体的第一个变量必须是hw_module_t(相当于我们的模块继承于hw_module_t);HAL_MODULE_INFO_SYM 这个常量是为调用dlsym 加载硬件模块使用;这个结构体也是定义在hardware.h中;

HAL_MODULE_INFO_SYM是如何使用呢?这里参考系统中已有的HAL写一个最简单的helloworld HAL的例子;
在/hardware/libhardware/modules目录下新建hello目录代表hello模块;然后在这个目录中实现对hello模块的操作;可以将这个模块的头文件放在/hardware/libhardware/include/hardware/目录下;这里的实现都是参考系统中目前已经存在的代码;

------> /hardware/libhardware/include/hardware/hello.h
/**
 * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
 * and the fields of this data structure must begin with hw_module_t
 * followed by module specific information.
 */
#ifndef ANDROID_HELLO_INTERFACE_H
#define ANDROID_HELLO_INTERFACE_H
#include <hardware hardware.h>

__BEGIN_DECLS
#define HELLO_HARDWARE_MODULE_ID "hello"//定义hello HAL 模块的ID 为 hello 
struct hello_module_t { //相当于继承于hw_module_t 
    struct hw_module_t common;//第一个数据为hw_module_t类型
};
struct hello_device_t {
    struct hw_device_t common;
    int fd;
    int (*set_val)(struct hello_device_t* dev, int val);
    int (*get_val)(struct hello_device_t* dev, int* val);//这里对硬件的操作接口应该设置为函数指针
};//hw_device_t的继承者
__END_DECLS
#endif


------> /hardware/libhardware/modules/hello/hello.c
#define LOG_TAG "HelloStub"
#include <hardware hardware.h>
#include <hardware hello.h>

#include <sys mman.h>

#include <dlfcn.h>

#include <cutils ashmem.h>
#include <cutils log.h>

#include <fcntl.h>
#include <errno.h>
#include <sys ioctl.h>
#include <string.h>
#include <stdlib.h>

#include <cutils log.h>
#include <cutils atomic.h>

#define MODULE_NAME "Hello"
char const * const device_name = "/dev/hello" ;//  /dev/hello是一个字符设备,该字符设备可以参考参考文档实现;
static int hello_device_open(const struct hw_module_t* module, const char* name, struct hw_device_t** device);
static int hello_device_close(struct hw_device_t* device);
static int hello_set_val(struct hello_device_t* dev, int val);
static int hello_get_val(struct hello_device_t* dev, int* val);

static struct hw_module_methods_t hello_module_methods = {
    .open = hello_device_open,
};
static int hello_device_open(const struct hw_module_t* module, const char* name, struct hw_device_t** device)
{
    struct hello_device_t* dev;
    char name_[64];
    //pthread_mutex_t lock;
    dev = (struct hello_device_t*)malloc(sizeof(struct hello_device_t));
    if(!dev) {
        ALOGE("Hello Stub: failed to alloc space");
        return -EFAULT;
    }
    ALOGE("Hello Stub: hello_device_open");
    memset(dev, 0, sizeof(struct hello_device_t));

    dev->common.tag = HARDWARE_DEVICE_TAG;
    dev->common.version = 0;
    dev->common.module = (hw_module_t*)module;
    dev->common.close = hello_device_close;
    dev->set_val = hello_set_val;
    dev->get_val = hello_get_val;

    //pthread_mutex_lock(&lock);
    dev->fd = -1 ;
    snprintf(name_, 64, device_name, 0);
    dev->fd = open(name_, O_RDWR);
    if(dev->fd == -1) {
        ALOGE("Hello Stub: open failed to open %s !-- %s.", name_,strerror(errno));
        free(dev);
        return -EFAULT;
    }
    //pthread_mutex_unlock(&lock);
    *device = &(dev->common);
    ALOGI("Hello Stub: open HAL hello successfully.");
    return 0;
}

static int hello_device_close(struct hw_device_t* device) {
    struct hello_device_t* hello_device = (struct hello_device_t*)device;
    if(hello_device) {
        close(hello_device->fd);
        free(hello_device);
    }
    return 0;
}
static int hello_set_val(struct hello_device_t* dev, int val) {
    ALOGI("Hello Stub: set value to device.");
    return 0;
}
static int hello_get_val(struct hello_device_t* dev, int* val) {
    if(!val) {
        ALOGE("Hello Stub: error val pointer");
        return -EFAULT;
    }
    ALOGI("Hello Stub: get value  from device");
    return 0;
}

struct hello_module_t HAL_MODULE_INFO_SYM = {
    .common = {
        .tag                = HARDWARE_MODULE_TAG,
        //.module_api_version = FINGERPRINT_MODULE_API_VERSION_2_0,
        .hal_api_version    = HARDWARE_HAL_API_VERSION,
        .id                 = HELLO_HARDWARE_MODULE_ID,//定义hello 模块的ID为hello
        .name               = "Demo shaomingliang hello HAL",
        .author             = "The Android Open Source Project",
        .methods            = &hello_module_methods,
    },
};

代码都编写OK 后需要将HAL编译成动态库,需要在/hardware/libhardware/modules/hello/目录下实现Android.mk将该模块编译到系统,下面是编译脚本;

------> /hardware/libhardware/modules/hello/Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := hello.default
LOCAL_MODULE_RELATIVE_PATH := hw
LOCAL_SRC_FILES := hello.c
LOCAL_SHARED_LIBRARIES := liblog
LOCAL_MODULE_TAGS := optional

include $(BUILD_SHARED_LIBRARY)

执行:mmm hardware/libhardware/modules/hello/
将会在out目录的system/lib/hw/下生成一个hello.default.so

到这里就Android OS就可以根据hello模块的id:hello使用hw_get_module获取到硬件模块指针,然后获取硬件操作接口操作硬件;

/hardware/libhardware/include/hardware/hardware.h
/hardware/libhardware/hardware.c

参考文章:
Android Hal层简要分析
Android系统移植与平台开发(八)- HAL Stub框架分析
Android硬件抽象层HAL总结
hello 设备驱动的HAL实现

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容

  • Android HAL概述 Android HAL(Hardware Abstract Layer)硬件抽象层,从...
    诺远阅读 29,923评论 2 27
  • Android系统对硬件设备的支持是分两层的。一层实现在内核空间中(只有内核空间才有特权操作硬件设备),另一层实现...
    passerbywhu阅读 646评论 0 0
  • 硬件厂商处于保护核心代码,会将核心实现以so库的形式出现在HAL层,当需要时HAL会自动调用相关的共享库。 共享库...
    Galileo_404阅读 1,935评论 0 3
  • 前言 Android HAL是Hardware Abstract Layer的缩写,顾名思义,就是硬件抽象层的意思...
    Jimmy2012阅读 2,530评论 0 1
  • 到现在基本可以确定,我没什么朋友的根本原因都是来自我本身的问题。 在广州这个国际化大都市里,我每天遇到的人能数以千...
    今诗阅读 370评论 0 0