版权说明:本文为 开开向前冲 原创文章,转载请注明出处;
注:限于作者水平有限,文中有不对的地方还请指教
注: Android O中HAL有新的改动,这篇文章暂时不涉及,后续会有相关文章讲述;
HAL(Hardware Abstract Layer)硬件抽象层,字面意思就是对硬件设备的封装和抽象;
HAL存在的意义:
(1)HAL层屏蔽了不同硬件设备的差异,为Android OS提供了统一的访问硬件设备的接口;
(2)Linux内核遵循GPL协议;HAL层处于用户空间,遵循Apache License 协议,可以不对外公开;这样HAL层可以帮助硬件厂商隐藏了设备相关模块的核心细节。
HAL 数据结构介绍(三个数据结构+两个常量+一个方法)
- 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封装。
- 两个常量+一个方法 (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实现