vibrator: add initial forcefeedback vibrator HAL

This HAL talks to vibrators which are exposed as input devices using the
forcefeedback API.

This version includes lots of debugging spam.
diff --git a/vibrator/Android.bp b/vibrator/Android.bp
new file mode 100644
index 0000000..653457c
--- /dev/null
+++ b/vibrator/Android.bp
@@ -0,0 +1,31 @@
+//
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+cc_binary {
+    name: "android.hardware.vibrator@1.1-service.sdm845",
+    vendor: true,
+    relative_install_path: "hw",
+    init_rc: ["android.hardware.vibrator@1.1-service.sdm845.rc"],
+    srcs: ["service.cpp", "Vibrator.cpp"],
+    cflags: ["-Wall", "-Werror"],
+    shared_libs: [
+        "libhidlbase",
+        "libcutils",
+        "liblog",
+        "libutils",
+        "libhardware",
+        "android.hardware.vibrator@1.0",
+        "android.hardware.vibrator@1.1",
+    ],
+}
diff --git a/vibrator/Vibrator.cpp b/vibrator/Vibrator.cpp
new file mode 100644
index 0000000..3d1b413
--- /dev/null
+++ b/vibrator/Vibrator.cpp
@@ -0,0 +1,206 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* Adapted from Crosshatch downstream:
+ * https://github.com/GrapheneOS/device_google_crosshatch/blob/c7f62a539b6cb4685348fbd747605cbfabf1b94d/vibrator/Vibrator.cpp
+ */
+
+#define LOG_TAG "VibratorService"
+
+#include <log/log.h>
+
+#include <hardware/hardware.h>
+#include <hardware/vibrator.h>
+#include <cutils/properties.h>
+#include <linux/input.h>
+
+#include "Vibrator.h"
+
+#include <cinttypes>
+#include <cmath>
+#include <iostream>
+#include <fstream>
+#include <cstring>
+
+
+namespace android {
+namespace hardware {
+namespace vibrator {
+namespace V1_1 {
+namespace implementation {
+
+using Status = ::android::hardware::vibrator::V1_0::Status;
+using EffectStrength = ::android::hardware::vibrator::V1_0::EffectStrength;
+using Effect = ::android::hardware::vibrator::V1_1::Effect_1_1;
+
+static constexpr int8_t MAX_TRIGGER_LATENCY_MS = 6;
+
+Vibrator::Vibrator(std::string devpath) :
+    mInputDevPath(devpath)
+{
+    std::memset(&mEffect, 0, sizeof(mEffect));
+    mEffect.type = FF_RUMBLE;
+    mEffect.id = -1;
+
+    mfd = openInputDev();
+    if (mfd < 0) {
+		ALOGE("CA:: %s() can't open FF input device %s", __func__, mInputDevPath.c_str());
+        return;
+	}
+}
+
+int Vibrator::openInputDev() {
+    return open(mInputDevPath.c_str(), O_RDWR|O_CLOEXEC);
+}
+
+Return<Status> Vibrator::on(uint32_t timeoutMs, uint32_t playCount) {
+    ALOGI("CA:: %s, timeoutMs = %d, playCount = %d, effect.id = %d, strong magnitude = %d, weak magnitude = %d", __func__, timeoutMs, playCount, mEffect.id, mEffect.u.rumble.strong_magnitude, mEffect.u.rumble.weak_magnitude);
+    struct input_event play;
+    int ret;
+
+    // Upload Rumble effect
+    ret = ioctl(mfd, EVIOCSFF, &mEffect);
+    if (ret < 0) {
+        ALOGE("CA:: %s() Couldn't upload rumble effect to device %s, ret = %d", __func__, mInputDevPath.c_str(), ret);
+        return Status::UNKNOWN_ERROR;
+	}
+
+    play.type = EV_FF;
+    play.code = mEffect.id;
+    play.value = playCount;
+    ret = write(mfd, (const void*) &play, sizeof(play));
+    if (ret != sizeof(play)) {
+        ALOGE("CA:: %s() failed to fully write play event to input device: %d", __func__, errno);
+        return Status::UNKNOWN_ERROR;
+    }
+
+    usleep(timeoutMs * 1000);
+    
+    return Status::OK;
+}
+
+// Methods from ::android::hardware::vibrator::V1_1::IVibrator follow.
+Return<Status> Vibrator::on(uint32_t timeoutMs) {
+    return(on(timeoutMs, 1));
+}
+
+Return<Status> Vibrator::off()  {
+    ALOGI("CA:: %s", __func__);
+    struct input_event stop;
+    int ret;
+
+    stop.type = EV_FF;
+    stop.code = mEffect.id;
+    stop.value = 0;
+    if (write(mfd, (const void*) &stop, sizeof(stop)) != sizeof(stop)) {
+        ALOGE("CA:: %s() failed to fully write stop event to input device", __func__);
+        return Status::UNKNOWN_ERROR;
+    }
+
+    // Unload rumble effect
+    ret = ioctl(mfd, EVIOCRMFF, &mEffect);
+    if (ret < 0) {
+		ALOGE("CA:: %s() Failed to remove rumble effect from device %s, ret = %d", __func__, mInputDevPath.c_str(), ret);
+        return Status::UNKNOWN_ERROR;
+	}
+    mEffect.id = -1;
+
+    return Status::OK;
+}
+
+Return<bool> Vibrator::supportsAmplitudeControl()  {
+    ALOGI("CA:: %s", __func__);
+    return false;
+}
+
+Return<Status> Vibrator::setAmplitude(uint8_t amplitude) {
+    ALOGI("CA:: %s", __func__);
+
+    if (!amplitude) {
+        return Status::BAD_VALUE;
+    }
+
+    return Status::OK;
+}
+
+Return<void> Vibrator::perform(V1_0::Effect effect, EffectStrength strength,
+        perform_cb _hidl_cb) {
+    return performWrapper(effect, strength, _hidl_cb);
+}
+
+Return<void> Vibrator::perform_1_1(V1_1::Effect_1_1 effect, EffectStrength strength,
+        perform_cb _hidl_cb) {
+    return performWrapper(effect, strength, _hidl_cb);
+}
+
+template <typename T>
+Return<void> Vibrator::performWrapper(T effect, EffectStrength strength, perform_cb _hidl_cb) {
+    ALOGI("CA:: %s, ", __func__);
+    auto validRange = hidl_enum_range<T>();
+    if (effect < *validRange.begin() || effect > *std::prev(validRange.end())) {
+        _hidl_cb(Status::UNSUPPORTED_OPERATION, 0);
+        return Void();
+    }
+    return performEffect(static_cast<Effect>(effect), strength, _hidl_cb);
+}
+
+Return<void> Vibrator::performEffect(Effect effect, EffectStrength strength,
+        perform_cb _hidl_cb) {
+    Status status = Status::OK;
+    uint32_t timeMs;
+    int playCount = 1;
+    mEffect.u.rumble.weak_magnitude = mEffect.u.rumble.strong_magnitude = 0;
+
+    ALOGI("CA:: %s() effect = %d", __func__, effect);
+
+    switch (effect) {
+    case Effect::TICK:
+        mEffect.u.rumble.weak_magnitude = 0x5000 + (int)strength * 0x1000;
+        timeMs = 9;
+        break;
+    case Effect::CLICK:
+        mEffect.u.rumble.strong_magnitude = 0x500 + (int)strength * 0x1000;
+        timeMs = 9;
+        break;
+    case Effect::DOUBLE_CLICK:
+        mEffect.u.rumble.strong_magnitude = 0x4000 + (int)strength * 0x1000;
+        playCount = 2;
+        timeMs = 130;
+        break;
+    default:
+        _hidl_cb(Status::UNSUPPORTED_OPERATION, 0);
+        return Void();
+    }
+
+    timeMs += MAX_TRIGGER_LATENCY_MS; // Add expected cold-start latency
+
+    on(timeMs, playCount);
+    // Android calls off() for us.
+    _hidl_cb(status, timeMs);
+
+    return Void();
+}
+
+Vibrator::~Vibrator() {
+    close(mfd);
+}
+
+
+} // namespace implementation
+}  // namespace V1_1
+}  // namespace vibrator
+}  // namespace hardware
+}  // namespace android
\ No newline at end of file
diff --git a/vibrator/Vibrator.h b/vibrator/Vibrator.h
new file mode 100644
index 0000000..308f4fe
--- /dev/null
+++ b/vibrator/Vibrator.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef ANDROID_HARDWARE_VIBRATOR_V1_1_VIBRATOR_H
+#define ANDROID_HARDWARE_VIBRATOR_V1_1_VIBRATOR_H
+
+#include <android/hardware/vibrator/1.1/IVibrator.h>
+#include <hidl/Status.h>
+
+#include <linux/input.h>
+
+#include <fstream>
+
+// Borrowed from linuxconsole/utils/bitmaskros.h
+/* Number of bits for 1 unsigned char */
+#define nBitsPerUchar          (sizeof(unsigned char) * 8)
+/* Index=Offset of given bit in 1 unsigned char */
+#define bitOffsetInUchar(bit)  ((bit)%nBitsPerUchar)
+/* Index=Offset of the unsigned char associated to the bit
+ * at the given index=offset
+ */
+#define ucharIndexForBit(bit)  ((bit)/nBitsPerUchar)
+/* Test the bit with given index=offset in an unsigned char array */
+#define testBit(bit, array)    ((array[ucharIndexForBit(bit)] >> bitOffsetInUchar(bit)) & 1)
+
+namespace android {
+namespace hardware {
+namespace vibrator {
+namespace V1_1 {
+namespace implementation {
+
+class Vibrator : public IVibrator {
+public:
+    Vibrator(std::string mInputDevPath);
+
+    // Methods from ::android::hardware::vibrator::V1_0::IVibrator follow.
+    using Status = ::android::hardware::vibrator::V1_0::Status;
+    Return<Status> on(uint32_t timeoutMs)  override;
+    Return<Status> off()  override;
+    Return<bool> supportsAmplitudeControl() override;
+    Return<Status> setAmplitude(uint8_t amplitude) override;
+
+    using EffectStrength = ::android::hardware::vibrator::V1_0::EffectStrength;
+    Return<void> perform(V1_0::Effect effect, EffectStrength strength, perform_cb _hidl_cb)
+            override;
+    Return<void> perform_1_1(Effect_1_1 effect, EffectStrength strength, perform_cb _hidl_cb)
+            override;
+
+private:
+    ~Vibrator();
+    Return<Status> on(uint32_t timeoutMs, uint32_t playCount);
+    int openInputDev();
+    template <typename T>
+    Return<void> performWrapper(T effect, EffectStrength strength, perform_cb _hidl_cb);
+    Return<void> performEffect(Effect_1_1 effect, EffectStrength strength, perform_cb _hidl_cb);
+    std::string mInputDevPath;
+    int mfd;
+    struct ff_effect mEffect;
+
+};
+
+}  // namespace implementation
+}  // namespace V1_1
+}  // namespace vibrator
+}  // namespace hardware
+}  // namespace android
+
+class FileDescGuard {
+    public:
+        FileDescGuard(int fd) : m_fd(fd) {}
+
+        ~FileDescGuard() {
+            if (close(m_fd) != 0)
+            {
+                ALOGE("CA:: Failed to close fd %d, errno = %d", m_fd, errno);
+            }
+        }
+    private:
+        int m_fd = -1;
+};
+
+#endif  // ANDROID_HARDWARE_VIBRATOR_V1_1_VIBRATOR_H
diff --git a/vibrator/android.hardware.vibrator@1.1-service.sdm845.rc b/vibrator/android.hardware.vibrator@1.1-service.sdm845.rc
new file mode 100644
index 0000000..a47743a
--- /dev/null
+++ b/vibrator/android.hardware.vibrator@1.1-service.sdm845.rc
@@ -0,0 +1,4 @@
+service vendor.vibrator-1-1 /vendor/bin/hw/android.hardware.vibrator@1.1-service.sdm845
+    class hal
+    user system
+    group system
diff --git a/vibrator/service.cpp b/vibrator/service.cpp
new file mode 100644
index 0000000..6d13730
--- /dev/null
+++ b/vibrator/service.cpp
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "android.hardware.vibrator@1.2-service.sdm845"
+
+#include <log/log.h>
+
+#include <android/hardware/vibrator/1.1/IVibrator.h>
+#include <hidl/HidlSupport.h>
+#include <hidl/HidlTransportSupport.h>
+#include <utils/Errors.h>
+#include <utils/StrongPointer.h>
+
+#include <linux/input.h>
+
+#include <iostream>
+#include <stdio.h>
+#include <dirent.h>
+#include <fcntl.h>
+
+#include "Vibrator.h"
+
+#define DEV_INPUT_DIR "/dev/input"
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::joinRpcThreadpool;
+using android::hardware::vibrator::V1_1::IVibrator;
+using android::hardware::vibrator::V1_1::implementation::Vibrator;
+using namespace android;
+
+// From : https://github.com/ubports/hfd-service/blob/xenial/src/vibrator-ff.cpp#L46
+static bool inputDevSupportsFF(std::string devname) {
+    int ret;
+	unsigned char features[1 + FF_MAX/8/sizeof(unsigned char)];
+	int tempFd = open(devname.c_str(), O_RDWR);
+	int request = EVIOCGBIT(EV_FF, sizeof(features)*sizeof(unsigned char));
+	bool supported = false;
+
+    ALOGE("CA:: %s: Testing device: %s", __func__, devname.c_str());
+
+	if ((ret = ioctl(tempFd, request, &features)) < 0) {
+        ALOGE("CA:: %s: ioctl() failed with errno = %d", __func__, ret);
+		supported = false;
+    }
+	if (testBit(FF_RUMBLE, features)) {
+		supported = true;
+	}
+
+	close(tempFd);
+	return supported;
+}
+
+// Returns path event path to to the first input device
+// which supports forcefeedback.
+// Adapted from getevent.c (I know this is bad)
+static std::string findFirstFFDevice() {
+    char devname[PATH_MAX];
+    char *filename;
+    struct dirent *de;
+    DIR *dir = opendir(DEV_INPUT_DIR);
+    if (dir == NULL)
+        return NULL;
+    strcpy(devname, DEV_INPUT_DIR);
+    filename = devname + strlen(devname);
+    *filename++ = '/';
+    while((de = readdir(dir))) {
+        if (std::string(de->d_name).find("event") == std::string::npos)
+            continue;
+        strcpy(filename, de->d_name);
+        // At this point devname is the full path to the dirent
+        std::string devpath(devname);
+        if (inputDevSupportsFF(devpath)) {
+            closedir(dir);
+            ALOGI("CA:: %s(): Found haptics device: %s", __func__, devpath.c_str());
+            return devpath;
+        }
+    }
+    closedir(dir);
+    return "";
+}
+
+
+status_t registerVibratorService() {
+    std::string hapticsDev = findFirstFFDevice();
+    if (hapticsDev.length() < 2)
+        return UNKNOWN_ERROR;
+    sp<IVibrator> vibrator = new Vibrator(hapticsDev);
+    ALOGI("CA:: %s", __func__);
+
+    return vibrator->registerAsService();
+}
+
+int main() {
+    configureRpcThreadpool(1, true);
+    status_t status = registerVibratorService();
+
+    if (status != OK) {
+        return status;
+    }
+
+    joinRpcThreadpool();
+}