版權說明:本文為 開開向前沖 原創文章,轉載請注明出處;
注:限于作者水平有限,文中有不對的地方還請指教
注: 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"http://定義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實現