Android HAL

版權(quán)說明:本文為 開開向前沖 原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明出處;
注:限于作者水平有限,文中有不對(duì)的地方還請(qǐng)指教

注: Android O中HAL有新的改動(dòng),這篇文章暫時(shí)不涉及,后續(xù)會(huì)有相關(guān)文章講述;

HAL(Hardware Abstract Layer)硬件抽象層,字面意思就是對(duì)硬件設(shè)備的封裝和抽象;
HAL存在的意義:
(1)HAL層屏蔽了不同硬件設(shè)備的差異,為Android OS提供了統(tǒng)一的訪問硬件設(shè)備的接口;
(2)Linux內(nèi)核遵循GPL協(xié)議;HAL層處于用戶空間,遵循Apache License 協(xié)議,可以不對(duì)外公開;這樣HAL層可以幫助硬件廠商隱藏了設(shè)備相關(guān)模塊的核心細(xì)節(jié)。

HAL 數(shù)據(jù)結(jié)構(gòu)介紹(三個(gè)數(shù)據(jù)結(jié)構(gòu)+兩個(gè)常量+一個(gè)方法)
  1. HAL有三個(gè)重要的數(shù)據(jù)結(jié)構(gòu):hw_module_t,hw_device_t,hw_module_methods_t;這三個(gè)數(shù)據(jù)結(jié)構(gòu)都是定義在/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 {//該結(jié)構(gòu)體稱之為硬件模塊,可以將硬件相關(guān)信息都定義在這個(gè)結(jié)構(gòu)體中,注釋中有提到,
//每一個(gè)硬件模塊都必須要有一個(gè)名叫HAL_MODULE_INFO_SYM的數(shù)據(jù)結(jié)構(gòu);這就是所謂的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; //唯一標(biāo)識(shí)該module的ID號(hào)

    /** 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;//指向函數(shù)指針的hw_module_methods_t結(jié)構(gòu)體,這個(gè)結(jié)構(gòu)體中有open的函數(shù)指針;

    /** 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 函數(shù)指針,打開硬件模塊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結(jié)構(gòu)體來描述 
} 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 {//硬件操作接口數(shù)據(jù)結(jié)構(gòu),可以將操作該硬件的方法都定義在該數(shù)據(jù)結(jié)構(gòu)中
    /** 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;//硬件操作接口對(duì)應(yīng)的硬件模塊

    /** 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 方法相對(duì)的close 函數(shù)指針;

} hw_device_t;

關(guān)于hw_module_t,hw_device_t,hw_module_methods_t的定義以及注釋如上面代碼所示,
hw_module_t用于描述硬件模塊,只要拿到了硬件模塊,就可以調(diào)用它的open方法,返回硬件模塊的硬件操作接口,然后通過這些硬件操作接口來間接操作硬件(這里硬件操作接口可以通過調(diào)用BSP的接口來實(shí)現(xiàn)真正操作硬件)。這里的open方法被hw_module_methods_t封裝,硬件操作接口被hw_device_t封裝。

結(jié)構(gòu)體關(guān)系.png
  1. 兩個(gè)常量+一個(gè)方法 (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的定義處有注釋:每一個(gè)硬件模塊(我們自己定義的硬件模塊)都必須有一個(gè)HAL_MODULE_INFO_SYM,并且HAL_MODULE_INFO_SYM結(jié)構(gòu)體的第一個(gè)變量必須是hw_module_t(相當(dāng)于我們的模塊繼承于hw_module_t);

hw_get_module用于根據(jù)硬件模塊 ID加載硬件模塊,理解整個(gè)加載過程對(duì)HAL_MODULE_INFO_SYM和HAL_MODULE_INFO_SYM_AS_STR 的設(shè)計(jì)會(huì)有更好的理解;

------>/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[] = {//獲取這些屬性用于拼接硬件模塊動(dòng)態(tài)庫
    "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) 
//這個(gè)id是必須要和hw_module_t中定義的模塊ID相同;
{
    return hw_get_module_by_class(id, NULL, module); //實(shí)際調(diào)用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);//根據(jù)硬件模塊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);//構(gòu)造初始化prop_name
    if (property_get(prop_name, prop, NULL) > 0) {//根據(jù)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數(shù)組中屬性存入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中查找相應(yīng)的硬件庫是否存在
            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);//找到硬件動(dòng)態(tài)庫后調(diào)用load 加載硬件動(dòng)態(tài)庫
}

/*
 * 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);//拼接硬件模塊動(dòng)態(tài)庫完整路徑
    if (access(path, R_OK) == 0)//判斷硬件模塊動(dòng)態(tài)庫是否存在
        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);//調(diào)用dlopen打開硬件模塊動(dòng)態(tài)庫
    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"這個(gè)符號(hào),如果在so代碼里有定義的函數(shù)名或變量名為hmi,
    //dlsym返回其地址hmi,最后將該地址轉(zhuǎn)化成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硬件對(duì)象的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 最后調(diào)用load函數(shù)加載特定硬件模塊(dlopen 和dlsym)獲取到hw_module_t指針,獲取到這個(gè)指針后就可以對(duì)硬件抽象接口進(jìn)行各種操作了;

HAL 模塊代碼編寫

前面hardware.h中hw_module_t的定義處有注釋:每一個(gè)硬件模塊(我們自己定義的硬件模塊)都必須有一個(gè)HAL_MODULE_INFO_SYM,并且HAL_MODULE_INFO_SYM結(jié)構(gòu)體的第一個(gè)變量必須是hw_module_t(相當(dāng)于我們的模塊繼承于hw_module_t);HAL_MODULE_INFO_SYM 這個(gè)常量是為調(diào)用dlsym 加載硬件模塊使用;這個(gè)結(jié)構(gòu)體也是定義在hardware.h中;

HAL_MODULE_INFO_SYM是如何使用呢?這里參考系統(tǒng)中已有的HAL寫一個(gè)最簡(jiǎn)單的helloworld HAL的例子;
在/hardware/libhardware/modules目錄下新建hello目錄代表hello模塊;然后在這個(gè)目錄中實(shí)現(xiàn)對(duì)hello模塊的操作;可以將這個(gè)模塊的頭文件放在/hardware/libhardware/include/hardware/目錄下;這里的實(shí)現(xiàn)都是參考系統(tǒng)中目前已經(jīng)存在的代碼;

------> /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 { //相當(dāng)于繼承于hw_module_t 
    struct hw_module_t common;//第一個(gè)數(shù)據(jù)為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);//這里對(duì)硬件的操作接口應(yīng)該設(shè)置為函數(shù)指針
};//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是一個(gè)字符設(shè)備,該字符設(shè)備可以參考參考文檔實(shí)現(xiàn);
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編譯成動(dòng)態(tài)庫,需要在/hardware/libhardware/modules/hello/目錄下實(shí)現(xiàn)Android.mk將該模塊編譯到系統(tǒng),下面是編譯腳本;

------> /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)

執(zhí)行:mmm hardware/libhardware/modules/hello/
將會(huì)在out目錄的system/lib/hw/下生成一個(gè)hello.default.so

到這里就Android OS就可以根據(jù)hello模塊的id:hello使用hw_get_module獲取到硬件模塊指針,然后獲取硬件操作接口操作硬件;

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

參考文章:
Android Hal層簡(jiǎn)要分析
Android系統(tǒng)移植與平臺(tái)開發(fā)(八)- HAL Stub框架分析
Android硬件抽象層HAL總結(jié)
hello 設(shè)備驅(qū)動(dòng)的HAL實(shí)現(xiàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android HAL概述 Android HAL(Hardware Abstract Layer)硬件抽象層,從...
    諾遠(yuǎn)閱讀 31,203評(píng)論 2 27
  • Android系統(tǒng)對(duì)硬件設(shè)備的支持是分兩層的。一層實(shí)現(xiàn)在內(nèi)核空間中(只有內(nèi)核空間才有特權(quán)操作硬件設(shè)備),另一層實(shí)現(xiàn)...
    passerbywhu閱讀 794評(píng)論 0 0
  • 硬件廠商處于保護(hù)核心代碼,會(huì)將核心實(shí)現(xiàn)以so庫的形式出現(xiàn)在HAL層,當(dāng)需要時(shí)HAL會(huì)自動(dòng)調(diào)用相關(guān)的共享庫。 共享庫...
    Galileo_404閱讀 2,224評(píng)論 0 3
  • 前言 Android HAL是Hardware Abstract Layer的縮寫,顧名思義,就是硬件抽象層的意思...
    Jimmy2012閱讀 2,753評(píng)論 0 1
  • 到現(xiàn)在基本可以確定,我沒什么朋友的根本原因都是來自我本身的問題。 在廣州這個(gè)國際化大都市里,我每天遇到的人能數(shù)以千...
    今詩閱讀 421評(píng)論 0 0

友情鏈接更多精彩內(nèi)容