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"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實現

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容

  • Android HAL概述 Android HAL(Hardware Abstract Layer)硬件抽象層,從...
    諾遠閱讀 30,404評論 2 27
  • Android系統對硬件設備的支持是分兩層的。一層實現在內核空間中(只有內核空間才有特權操作硬件設備),另一層實現...
    passerbywhu閱讀 675評論 0 0
  • 硬件廠商處于保護核心代碼,會將核心實現以so庫的形式出現在HAL層,當需要時HAL會自動調用相關的共享庫。 共享庫...
    Galileo_404閱讀 2,061評論 0 3
  • 前言 Android HAL是Hardware Abstract Layer的縮寫,顧名思義,就是硬件抽象層的意思...
    Jimmy2012閱讀 2,577評論 0 1
  • 到現在基本可以確定,我沒什么朋友的根本原因都是來自我本身的問題。 在廣州這個國際化大都市里,我每天遇到的人能數以千...
    今詩閱讀 380評論 0 0