Add basic function for phosphor-nvme.

Add basic function to monitor temperature of
NVMe drive for phosphor-nvme.

Change-Id: Iebe3c8bf4b5cb958defab5b24a88f4bce477ad5e
Signed-off-by: Tony Lee <tony.lee@quantatw.com>
diff --git a/i2c.h b/i2c.h
new file mode 100644
index 0000000..2b2984d
--- /dev/null
+++ b/i2c.h
@@ -0,0 +1,34 @@
+#include <linux/i2c-dev.h>
+#include <linux/i2c.h>
+#include <linux/types.h>
+#include <sys/ioctl.h>
+
+#define I2C_DATA_MAX 256
+
+static inline __s32 i2c_read_after_write(int file, __u8 slave_addr, __u8 tx_len,
+                                         __u8* tx_buf, int rx_len, __u8* rx_buf)
+{
+    struct i2c_rdwr_ioctl_data msgst;
+    struct i2c_msg msg[2];
+    int ret;
+
+    msg[0].addr = slave_addr & 0xFF;
+    msg[0].flags = 0;
+    msg[0].buf = (__u8*)tx_buf;
+    msg[0].len = tx_len;
+
+    msg[1].addr = slave_addr & 0xFF;
+    msg[1].flags = I2C_M_RD | I2C_M_RECV_LEN;
+    msg[1].buf = (__u8*)rx_buf;
+    msg[1].len = rx_len;
+
+    msgst.msgs = msg;
+    msgst.nmsgs = 2;
+
+    ret = ioctl(file, I2C_RDWR, &msgst);
+
+    if (ret < 0)
+        return ret;
+
+    return ret;
+}
diff --git a/meson.build b/meson.build
index 07b1dd5..93a1537 100644
--- a/meson.build
+++ b/meson.build
@@ -12,6 +12,8 @@
     [
         'nvme_main.cpp',
         'nvme_manager.cpp',
+        'smbus.cpp',
+        'nvmes.cpp',
     ],
     dependencies: [
         dependency('phosphor-logging'),
@@ -23,6 +25,8 @@
     install_dir: get_option('bindir')
 )
 
+install_data(sources : 'nvme_config.json', install_dir : '/etc/nvme')
+
 conf_data = configuration_data()
 conf_data.set('NVME_REQUEST_NAME', '"xyz.openbmc_project.nvme.manager"')
 conf_data.set('NVME_OBJ_PATH_ROOT', '"/xyz/openbmc_project/sensors/temperature"')
diff --git a/nvme_config.json b/nvme_config.json
new file mode 100644
index 0000000..2f6423d
--- /dev/null
+++ b/nvme_config.json
@@ -0,0 +1,62 @@
+{
+    "config": [
+        {
+            "NVMeDriveIndex": 0,
+            "NVMeDriveBusID": 16,
+            "NVMeDrivePresentPin": 148,
+            "NVMeDrivePwrGoodPin": 161
+        },
+        {
+            "NVMeDriveIndex": 1,
+            "NVMeDriveBusID": 17,
+            "NVMeDrivePresentPin": 149,
+            "NVMeDrivePwrGoodPin": 162
+        },
+        {
+            "NVMeDriveIndex": 2,
+            "NVMeDriveBusID": 18,
+            "NVMeDrivePresentPin": 150,
+            "NVMeDrivePwrGoodPin": 163
+        },
+        {
+            "NVMeDriveIndex": 3,
+            "NVMeDriveBusID": 19,
+            "NVMeDrivePresentPin": 151,
+            "NVMeDrivePwrGoodPin": 164
+        },
+        {
+            "NVMeDriveIndex": 4,
+            "NVMeDriveBusID": 20,
+            "NVMeDrivePresentPin": 152,
+            "NVMeDrivePwrGoodPin": 165
+        },
+        {
+            "NVMeDriveIndex": 5,
+            "NVMeDriveBusID": 21,
+            "NVMeDrivePresentPin": 153,
+            "NVMeDrivePwrGoodPin": 166
+        },
+        {
+            "NVMeDriveIndex": 6,
+            "NVMeDriveBusID": 22,
+            "NVMeDrivePresentPin": 154,
+            "NVMeDrivePwrGoodPin": 167
+        },
+        {
+            "NVMeDriveIndex": 7,
+            "NVMeDriveBusID": 23,
+            "NVMeDrivePresentPin": 155,
+            "NVMeDrivePwrGoodPin": 168
+        }
+    ],
+    "threshold": [
+        {
+            "criticalHigh": 80,
+            "criticalLow": 0,
+            "warningHigh": 70,
+            "warningLow": 5,
+            "maxValue": 127,
+            "minValue": -128
+        }
+    ]
+}
\ No newline at end of file
diff --git a/nvme_main.cpp b/nvme_main.cpp
index 956e374..8552593 100644
--- a/nvme_main.cpp
+++ b/nvme_main.cpp
@@ -1,8 +1,14 @@
 #include "nvme_manager.hpp"
 
+#include <string.h>
+
+#include <fstream>
+#include <phosphor-logging/elog-errors.hpp>
+#include <phosphor-logging/log.hpp>
 #include <sdbusplus/bus.hpp>
 #include <sdbusplus/sdbus.hpp>
 #include <sdbusplus/server/manager.hpp>
+using namespace phosphor::logging;
 
 int main(void)
 {
diff --git a/nvme_manager.cpp b/nvme_manager.cpp
index 1f946f4..639f85d 100644
--- a/nvme_manager.cpp
+++ b/nvme_manager.cpp
@@ -1,9 +1,36 @@
 #include "nvme_manager.hpp"
 
+#include "smbus.hpp"
+
+#include <filesystem>
+#include <map>
+#include <nlohmann/json.hpp>
 #include <phosphor-logging/elog-errors.hpp>
 #include <phosphor-logging/log.hpp>
+#include <sstream>
+#include <string>
 
+#include "i2c.h"
 #define MONITOR_INTERVAL_SECONDS 1
+#define NVME_SSD_SLAVE_ADDRESS 0x6a
+#define GPIO_BASE_PATH "/sys/class/gpio/gpio"
+#define IS_PRESENT "0"
+#define POWERGD "1"
+
+static constexpr auto configFile = "/etc/nvme/nvme_config.json";
+static constexpr auto delay = std::chrono::milliseconds{100};
+using Json = nlohmann::json;
+
+static constexpr const uint8_t COMMAND_CODE_0 = 0;
+static constexpr const uint8_t COMMAND_CODE_8 = 8;
+
+static constexpr int SERIALNUMBER_START_INDEX = 3;
+static constexpr int SERIALNUMBER_END_INDEX = 23;
+
+static constexpr const int TEMPERATURE_SENSOR_FAILURE = 0x81;
+
+namespace fs = std::filesystem;
+
 namespace phosphor
 {
 namespace nvme
@@ -12,10 +39,108 @@
 using namespace std;
 using namespace phosphor::logging;
 
+std::string intToHex(int input)
+{
+    std::stringstream tmp;
+    tmp << std::hex << input;
+
+    return tmp.str();
+}
+
+/** @brief Get NVMe info over smbus  */
+bool getNVMeInfobyBusID(int busID, phosphor::nvme::Nvme::NVMeData& nvmeData)
+{
+    nvmeData.present = true;
+    nvmeData.vendor = "";
+    nvmeData.serialNumber = "";
+    nvmeData.smartWarnings = "";
+    nvmeData.statusFlags = "";
+    nvmeData.driveLifeUsed = "";
+    nvmeData.sensorValue = (int8_t)TEMPERATURE_SENSOR_FAILURE;
+
+    phosphor::smbus::Smbus smbus;
+
+    unsigned char rsp_data_command_0[I2C_DATA_MAX] = {0};
+    unsigned char rsp_data_command_8[I2C_DATA_MAX] = {0};
+
+    uint8_t tx_data = COMMAND_CODE_0;
+
+    auto init = smbus.smbusInit(busID);
+
+    static std::unordered_map<int, bool> isErrorSmbus;
+
+    if (init == -1)
+    {
+        if (isErrorSmbus[busID] != true)
+        {
+            log<level::ERR>("smbusInit fail!");
+            isErrorSmbus[busID] = true;
+        }
+
+        nvmeData.present = false;
+
+        return nvmeData.present;
+    }
+
+    auto res_int =
+        smbus.SendSmbusRWBlockCmdRAW(busID, NVME_SSD_SLAVE_ADDRESS, &tx_data,
+                                     sizeof(tx_data), rsp_data_command_0);
+
+    if (res_int < 0)
+    {
+        if (isErrorSmbus[busID] != true)
+        {
+            log<level::ERR>("Send command code 0 fail!");
+            isErrorSmbus[busID] = true;
+        }
+
+        smbus.smbusClose(busID);
+        nvmeData.present = false;
+        return nvmeData.present;
+    }
+
+    tx_data = COMMAND_CODE_8;
+
+    res_int =
+        smbus.SendSmbusRWBlockCmdRAW(busID, NVME_SSD_SLAVE_ADDRESS, &tx_data,
+                                     sizeof(tx_data), rsp_data_command_8);
+
+    if (res_int < 0)
+    {
+        if (isErrorSmbus[busID] != true)
+        {
+            log<level::ERR>("Send command code 8 fail!");
+            isErrorSmbus[busID] = true;
+        }
+
+        smbus.smbusClose(busID);
+        nvmeData.present = false;
+        return nvmeData.present;
+    }
+
+    nvmeData.vendor =
+        intToHex(rsp_data_command_8[1]) + " " + intToHex(rsp_data_command_8[2]);
+
+    for (int offset = SERIALNUMBER_START_INDEX; offset < SERIALNUMBER_END_INDEX;
+         offset++)
+    {
+        nvmeData.serialNumber += static_cast<char>(rsp_data_command_8[offset]);
+    }
+
+    nvmeData.statusFlags = intToHex(rsp_data_command_0[1]);
+    nvmeData.smartWarnings = intToHex(rsp_data_command_0[2]);
+    nvmeData.driveLifeUsed = intToHex(rsp_data_command_0[4]);
+    nvmeData.sensorValue = (int8_t)rsp_data_command_0[3];
+
+    smbus.smbusClose(busID);
+
+    isErrorSmbus[busID] = false;
+
+    return nvmeData.present;
+}
+
 void Nvme::run()
 {
-    init();
-
     std::function<void()> callback(std::bind(&Nvme::read, this));
     try
     {
@@ -29,12 +154,206 @@
     }
 }
 
-void Nvme::init()
+/** @brief Parsing NVMe config JSON file  */
+Json parseSensorConfig()
 {
+    std::ifstream jsonFile(configFile);
+    if (!jsonFile.is_open())
+    {
+        log<level::ERR>("NVMe config JSON file not found");
+    }
+
+    auto data = Json::parse(jsonFile, nullptr, false);
+    if (data.is_discarded())
+    {
+        log<level::ERR>("NVMe config readings JSON parser failure");
+    }
+
+    return data;
 }
 
+/** @brief Obtain the initial configuration value of NVMe  */
+std::vector<phosphor::nvme::Nvme::NVMeConfig> Nvme::getNvmeConfig()
+{
+
+    phosphor::nvme::Nvme::NVMeConfig nvmeConfig;
+    std::vector<phosphor::nvme::Nvme::NVMeConfig> nvmeConfigs;
+    int8_t criticalHigh = 0;
+    int8_t criticalLow = 0;
+    int8_t maxValue = 0;
+    int8_t minValue = 0;
+    int8_t warningHigh = 0;
+    int8_t warningLow = 0;
+
+    try
+    {
+        auto data = parseSensorConfig();
+        static const std::vector<Json> empty{};
+        std::vector<Json> readings = data.value("config", empty);
+        std::vector<Json> thresholds = data.value("threshold", empty);
+        if (!thresholds.empty())
+        {
+            for (const auto& instance : thresholds)
+            {
+                criticalHigh = instance.value("criticalHigh", 0);
+                criticalLow = instance.value("criticalLow", 0);
+                maxValue = instance.value("maxValue", 0);
+                minValue = instance.value("minValue", 0);
+                warningHigh = instance.value("warningHigh", 0);
+                warningLow = instance.value("warningLow", 0);
+            }
+        }
+        else
+        {
+            log<level::ERR>(
+                "Invalid NVMe config file, thresholds dosen't exist");
+        }
+
+        if (!readings.empty())
+        {
+            for (const auto& instance : readings)
+            {
+                uint8_t index = instance.value("NVMeDriveIndex", 0);
+                uint8_t busID = instance.value("NVMeDriveBusID", 0);
+                uint8_t presentPin = instance.value("NVMeDrivePresentPin", 0);
+                uint8_t pwrGoodPin = instance.value("NVMeDrivePwrGoodPin", 0);
+
+                nvmeConfig.index = std::to_string(index);
+                nvmeConfig.busID = busID;
+                nvmeConfig.presentPin = presentPin;
+                nvmeConfig.pwrGoodPin = pwrGoodPin;
+                nvmeConfig.criticalHigh = criticalHigh;
+                nvmeConfig.criticalLow = criticalLow;
+                nvmeConfig.warningHigh = warningHigh;
+                nvmeConfig.warningLow = warningLow;
+                nvmeConfig.maxValue = maxValue;
+                nvmeConfig.minValue = minValue;
+                nvmeConfigs.push_back(nvmeConfig);
+            }
+        }
+        else
+        {
+            log<level::ERR>("Invalid NVMe config file, config dosen't exist");
+        }
+    }
+    catch (const Json::exception& e)
+    {
+        log<level::ERR>("Json Exception caught."), entry("MSG: %s", e.what());
+    }
+
+    return nvmeConfigs;
+}
+
+std::string Nvme::getGPIOValueOfNvme(const std::string& fullPath)
+{
+    std::string val;
+    std::ifstream ifs;
+    auto retries = 3;
+
+    while (retries != 0)
+    {
+        try
+        {
+            if (!ifs.is_open())
+                ifs.open(fullPath);
+            ifs.clear();
+            ifs.seekg(0);
+            ifs >> val;
+        }
+        catch (const std::exception& e)
+        {
+            --retries;
+            std::this_thread::sleep_for(delay);
+            log<level::ERR>("Can not open gpio path.",
+                            entry("MSG: %s", e.what()));
+            continue;
+        }
+        break;
+    }
+
+    ifs.close();
+    return val;
+}
+
+/** @brief Monitor NVMe drives every one second  */
 void Nvme::read()
 {
+    std::string devPresentPath;
+    std::string devPwrGoodPath;
+
+    static std::unordered_map<std::string, bool> isErrorPower;
+
+    for (auto config : configs)
+    {
+        NVMeData nvmeData;
+        devPresentPath =
+            GPIO_BASE_PATH + std::to_string(config.presentPin) + "/value";
+
+        devPwrGoodPath =
+            GPIO_BASE_PATH + std::to_string(config.pwrGoodPin) + "/value";
+
+        auto iter = nvmes.find(config.index);
+
+        if (getGPIOValueOfNvme(devPresentPath) == IS_PRESENT)
+        {
+            // Drive status is good, update value or create d-bus and update
+            // value.
+            if (getGPIOValueOfNvme(devPwrGoodPath) == POWERGD)
+            {
+                // get NVMe information through i2c by busID.
+                getNVMeInfobyBusID(config.busID, nvmeData);
+                // can not find. create dbus
+                if (iter == nvmes.end())
+                {
+                    log<level::INFO>("SSD plug.",
+                                     entry("index = %s", config.index.c_str()));
+
+                    std::string objPath = NVME_OBJ_PATH + config.index;
+                    auto nvmeSSD = std::make_shared<phosphor::nvme::NvmeSSD>(
+                        bus, objPath.c_str());
+                    nvmes.emplace(config.index, nvmeSSD);
+
+                    nvmeSSD->setSensorValueToDbus(nvmeData.sensorValue);
+                    nvmeSSD->setSensorThreshold(
+                        config.criticalHigh, config.criticalLow,
+                        config.maxValue, config.minValue, config.warningHigh,
+                        config.warningLow);
+
+                    nvmeSSD->checkSensorThreshold();
+                }
+                else
+                {
+                    iter->second->setSensorValueToDbus(nvmeData.sensorValue);
+                    iter->second->checkSensorThreshold();
+                }
+                isErrorPower[config.index] = false;
+            }
+            else
+            {
+                // Present pin is true but power good pin is false
+                // remove nvme d-bus path
+                nvmeData = NVMeData();
+                nvmes.erase(config.index);
+
+                if (isErrorPower[config.index] != true)
+                {
+                    log<level::ERR>(
+                        "Present pin is true but power good pin is false.",
+                        entry("index = %s", config.index.c_str()));
+                    log<level::ERR>("Erase SSD from map and d-bus.",
+                                    entry("index = %s", config.index.c_str()));
+
+                    isErrorPower[config.index] = true;
+                }
+            }
+        }
+        else
+        {
+            // Drive not present, remove nvme d-bus path
+            nvmeData = NVMeData();
+            nvmes.erase(config.index);
+        }
+    }
 }
 } // namespace nvme
 } // namespace phosphor
diff --git a/nvme_manager.hpp b/nvme_manager.hpp
index b6f32c3..2b0e27d 100644
--- a/nvme_manager.hpp
+++ b/nvme_manager.hpp
@@ -1,5 +1,10 @@
+#pragma once
+
 #include "config.h"
 
+#include "nvmes.hpp"
+
+#include <fstream>
 #include <sdbusplus/bus.hpp>
 #include <sdbusplus/server.hpp>
 #include <sdbusplus/server/object.hpp>
@@ -12,6 +17,9 @@
 namespace nvme
 {
 
+/** @class Nvme
+ *  @brief Nvme manager implementation.
+ */
 class Nvme
 {
   public:
@@ -21,23 +29,80 @@
     Nvme(Nvme&&) = delete;
     Nvme& operator=(Nvme&&) = delete;
 
+    /** @brief Constructs Nvme
+     *
+     * @param[in] bus     - Handle to system dbus
+     * @param[in] objPath - The Dbus path of nvme
+     */
     Nvme(sdbusplus::bus::bus& bus) :
         bus(bus), _event(sdeventplus::Event::get_default()),
         _timer(_event, std::bind(&Nvme::read, this))
     {
+        // read json file
+        configs = getNvmeConfig();
     }
 
+    /**
+     * Structure for keeping nvme configure data required by nvme monitoring
+     */
+    struct NVMeConfig
+    {
+        std::string index;
+        uint8_t busID;
+        uint8_t presentPin;
+        uint8_t pwrGoodPin;
+        int8_t criticalHigh;
+        int8_t criticalLow;
+        int8_t maxValue;
+        int8_t minValue;
+        int8_t warningHigh;
+        int8_t warningLow;
+    };
+
+    /**
+     * Structure for keeping nvme data required by nvme monitoring
+     */
+    struct NVMeData
+    {
+        bool present;              /* Whether or not the nvme is present  */
+        std::string vendor;        /* The nvme manufacturer  */
+        std::string serialNumber;  /* The nvme serial number  */
+        std::string smartWarnings; /* Indicates smart warnings for the state  */
+        std::string statusFlags;   /* Indicates the status of the drives  */
+        std::string
+            driveLifeUsed;  /* A vendor specific estimate of the percentage  */
+        int8_t sensorValue; /* Sensor value, if sensor value didn't be
+                                  update, means sensor failure, default set to
+                                  129(0x81) accroding to NVMe-MI SPEC*/
+    };
+
+    /** @brief Setup polling timer in a sd event loop and attach to D-Bus
+     *         event loop.
+     */
     void run();
 
-  private:
-    sdbusplus::bus::bus& bus;
+    /** @brief Get GPIO value of nvme by sysfs */
+    std::string getGPIOValueOfNvme(const std::string& fullPath);
+    /** @brief Map of the object NvmeSSD */
+    std::unordered_map<std::string, std::shared_ptr<phosphor::nvme::NvmeSSD>>
+        nvmes;
 
+  private:
+    /** @brief sdbusplus bus client connection. */
+    sdbusplus::bus::bus& bus;
+    /** @brief the Event Loop structure */
     sdeventplus::Event _event;
     /** @brief Read Timer */
     sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic> _timer;
 
+    std::vector<phosphor::nvme::Nvme::NVMeConfig> configs;
+
+    /** @brief Set up initial configuration value of NVMe */
     void init();
+    /** @brief Monitor NVMe drives every one second  */
     void read();
+
+    std::vector<phosphor::nvme::Nvme::NVMeConfig> getNvmeConfig();
 };
 } // namespace nvme
-} // namespace phosphor
\ No newline at end of file
+} // namespace phosphor
diff --git a/nvmes.cpp b/nvmes.cpp
new file mode 100644
index 0000000..01222d0
--- /dev/null
+++ b/nvmes.cpp
@@ -0,0 +1,46 @@
+#include "nvmes.hpp"
+
+namespace phosphor
+{
+namespace nvme
+{
+
+void NvmeSSD::checkSensorThreshold()
+{
+    int8_t value = ValueIface::value();
+    int8_t criticalHigh = CriticalInterface::criticalHigh();
+    int8_t criticalLow = CriticalInterface::criticalLow();
+    int8_t warningHigh = WarningInterface::warningHigh();
+    int8_t warningLow = WarningInterface::warningLow();
+
+    CriticalInterface::criticalAlarmHigh(value > criticalHigh);
+
+    CriticalInterface::criticalAlarmLow(value < criticalLow);
+
+    WarningInterface::warningAlarmHigh(value > warningHigh);
+
+    WarningInterface::warningAlarmLow(value < warningLow);
+}
+
+void NvmeSSD::setSensorThreshold(int8_t criticalHigh, int8_t criticalLow,
+                                 int8_t maxValue, int8_t minValue,
+                                 int8_t warningHigh, int8_t warningLow)
+{
+
+    CriticalInterface::criticalHigh(criticalHigh);
+    CriticalInterface::criticalLow(criticalLow);
+
+    WarningInterface::warningHigh(warningHigh);
+    WarningInterface::warningLow(warningLow);
+
+    ValueIface::maxValue(maxValue);
+    ValueIface::minValue(minValue);
+}
+
+void NvmeSSD::setSensorValueToDbus(const int8_t value)
+{
+    ValueIface::value(value);
+}
+
+} // namespace nvme
+} // namespace phosphor
\ No newline at end of file
diff --git a/nvmes.hpp b/nvmes.hpp
new file mode 100644
index 0000000..c9a133e
--- /dev/null
+++ b/nvmes.hpp
@@ -0,0 +1,64 @@
+#pragma once
+
+#include "config.h"
+
+#include <sdbusplus/bus.hpp>
+#include <sdbusplus/server.hpp>
+#include <sdeventplus/clock.hpp>
+#include <sdeventplus/event.hpp>
+#include <sdeventplus/utility/timer.hpp>
+#include <xyz/openbmc_project/Sensor/Threshold/Critical/server.hpp>
+#include <xyz/openbmc_project/Sensor/Threshold/Warning/server.hpp>
+#include <xyz/openbmc_project/Sensor/Value/server.hpp>
+
+namespace phosphor
+{
+namespace nvme
+{
+
+using ValueIface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;
+
+using CriticalInterface =
+    sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;
+
+using WarningInterface =
+    sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;
+
+using NvmeIfaces =
+    sdbusplus::server::object::object<ValueIface, CriticalInterface,
+                                      WarningInterface>;
+
+class NvmeSSD : public NvmeIfaces
+{
+  public:
+    NvmeSSD() = delete;
+    NvmeSSD(const NvmeSSD&) = delete;
+    NvmeSSD& operator=(const NvmeSSD&) = delete;
+    NvmeSSD(NvmeSSD&&) = delete;
+    NvmeSSD& operator=(NvmeSSD&&) = delete;
+    virtual ~NvmeSSD() = default;
+
+    /** @brief Constructs NvmeSSD
+     *
+     * @param[in] bus     - Handle to system dbus
+     * @param[in] objPath - The Dbus path of nvme
+     */
+    NvmeSSD(sdbusplus::bus::bus& bus, const char* objPath) :
+        NvmeIfaces(bus, objPath), bus(bus)
+    {
+    }
+
+    /** @brief Set sensor value temperature to nvme D-bus  */
+    void setSensorValueToDbus(const int8_t value);
+    /** @brief Check if sensor value higher or lower threshold */
+    void checkSensorThreshold();
+    /** @brief Set Sensor Threshold to D-bus at beginning */
+    void setSensorThreshold(int8_t criticalHigh, int8_t criticalLow,
+                            int8_t maxValue, int8_t minValue,
+                            int8_t warningHigh, int8_t warningLow);
+
+  private:
+    sdbusplus::bus::bus& bus;
+};
+} // namespace nvme
+} // namespace phosphor
\ No newline at end of file
diff --git a/smbus.cpp b/smbus.cpp
new file mode 100644
index 0000000..7e8d968
--- /dev/null
+++ b/smbus.cpp
@@ -0,0 +1,129 @@
+#include "smbus.hpp"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include <iostream>
+#include <mutex>
+
+#include "i2c.h"
+
+#define MAX_I2C_BUS 30
+static constexpr bool DEBUG = false;
+
+static int fd[MAX_I2C_BUS] = {0};
+
+namespace phosphor
+{
+namespace smbus
+{
+
+std::mutex gMutex;
+
+int phosphor::smbus::Smbus::openI2cDev(int i2cbus, char* filename, size_t size,
+                                       int quiet)
+{
+    int file;
+
+    snprintf(filename, size, "/dev/i2c/%d", i2cbus);
+    filename[size - 1] = '\0';
+    file = open(filename, O_RDWR);
+
+    if (file < 0 && (errno == ENOENT || errno == ENOTDIR))
+    {
+        sprintf(filename, "/dev/i2c-%d", i2cbus);
+        file = open(filename, O_RDWR);
+    }
+
+    if (DEBUG)
+    {
+        if (file < 0 && !quiet)
+        {
+            if (errno == ENOENT)
+            {
+                fprintf(stderr,
+                        "Error: Could not open file "
+                        "`/dev/i2c-%d' or `/dev/i2c/%d': %s\n",
+                        i2cbus, i2cbus, strerror(ENOENT));
+            }
+            else
+            {
+                fprintf(stderr,
+                        "Error: Could not open file "
+                        "`%s': %s\n",
+                        filename, strerror(errno));
+                if (errno == EACCES)
+                    fprintf(stderr, "Run as root?\n");
+            }
+        }
+    }
+
+    return file;
+}
+
+int phosphor::smbus::Smbus::smbusInit(int smbus_num)
+{
+    int res = 0;
+    char filename[20];
+
+    gMutex.lock();
+
+    fd[smbus_num] = openI2cDev(smbus_num, filename, sizeof(filename), 0);
+    if (fd[smbus_num] < 0)
+    {
+        gMutex.unlock();
+
+        return -1;
+    }
+
+    res = fd[smbus_num];
+
+    gMutex.unlock();
+
+    return res;
+}
+
+void phosphor::smbus::Smbus::smbusClose(int smbus_num)
+{
+    close(fd[smbus_num]);
+}
+
+int phosphor::smbus::Smbus::SendSmbusRWBlockCmdRAW(int smbus_num,
+                                                   int8_t device_addr,
+                                                   uint8_t* tx_data,
+                                                   uint8_t tx_len,
+                                                   uint8_t* rsp_data)
+{
+    int res, res_len;
+    unsigned char Rx_buf[I2C_DATA_MAX] = {0};
+
+    Rx_buf[0] = 1;
+
+    gMutex.lock();
+
+    res = i2c_read_after_write(fd[smbus_num], device_addr, tx_len,
+                               (unsigned char*)tx_data, I2C_DATA_MAX,
+                               (unsigned char*)Rx_buf);
+
+    if (res < 0)
+    {
+        fprintf(stderr, "Error: SendSmbusRWBlockCmdRAW failed\n");
+    }
+
+    res_len = Rx_buf[0] + 1;
+
+    memcpy(rsp_data, Rx_buf, res_len);
+
+    gMutex.unlock();
+
+    return res;
+}
+
+} // namespace smbus
+} // namespace phosphor
diff --git a/smbus.hpp b/smbus.hpp
new file mode 100644
index 0000000..c270d01
--- /dev/null
+++ b/smbus.hpp
@@ -0,0 +1,34 @@
+#pragma once
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+namespace phosphor
+{
+namespace smbus
+{
+
+class Smbus
+{
+  public:
+    Smbus(){};
+
+    int openI2cDev(int i2cbus, char* filename, size_t size, int quiet);
+
+    int smbusInit(int smbus_num);
+
+    void smbusClose(int smbus_num);
+
+    int SendSmbusRWBlockCmdRAW(int smbus_num, int8_t device_addr,
+                               uint8_t* tx_data, uint8_t tx_len,
+                               uint8_t* rsp_data);
+};
+
+} // namespace smbus
+} // namespace phosphor
\ No newline at end of file