[Refactoring] return 'task_id' when calling runNPU_sync/async
[platform/adaptation/npu/trix-engine.git] / src / core / ne-handler.cc
index 816887f..1550b79 100644 (file)
@@ -4,23 +4,21 @@
  * Copyright (C) 2020 Dongju Chae <dongju.chae@samsung.com>
  */
 /**
- * @file ne-host-handler.cc
+ * @file ne-handler.cc
  * @date 03 Apr 2020
- * @brief Implementation of APIs to access NPU from Host
+ * @brief Impelemetation of NPU Engine entrypoint that handles APIs from host
  * @see https://code.sec.samsung.net/confluence/display/ODLC/2020+Overall+Software+Stack
  * @author Dongju Chae <dongju.chae@samsung.com>
  * @bug No known bugs except for NYI items
  */
 
+#include "ne-handler.h"
+#include "ne-data.h"
+
 #include <npubinfmt.h>
 #include <NPUdrvAPI.h>
 #include <CommPlugin.h>
 
-#include "ne-utils.h"
-#include "ne-mem.h"
-#include "ne-scheduler.h"
-#include "ne-handler.h"
-
 #include <string.h>
 #include <assert.h>
 
 
 #define TAG _N2
 
-#define INIT_HOST_HANDLER(handler, dev) \
-  Device *tdev = static_cast <Device *> (dev); \
-  if (tdev == nullptr) return -EINVAL; \
-  HostHandler *handler = tdev->getHostHandler (); \
-  if (handler == nullptr) return -EINVAL;
-
-/** @brief device class. it contains all related instances */
-class Device {
-  public:
-    /** @brief Factory method to create a trinity device dependong on dev type */
-    static Device *createInstance (dev_type device_type, int device_id);
-
-    /** @brief constructor of device */
-    Device (dev_type type, int id, bool need_model = true)
-      : comm_(CommPlugin::getCommPlugin()), type_ (type), id_ (id),
-        need_model_ (true), mode_ (NPUASYNC_WAIT), initialized_ (ATOMIC_FLAG_INIT) {}
-
-    /** @brief destructor of device */
-    virtual ~Device () {}
-
-    /** @brief initialization */
-    int init () {
-      if (!initialized_.test_and_set()) {
-        /** create the corresponding driver API */
-        api_ = DriverAPI::createDriverAPI (type_, id_);
-        if (api_.get() == nullptr) {
-          initialized_.clear();
-          logerr (TAG, "Failed to create driver API\n");
-          return -EINVAL;
-        }
-
-        handler_.reset (new HostHandler (this));
-        scheduler_.reset (new Scheduler (api_.get()));
-        mem_ = MemAllocator::createInstance (api_.get());
-      }
-
-      return 0;
-    }
-
-    HostHandler *getHostHandler () { return handler_.get(); }
-    dev_type getType () { return type_; }
-    int getID () { return id_; }
-    bool needModel () { return need_model_; }
-    void setAsyncMode (npu_async_mode mode) { mode_ = mode; }
-
-    HWmem * allocMemory () { return mem_->allocMemory (); }
-    void deallocMemory (int dmabuf_fd) { mem_->deallocMemory (dmabuf_fd); }
-
-    /** it stops all requests in this device (choose wait or force) */
-    int stop (bool force_stop) {
-      Request *req = new Request (NPUINPUT_STOP);
-      req->setForceStop (force_stop);
-      return scheduler_->submitRequest (req);
-    }
-
-    virtual Model * registerModel (const generic_buffer *model) = 0;
-    virtual int run (npu_input_opmode opmode, const Model *model,
-        const input_buffers *input, npuOutputNotify cb, void *cb_data,
-        uint64_t *sequence) = 0;
-
-  protected:
-    /** the device instance has ownership of all related components */
-    std::unique_ptr<DriverAPI>    api_;       /**< device api */
-    std::unique_ptr<MemAllocator> mem_;       /**< memory allocator */
-    std::unique_ptr<HostHandler>  handler_;   /**< host handler */
-    std::unique_ptr<Scheduler>    scheduler_; /**< scheduler */
-
-    CommPlugin& comm_;                        /**< plugin communicator */
-
-    dev_type type_;                           /**< device type */
-    int id_;                                  /**< device id */
-    bool need_model_;                         /**< indicates whether the device needs model */
-    npu_async_mode mode_;                     /**< async run mode */
-
-  private:
-    std::atomic_flag initialized_;
-};
-
-/** @brief Trinity Vision (TRIV) classs */
-class TrinityVision : public Device {
-  public:
-    TrinityVision (int id) : Device (NPUCOND_TRIV_CONN_SOCIP, id) {}
-    ~TrinityVision () {}
-
-    static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
-        void *dst, void *src, size_t size);
-
-    Model * registerModel (const generic_buffer *model_buf) {
-      Model *model = mem_->allocModel ();
-      if (model == nullptr) {
-        logerr (TAG, "Failed to allocate model\n");
-        return nullptr;
-      }
-
-      int status;
-      if (model_buf->type == BUFFER_DMABUF) {
-        model->setDmabuf (model_buf->dmabuf);
-        model->setOffset (model_buf->offset);
-        model->setSize (model_buf->size);
-      } else {
-        status = model->alloc (model_buf->size);
-        if (status != 0) {
-          logerr (TAG, "Failed to allocate model: %d\n", status);
-          goto delete_exit;
-        }
-
-        status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
-        if (status != 0) {
-          logerr (TAG, "Failed to extract generic buffer: %d\n", status);
-          goto delete_exit;
-        }
-      }
-
-      status = model->setMetadata (model->getData());
-      if (status != 0)
-        goto delete_exit;
-
-      model_config_t config;
-      config.dmabuf_id = model->getDmabuf();
-      config.program_size = model->getMetadata()->getProgramSize();
-      config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
-      config.weight_offset_addr = config.program_offset_addr + config.program_size;
-
-      status = api_->setModel (&config);
-      if (status != 0)
-        goto delete_exit;
-
-      return model;
-
-delete_exit:
-      delete model;
-      return nullptr;
-    }
-
-    Buffer * prepareInputBuffers (const Model *model, const input_buffers *input) {
-      const Metadata *meta = model->getMetadata();
-      const generic_buffer *first = &input->bufs[0];
-
-      if (meta->getInputNum() != input->num_buffers)
-        return nullptr;
-
-      Buffer * buffer = mem_->allocBuffer ();
-      if (buffer != nullptr) {
-        if (first->type == BUFFER_DMABUF) {
-          buffer->setDmabuf (first->dmabuf);
-          buffer->setOffset (first->offset);
-          buffer->setSize (meta->getBufferSize());
-        } else {
-          int status = buffer->alloc (meta->getBufferSize ());
-          if (status != 0) {
-            logerr (TAG, "Failed to allocate buffer: %d\n", status);
-            delete buffer;
-            return nullptr;
-          }
-        }
-      }
-
-      buffer->createTensors (meta);
-      return buffer;
-    }
-
-    int run (npu_input_opmode opmode, const Model *model,
-        const input_buffers *input, npuOutputNotify cb, void *cb_data,
-        uint64_t *sequence) {
-      if (opmode != NPUINPUT_HOST)
-        return -EINVAL;
-
-      Buffer *buffer = prepareInputBuffers (model, input);
-      if (buffer == nullptr)
-        return -EINVAL;
-
-      for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
-        auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
-            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
-        int status = comm_.extractGenericBuffer (&input->bufs[idx],
-            buffer->getInputTensor(idx)->getData(), func);
-        if (status != 0) {
-          logerr (TAG, "Failed to feed input buffer: %d\n", status);
-          return status;
-        }
-      }
-
-      /** this device uses CMA buffer */
-
-      Request *req = new Request (opmode);
-      req->setModel (model);
-      req->setBuffer (buffer);
-      req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
-
-      if (sequence)
-        *sequence = req->getID();
-
-      return scheduler_->submitRequest (req);
-    }
-
-    void callback (Request *req, npuOutputNotify cb, void *cb_data) {
-      const Model *model = req->getModel ();
-      Buffer *buffer = req->getBuffer ();
-      output_buffers output = {
-        .num_buffers = buffer->getOutputNum ()
-      };
-
-      for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
-        uint32_t output_tensor_size = model->getOutputTensorSize (idx);
-
-        output.bufs[idx].type = BUFFER_MAPPED;
-        output.bufs[idx].size = output_tensor_size;
-        /** user needs to free this */
-        output.bufs[idx].addr = malloc (output_tensor_size);
-
-        auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
-            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
-        int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
-            &output.bufs[idx], func);
-        if (status != 0) {
-          logerr (TAG, "Failed to return output buffer: %d\n", status);
-        }
-      }
-
-      cb (&output, req->getID(), cb_data);
-    }
-};
-
-/** @brief Trinity Vision2 (TRIV2) classs */
-class TrinityVision2 : public Device {
-  public:
-    TrinityVision2 (int id) : Device (NPUCOND_TRIV2_CONN_SOCIP, id) {}
-    ~TrinityVision2 () {}
-
-    static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
-        void *dst, void *src, size_t size) {
-      memcpy (dst, src, size);
-      return size;
-    }
-
-    Model * registerModel (const generic_buffer *model_buf) {
-      /** TODO: model's weight values are stored in segments */
-      return nullptr;
-    }
-
-    int run (npu_input_opmode opmode, const Model *model,
-        const input_buffers *input, npuOutputNotify cb, void *cb_data,
-        uint64_t *sequence) {
-      if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
-        return -EINVAL;
-
-      /** this device uses segment table */
-
-      Request *req = new Request (opmode);
-      req->setModel (model);
-#if 0
-      req->setSegmentTable (segt);
-#endif
-      req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
-
-      if (sequence)
-        *sequence = req->getID();
-
-      return scheduler_->submitRequest (req);
-    }
-
-    void callback (Request *req, npuOutputNotify cb, void *cb_data) {
-    }
-};
-
-/** @brief Trinity Asr (TRIA) classs */
-class TrinityAsr : public Device {
-  public:
-    TrinityAsr (int id) : Device (NPUCOND_TRIA_CONN_SOCIP, id, false) {}
-    ~TrinityAsr () {}
-
-    static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
-        void *dst, void *src, size_t size) {
-      memcpy (dst, src, size);
-      return size;
-    }
-
-    Model * registerModel (const generic_buffer *model_buf) { return nullptr; }
-
-    int run (npu_input_opmode opmode, const Model *model,
-        const input_buffers *input, npuOutputNotify cb, void *cb_data,
-        uint64_t *sequence) {
-      if (opmode != NPUINPUT_HOST)
-        return -EINVAL;
-
-      /** ASR does not require model and support only a single tensor */
-      const generic_buffer *first_buf = &input->bufs[0];
-      Buffer * buffer = mem_->allocBuffer ();
-      int status;
-      if (first_buf->type == BUFFER_DMABUF) {
-        buffer->setDmabuf (first_buf->dmabuf);
-        buffer->setOffset (first_buf->offset);
-        buffer->setSize (first_buf->size);
-      } else {
-        status = buffer->alloc (first_buf->size);
-        if (status != 0) {
-          delete buffer;
-          return status;
-        }
-      }
-      buffer->createTensors ();
-
-      status = comm_.extractGenericBuffer (first_buf,
-          buffer->getInputTensor(0)->getData(), nullptr);
-      if (status != 0)
-        return status;
-
-      Request *req = new Request (opmode);
-      req->setBuffer (buffer);
-      req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
-
-      if (sequence)
-        *sequence = req->getID();
-
-      return scheduler_->submitRequest (req);
-    }
-
-    void callback (Request *req, npuOutputNotify cb, void *cb_data) {
-    }
-};
-
-#ifdef ENABLE_MANIP
-
-#define do_quantized_memcpy(type) do {\
-    idx = 0;\
-    if (quant) {\
-      while (idx < num_elems) {\
-          val = ((type *) src)[idx];\
-          val = val / _scale;\
-          val += _zero_point;\
-          val = (val > 255.0) ? 255.0 : 0.0;\
-          ((uint8_t *) dst)[idx++] = (uint8_t) val;\
-      }\
-    } else {\
-      while (idx < num_elems) {\
-          val = *(uint8_t *) src;\
-          val -= _zero_point;\
-          val *= _scale;\
-          ((type *) dst)[idx++] = (type) val;\
-          dst = (void*)(((uint8_t *) dst) + data_size);\
-          src = (void*)(((uint8_t *) src) + 1);\
-      }\
-    }\
-  } while (0)
-
-/**
- * @brief memcpy during quantization
- */
-static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
-    void *dst, const void *src, uint32_t num_elems)
+/** @brief host handler constructor */
+HostHandler::HostHandler (Device *device)
+  : device_(device),
+    /* ignored as we don't use double buffering anymore, but for backward-compatibility */
+    async_mode_ (NPUASYNC_WAIT)
 {
-  double _scale = (double) scale;
-  double _zero_point = (double) zero_point;
-  double val;
-  uint32_t data_size = get_data_size (type);
-  uint32_t idx;
+}
 
-  switch (type) {
-    case DATA_TYPE_INT8:
-      do_quantized_memcpy (int8_t);
-      break;
-    case DATA_TYPE_UINT8:
-      do_quantized_memcpy (uint8_t);
-      break;
-    case DATA_TYPE_INT16:
-      do_quantized_memcpy (int16_t);
-      break;
-    case DATA_TYPE_UINT16:
-      do_quantized_memcpy (uint16_t);
-      break;
-    case DATA_TYPE_INT32:
-      do_quantized_memcpy (int32_t);
-      break;
-    case DATA_TYPE_UINT32:
-      do_quantized_memcpy (uint32_t);
-      break;
-    case DATA_TYPE_INT64:
-      do_quantized_memcpy (int64_t);
-      break;
-    case DATA_TYPE_UINT64:
-      do_quantized_memcpy (uint64_t);
-      break;
-    case DATA_TYPE_FLOAT32:
-      do_quantized_memcpy (float);
-      break;
-    case DATA_TYPE_FLOAT64:
-      do_quantized_memcpy (double);
-      break;
-    default:
-      logerr (TAG, "Unsupported datatype %d\n", type);
-  }
+/** @brief host handler destructor */
+HostHandler::~HostHandler ()
+{
 }
 
 /**
- * @brief perform data manipulation
- * @param[in] model model instance
- * @param[in] idx tensor index
- * @param[in] is_input indicate it's input manipulation
- * @param[out] dst destination buffer
- * @param[in] src source buffer (feature map)
- * @param[in] size size to be copied
- * @return size of memory copy if no error, otherwise zero
- *
- * @note the input data format should be NHWC
- * @detail rules for the memory address of activations in NPU HW.
- *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
- *
- * 1) Special case (depth == 3)
- * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
- *
- * 2) Common case
- * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
- *
- * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
+ * @brief register model from generic buffer
+ * @param[in] model_buf model buffer
+ * @param[out] modelid model id
+ * @return 0 if no error. otherwise a negative errno
  */
-size_t
-TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
-    void *dst, void *src, size_t size)
+int
+HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
 {
-  const Metadata *meta = model->getMetadata();
-  const tensor_data_info* info;
-  const uint32_t *dims;
-  uint32_t zero_point;
-  float scale;
-
-  /** extract required information from the metadata */
-  if (is_input) {
-    if (idx >= meta->getInputNum()) {
-      logerr (TAG, "Wrong information for input tensors in metadata\n");
-      return 0;
-    }
-
-    info = model->getInputDataInfo (idx);
-    dims = meta->getInputDims (idx);
-    zero_point = meta->getInputQuantZero (idx);
-    scale = meta->getInputQuantScale (idx);
-  } else {
-    if (idx >= meta->getOutputNum()) {
-      logerr (TAG, "Wrong information for output tensors in metadata\n");
-      return 0;
-    }
-
-    info = model->getOutputDataInfo (idx);
-    dims = meta->getOutputDims (idx);
-    zero_point = meta->getOutputQuantZero (idx);
-    scale = meta->getOutputQuantScale (idx);
+  if (model_buf == nullptr || modelid == nullptr) {
+    logerr (TAG, "Invalid arguments given\n");
+    return -EINVAL;
   }
 
-  if (info == nullptr) {
-    logerr (TAG, "Unmatched tensors info\n");
-    return 0;
+  Model *model = nullptr;
+  int status = device_->setModel (model_buf, &model);
+  if (status != 0) {
+    logerr (TAG, "Failed to set model: %d\n", status);
+    return status;
   }
 
-  uint32_t batch = dims[0];
-  uint32_t height = dims[1];
-  uint32_t width = dims[2];
-  uint32_t depth = dims[3];
-
-  uint32_t data_size = get_data_size (info->type);
-  if (data_size == 0) {
-    logerr (TAG, "Invalid data size\n");
-    return 0;
-  }
+  assert (model != nullptr);
 
-  bool need_quantization = false;
-  /**
-   * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
-   * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
-   */
-  if (info->type != DATA_TYPE_SRNPU) {
-    assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
-
-    if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
-        !(zero_point == DEFAULT_ZERO_POINT && scale == DEFAULT_SCALE))
-      need_quantization = true;
+  status = models_.insert (model->getID(), model);
+  if (status != 0) {
+    logerr (TAG, "Failed to insert model id\n");
+    delete model;
+    return status;
   }
 
-  /** check data manipulation is required */
-  if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
-    uint32_t MPA_L = DATA_GRANULARITY;
-    uint32_t n, h, w, d;
-    uint32_t std_offset;  /* standard offset in NHWC data format */
-    uint32_t npu_offset;  /* npu offset in NPU HW data format*/
-    uint32_t src_offset;
-    uint32_t dst_offset;
-    uint32_t slice_size;
-
-    /* @todo we currently support only NHWC */
-    if (info->layout != DATA_LAYOUT_NHWC) {
-      logerr (TAG, "data manipulation is supported for NHWC only\n");
-      return -EINVAL;
-    }
+  *modelid = model->getID();
+  return 0;
+}
 
-    for (n = 0; n < batch; n++) {
-      for (h = 0; h < height; h++) {
-        for (w = 0; w < width; w++) {
-          for (d = 0; d < depth; d += MPA_L) {
-            std_offset = d + depth * (w + width * (h + n * height));
-            npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
-            slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
-
-            if (is_input) {
-              src_offset = std_offset * data_size;
-              dst_offset = npu_offset;
-            } else {
-              src_offset = npu_offset;
-              dst_offset = std_offset * data_size;
-            }
-
-            /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
-            if (need_quantization) {
-              memcpy_with_quant (is_input, info->type, scale, zero_point,
-                  static_cast<char*>(dst) + dst_offset,
-                  static_cast<char*>(src) + src_offset,
-                  slice_size);
-            } else {
-              memcpy (
-                  static_cast<char*>(dst) + dst_offset,
-                  static_cast<char*>(src) + src_offset,
-                  slice_size);
-            }
-          }
-        }
-      }
-    }
-  } else if (need_quantization) {
-    /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
-    if (is_input)
-      size = size / data_size;
+/**
+ * @brief remove the registered model
+ * @param[in] modelid model id
+ * @return 0 if no error. otherwise a negative errno
+ */
+int
+HostHandler::unregisterModel (uint32_t modelid)
+{
+  Model *model = models_.find (modelid);
+  if (model == nullptr)
+    return -ENOENT;
 
-    memcpy_with_quant (is_input, info->type, scale, zero_point,
-        dst, src, size);
-  } else {
-    memcpy (dst, src, size);
+  int status = device_->unsetModel (model);
+  if (status != 0) {
+    logerr (TAG, "Failed to unset model: %d\n", status);
+    return status;
   }
 
-  return 0;
+  return models_.remove (modelid);
 }
 
-#else
-
-size_t
-TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
-    void *dst, void *src, size_t size)
+/**
+ * @brief remove all registered models
+ * @return 0
+ */
+int
+HostHandler::unregisterModels ()
 {
-  memcpy (dst, src, size);
-  return size;
-}
+  std::function <bool (Model *)> functor =
+    [&] (Model *m) -> bool {
+      bool can_remove = true;
+      int status = device_->unsetModel (m);
+      if (status != 0) {
+        logwarn (TAG, "Failed to unset model: %d\n", status);
+        can_remove = false;
+      }
+      return can_remove;
+    };
 
-#endif
+  models_.for_each (functor);
+  return 0;
+}
 
 /**
- * @brief create device instance depending on device type and id
- * @param[in] type device type
- * @param[in] id device id
- * @return device instance
+ * @brief Get the profile information from NPU
+ * @param[in] task_id The identifier for each inference
+ * @param[out] profile The profile instance
+ * @return 0 if no error, otherwise a negative errno.
  */
-Device *
-Device::createInstance (dev_type type, int id)
+int
+HostHandler::getProfile (int task_id, npu_profile *profile)
 {
-  Device *device = nullptr;
-
-  switch (type & DEVICETYPE_MASK) {
-    case DEVICETYPE_TRIV:
-      device = new TrinityVision (id);
-      break;
-    case DEVICETYPE_TRIV2:
-      device = new TrinityVision2 (id);
-      break;
-    case DEVICETYPE_TRIA:
-      device = new TrinityAsr (id);
-      break;
-    default:
-      break;
+  if (task_id < 0 || profile == nullptr) {
+    logerr (TAG, "Invalid parameter provided\n");
+    return -EINVAL;
   }
 
-  if (device != nullptr && device->init () != 0) {
-    delete device;
-    device = nullptr;
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
+
+  profile->num_layers = 0;
+  profile->layers = nullptr;
+
+  int status = api->getProfile (task_id, profile);
+  if (status != 0) {
+    logerr (TAG, "Failed to get profile information: %d\n", status);
+    return status;
   }
 
-  return device;
+  return 0;
 }
 
-/** @brief host handler constructor */
-HostHandler::HostHandler (Device *device)
-  : device_(device)
+/**
+ * @brief get the stats for the latest apps of the target device
+ * @param[out] stat The list of app stat
+ * @note The caller has the responsibility to free the resources.
+ *       This API is not working on the emulated envionment.
+ */
+int
+HostHandler::getStatApps (npu_stat_apps *stat)
 {
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
+
+  return api->getStatApps (stat);
 }
 
-/** @brief host handler destructor */
-HostHandler::~HostHandler ()
+/**
+ * @brief get the stats for the latest tasks of the target app
+ * @param[in] appid The identifier of target app
+ * @param[out] stat The list of task stat
+ * @note The caller has the responsibility to free the resources.
+ *       This API is not working on the emulated envionment.
+ */
+int
+HostHandler::getStatTasks (int appid, npu_stat_tasks *stat)
 {
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
+
+  return api->getStatTasks (appid, stat);
 }
 
 /**
- * @brief register model from generic buffer
- * @param[in] model_buf model buffer
- * @param[out] modelid model id
- * @return 0 if no error. otherwise a negative errno
+ * @brief Get the driver API level of opened NPU device
+ * @param[out] level driver API level
+ * @return 0 if no error, otherwise a negative errno
  */
 int
-HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
+HostHandler::getAPILevel (uint32_t *level)
 {
-  Model *model = device_->registerModel (model_buf);
-  if (model == nullptr) {
-    logerr (TAG, "Failed to register model\n");
-    return -EINVAL;
-  }
-
-  int status = models_.insert (model->getID(), model);
-  if (status != 0) {
-    logerr (TAG, "Failed to insert model id\n");
-    delete model;
-    return status;
-  }
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
 
-  *modelid = model->getID();
-  return 0;
+  return api->getAPILevel (level);
 }
 
 /**
- * @brief remove the registered model
- * @param[in] modelid model id
- * @return 0 if no error. otherwise a negative errno
+ * @brief Get the TOPS of the opened NPU device
+ * @param[in] dev the NPU device handle
+ * @param[out] tops npu tops
+ * @return 0 if no error, otherwise a negative errno
+ * @note this does not support for emulated devices
  */
 int
-HostHandler::unregisterModel (uint32_t modelid)
+HostHandler::getTops (uint32_t *tops)
 {
-  return models_.remove (modelid);
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
+
+  return api->getTops (tops);
 }
 
 /**
- * @brief remove all registered models
- * @return 0
+ * @brief Get the DSP DSPM size of the opened NPU device
+ * @param[in] dev the NPU device handle
+ * @param[out] dspm dspm size
+ * @return 0 if no error, otherwise a negative errno
+ * @note this does not support for emulated devices
  */
 int
-HostHandler::unregisterModels ()
+HostHandler::getDspmSize (uint32_t *dspm)
 {
-  models_.clear ();
-  return 0;
-}
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
 
+  return api->getDspmSize (dspm);
+}
 /**
  * @brief Set the data layout for input/output tensors
  * @param[in] modelid The ID of model whose layouts are set
@@ -690,9 +240,7 @@ HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
   if (model == nullptr)
     return -ENOENT;
 
-  model->setDataInfo (in, out);
-
-  return 0;
+  return model->setDataInfo (in, out);
 }
 
 /**
@@ -736,8 +284,10 @@ class callbackSync {
     }
 
     void callback (output_buffers *output, uint64_t sequence) {
-      /** just copy internal variables of output buffers */
-      memcpy (output_, output, sizeof (output_buffers));
+      if (output_ != nullptr && output != nullptr) {
+        /** just copy internal variables of output buffers */
+        memcpy (output_, output, sizeof (output_buffers));
+      }
       done_ = true;
       cv_.notify_one ();
     }
@@ -759,7 +309,7 @@ class callbackSync {
  * @param[in] modelid The model to be inferred.
  * @param[in] input The input data to be inferred.
  * @param[out] output The output result.
- * @return @c 0 if no error. otherwise a negative error value
+ * @return @c positive id if no error. otherwise a negative error value
  */
 int
 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
@@ -768,7 +318,7 @@ HostHandler::runSync (uint32_t modelid, const input_buffers *input,
   callbackSync sync (output);
   int status = runAsync (modelid, input, callbackSync::callback,
       static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
-  if (status == 0) {
+  if (status > 0) {
     /** sync needs to wait callback */
     sync.wait ();
   }
@@ -783,7 +333,7 @@ HostHandler::runSync (uint32_t modelid, const input_buffers *input,
  * @param[in] cb_data The data given as a parameter to the runNPU_async call.
  * @param[in] mode Configures how this operation works.
  * @param[out] sequence The sequence number returned with runNPU_async.
- * @return @c 0 if no error. otherwise a negative error value
+ * @return @c positive id if no error. otherwise a negative error value
  */
 int
 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
@@ -797,11 +347,65 @@ HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
       return -ENOENT;
   }
 
+  /* check the given model before running */
+  if (model != nullptr && !model->finalize ()) {
+    logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
+    return -EINVAL;
+  }
+
   device_->setAsyncMode (mode);
   return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
 }
 
 /**
+ * @brief Let NPU accept input frames from its internal source continuously
+ * @param[in] modelid The model to be inferred.
+ * @param[in] opmode NPU has different opmode with auto-inputs. Choose one.
+ * @param[in] hw_dev The target device feeding input data
+ * @return @c 0 if no error. otherwise a negative error value
+ */
+int
+HostHandler::runInternal (uint32_t modelid, npu_input_opmode opmode,
+    std::string hw_dev)
+{
+  Model *model = nullptr;
+
+  if (device_->needModel()) {
+    model = getModel (modelid);
+    if (model == nullptr)
+      return -ENOENT;
+  }
+
+  /* check the given model before running */
+  if (model != nullptr && !model->finalize ()) {
+    logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
+    return -EINVAL;
+  }
+
+  return device_->runInternal (opmode, model, hw_dev);
+}
+
+/**
+ * @brief Stop the request with the given id
+ * @param[in] dev The NPU device handle
+ * @param[in] id The request id
+ * @return @c 0 if no error. otherwise a negative error value
+ */
+int
+HostHandler::stopInternal (int id)
+{
+  if (id <= 0) {
+    logerr (TAG, "Unable to stop this request with id (%d)\n", id);
+    return -EINVAL;
+  }
+
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
+
+  return api->stop_target (id);
+}
+
+/**
  * @brief get number of available devices
  * @param[in] type device type
  * @return number of devices
@@ -837,8 +441,6 @@ HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
   }
 
   *dev = device;
-  /** This is just for backward-compatility; we don't guarantee its corresness */
-  latest_dev_ = *dev;
 
   return 0;
 }
@@ -854,25 +456,38 @@ HostHandler::allocGenericBuffer (generic_buffer *buffer)
   if (buffer == NULL)
     return -EINVAL;
 
+  if (buffer->size == 0) {
+    logerr (TAG, "Invalid size\n");
+    return -EINVAL;
+  }
+
   if (buffer->size > UINT32_MAX) {
     logerr (TAG, "Don't support such a large size");
     return -ENOMEM;
   }
 
-  if (buffer->type == BUFFER_FILE) {
-    /* nothing to do */
-    if (buffer->filepath == nullptr)
+  switch (buffer->type) {
+    case BUFFER_FILE:
+      /* nothing to do */
+      if (buffer->filepath == nullptr)
+        return -EINVAL;
+      break;
+    case BUFFER_MAPPED:
+    {
+      /* now, npu-engine always provides dmabuf-based allocation */
+      void *addr = nullptr;
+      int dmabuf = device_->allocMemory (buffer->size, &addr);
+      if (dmabuf < 0)
+        return dmabuf;
+
+      buffer->dmabuf = dmabuf;
+      buffer->offset = 0;
+      buffer->addr = addr;
+    } break;
+    default:
       return -EINVAL;
-  } else {
-    /* now, npu-engine always provides dmabuf-based allocation */
-    HWmem *hwmem = device_->allocMemory ();
-    if (hwmem == nullptr || hwmem->alloc (buffer->size) < 0)
-      return -ENOMEM;
-
-    buffer->dmabuf = hwmem->getDmabuf();
-    buffer->offset = hwmem->getOffset();
-    buffer->addr = hwmem->getData();
   }
+
   return 0;
 }
 
@@ -887,488 +502,646 @@ HostHandler::deallocGenericBuffer (generic_buffer *buffer)
   if (buffer == NULL)
     return -EINVAL;
 
-  if (buffer->type != BUFFER_FILE)
-    device_->deallocMemory (buffer->dmabuf);
-
-  return 0;
-}
-
-/**
- * @brief allocate multiple generic buffers (just for users)
- * @param[out] buffers multi-buffer instance
- * @return 0 if no error. otherwise a negative errno
- */
-int
-HostHandler::allocGenericBuffer (generic_buffers *buffers)
-{
-  if (buffers == NULL || buffers->num_buffers < 1)
-    return -EINVAL;
-
-  buffer_types type = buffers->bufs[0].type;
-  if (type == BUFFER_FILE)
-    return 0;
-
-  uint64_t total_size = 0;
-  for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
-    total_size += buffers->bufs[idx].size;
-
-  uint64_t first_size = buffers->bufs[0].size;
-  buffers->bufs[0].size = total_size;
-  int status = allocGenericBuffer (&buffers->bufs[0]);
-  if (status != 0)
-    return status;
-
-  uint64_t offset = first_size;
-  for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
-    buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
-    buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
-    buffers->bufs[idx].type = type;
-
-    offset += buffers->bufs[idx].size;
+  switch (buffer->type) {
+    case BUFFER_FILE:
+      /** always true cuz nothing to do */
+      break;
+    case BUFFER_MAPPED:
+      return device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
+    default:
+      return -EINVAL;
   }
 
   return 0;
 }
 
 /**
- * @brief deallocate multiple generic buffers (just for users)
- * @param[in] buffers multi-buffer instance
- * @return 0 if no error. otherwise a negative errno
- */
-int
-HostHandler::deallocGenericBuffer (generic_buffers *buffers)
-{
-  if (buffers == NULL || buffers->num_buffers < 1)
-    return -EINVAL;
-
-  return deallocGenericBuffer (&buffers->bufs[0]);
-}
-
-/** just for backward-compatability */
-npudev_h HostHandler::latest_dev_ = nullptr;
-
-/** implementation of libnpuhost APIs */
-
-/**
- * @brief Returns the number of available NPU devices.
- * @return @c The number of NPU devices.
- * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
- * @note the caller should call putNPUdevice() to release the device handle
- */
-int getnumNPUdeviceByType (dev_type type)
-{
-  return HostHandler::getNumDevices (type);
-}
-
-/**
- * @brief Returns the handle of the chosen NPU devices.
- * @param[out] dev The NPU device handle
- * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
- * @return @c 0 if no error. otherwise a negative error value
- * @note the caller should call putNPUdevice() to release the device handle
- */
-int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
-{
-  return HostHandler::getDevice (dev, type, id);
-}
-
-/**
- * @brief Returns the handle of an NPU device meeting the condition
- * @param[out] dev The NPU device handle
- * @param[in] cond The condition for device search.
- * @return @c 0 if no error. otherwise a negative error value
- * @note the caller should call putNPUdevice() to release the device handle
- * @note it's not supported yet
- */
-int getNPUdeviceByCondition(npudev_h *dev, const npucondition *cond)
-{
-  /** not implmeneted yet */
-  return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, 0);
-}
-
-/**
- * @brief release the NPU device instance obtained by getDevice ()
- * @param[in] dev the NPU device handle
- */
-void putNPUdevice (npudev_h dev)
-{
-  if (dev != nullptr)
-    delete static_cast<Device *> (dev);
-}
-
-/**
- * @brief Send the NN model to NPU.
- * @param[in] dev The NPU device handle
- * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
- * @param[out] modelid The modelid allocated for this instance of NN model.
- * @return @c 0 if no error. otherwise a negative error value
- *
- * @detail For ASR devices, which do not accept models, but have models
- *         embedded in devices, you do not need to call register and
- *         register calls for ASR are ignored.
- *
- * @todo Add a variation: in-memory model register.
- */
-int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
-{
-  INIT_HOST_HANDLER (host_handler, dev);
-
-  return host_handler->registerModel (modelfile, modelid);
-}
-
-/**
- * @brief Remove the NN model from NPU
- * @param[in] dev The NPU device handle
- * @param[in] modelid The model to be removed from the NPU.
- * @return @c 0 if no error. otherwise a negative error value
- * @detail This may incur some latency with memory compatcion.
+ * @brief allocate multiple generic buffers (just for users)
+ * @param[out] buffers multi-buffer instance
+ * @return 0 if no error. otherwise a negative errno
  */
-int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
+int
+HostHandler::allocGenericBuffer (generic_buffers *buffers)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  uint32_t idx;
+  int status = 0;
 
-  return host_handler->unregisterModel (modelid);
-}
+  if (buffers == NULL || buffers->num_buffers < 1)
+    return -EINVAL;
 
-/**
- * @brief Remove all NN models from NPU
- * @param[in] dev The NPU device handle
- * @return @c 0 if no error. otherwise a negative error value
- */
-int unregisterNPUmodel_all(npudev_h dev)
-{
-  INIT_HOST_HANDLER (host_handler, dev);
+  for (idx = 0; idx < buffers->num_buffers; idx++) {
+    status = allocGenericBuffer (&buffers->bufs[idx]);
+    if (status != 0)
+      goto free_buffer;
+  }
+
+  return 0;
+
+free_buffer:
+  while (idx != 0) {
+    deallocGenericBuffer (&buffers->bufs[--idx]);
+  }
 
-  return host_handler->unregisterModels ();
+  return status;
 }
 
 /**
- * @brief [OPTIONAL] Set the data layout for input/output tensors
- * @param[in] dev The NPU device handle
- * @param[in] modelid The ID of model whose layouts are set
- * @param[in] info_in the layout/type info for input tensors
- * @param[in] info_out the layout/type info for output tensors
- * @return @c 0 if no error. otherwise a negative error value
- * @note if this function is not called, default layout/type will be used.
+ * @brief deallocate multiple generic buffers (just for users)
+ * @param[in] buffers multi-buffer instance
+ * @return 0 if no error. otherwise a negative errno
  */
-int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
-    tensors_data_info *info_in, tensors_data_info *info_out)
+int
+HostHandler::deallocGenericBuffer (generic_buffers *buffers)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  if (buffers == NULL || buffers->num_buffers < 1)
+    return -EINVAL;
+
+  for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
+    deallocGenericBuffer (&buffers->bufs[idx]);
+  buffers->num_buffers = 0;
 
-  return host_handler->setDataInfo (modelid, info_in, info_out);
+  return 0;
 }
 
 /**
- * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
- * @param[in] dev The NPU device handle
- * @param[in] modelid The target model id
- * @param[in] constraint inference constraint (e.g., timeout, priority)
- * @return @c 0 if no error. otherwise a negative error value
- * @note If this function is not called, default values are used.
+ * @brief get the current memory status
+ * @param[out] alloc_total The size of allocated memory until now
+ * @param[out] free_total The size of freed memory until now
+ * @return 0 if no error. otherwise a negatice error value
  */
-int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
+int
+HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  /** API is always set in initialize () */
+  const DriverAPI * api = device_->getDriverAPI ();
+  assert (api != nullptr);
 
-  return host_handler->setConstraint (modelid, constraint);
+  return api->getMemoryStatus (alloc_total, free_total);
 }
 
 /**
- * @brief Execute inference. Wait (block) until the output is available.
- * @param[in] dev The NPU device handle
- * @param[in] modelid The model to be inferred.
- * @param[in] input The input data to be inferred.
- * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
- * @return @c 0 if no error. otherwise a negative error value
- *
- * @detail This is a syntactic sugar of runNPU_async().
- *         CAUTION: There is a memcpy for the output buffer.
+ * @brief Get the current device status to be used
+ * @param[out] status the device status
+ * @param[out] num_requests the number of running requests (or pending)
+ * @return 0 if no error, otherwise a negative errno.
  */
-int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
-    output_buffers *output)
+int
+HostHandler::getDeviceStatus (npu_status *status, uint32_t *num_requests)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  /** API is always set in initialize () */
+  const DriverAPI * api = device_->getDriverAPI ();
+
+  if (!api)
+    return -EINVAL;
+
+  device_state_t state = api->isReady ();
+  if (state == device_state_t::STATE_READY) {
+    *num_requests = api->numRequests ();
+    if (*num_requests > 0)
+      *status = NPU_READY;
+    else
+      *status = NPU_IDLE;
+  } else {
+    *num_requests = 0;
+    *status = NPU_ERROR;
+  }
 
-  return host_handler->runSync (modelid, input, output);
+  return 0;
 }
 
-/**
- * @brief Invoke NPU inference. Unblocking call.
- * @param[in] dev The NPU device handle
- * @param[in] modelid The model to be inferred.
- * @param[in] input The input data to be inferred.
- * @param[in] cb The output buffer handler.
- * @param[out] sequence The sequence number returned with runNPU_async.
- * @param[in] data The data given as a parameter to the runNPU_async call.
- * @param[in] mode Configures how this operation works.
- * @return @c 0 if no error. otherwise a negative error value
- */
-int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
-    npuOutputNotify cb, uint64_t *sequence, void *data,
-    npu_async_mode mode)
-{
-  INIT_HOST_HANDLER (host_handler, dev);
+/** implement methods of Device class */
 
-  return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
+/** @brief constructor of device */
+Device::Device (dev_type type, int id, bool need_model)
+  : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
+    mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
+{
 }
 
 /**
- * @brief Allocate a buffer for NPU model with the requested buffer type.
- * @param[in] dev The NPU device handle
- * @param[in/out] Buffer the buffer pointer where memory is allocated.
- * @return 0 if no error, otherwise a negative errno.
+ * @brief create device instance depending on device type and id
+ * @param[in] type device type
+ * @param[in] id device id
+ * @return device instance
  */
-int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
+Device *
+Device::createInstance (dev_type type, int id)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  Device *device = nullptr;
+
+  switch (type & DEVICETYPE_MASK) {
+    case DEVICETYPE_TRIV2:
+      device = new TrinityVision2 (id);
+      break;
+    case DEVICETYPE_DEPR:
+      logwarn (TAG, "You're trying to open deprecated devices..\n");
+      break;
+    default:
+      break;
+  }
+
+  if (device != nullptr && device->init () != 0) {
+    delete device;
+    device = nullptr;
+  }
 
-  return host_handler->allocGenericBuffer (buffer);
+  return device;
 }
 
 /**
- * @brief Free the buffer and remove the address mapping.
- * @param[in] dev The NPU device handle
- * @param[in] buffer the model buffer
- * @return 0 if no error, otherwise a negative errno.
+ * @brief device initialization
+ * @return 0 if no error, otherwise a negative errno
+ * @note Init failures come from createDriverAPI() only.
  */
-int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
+int
+Device::init ()
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  /** should be initilizaed only once */
+  if (!atomic_flag_.test_and_set()) {
+    /** create the corresponding driver API */
+    api_ = DriverAPI::createDriverAPI (type_, id_);
+    if (api_.get() == nullptr) {
+      atomic_flag_.clear();
+      logerr (TAG, "Failed to create driver API\n");
+      return -EINVAL;
+    }
+
+    handler_.reset (new HostHandler (this));
+    scheduler_.reset (new Scheduler (api_.get()));
+    mem_ = MemAllocator::createInstance (api_.get());
+
+    initialized_ = true;  /** c++11 does not provide test() of atomic flag */
+  }
 
-  return host_handler->deallocGenericBuffer (buffer);
+  return 0;
 }
 
 /**
- * @brief Allocate a buffer for NPU input with the requested buffer type.
- * @param[in] dev The NPU device handle
- * @param[in/out] Buffer the buffer pointer where memory is allocated.
- * @return 0 if no error, otherwise a negative errno.
- * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
- *       calls of allocInputBuffer() don't gurantee contiguous allocations between them.
+ * @brief stop all requests from this device
+ * @param[in] force_stop indicate the schedduler waits until to handle previous requests
+ * @return 0 if no error, otherwise a negative errno
  */
-int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
+int
+Device::stop (bool force_stop)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
 
-  return host_handler->allocGenericBuffer (buffer);
+  Request *req = new Request (NPUINPUT_STOP);
+  req->setForceStop (force_stop);
+  return scheduler_->submitRequest (req);
 }
 
 /**
- * @brief Free the buffer and remove the address mapping.
- * @param[in] dev The NPU device handle
- * @param[in] buffer the input buffer
- * @return 0 if no error, otherwise a negative errno.
+ * @brief allocate generic memory buffer
+ * @param[in] size the size to allocate
+ * @param[out] addr the mapped address
+ * @return dmabuf fd if no error, otherwise a negative errno
  */
-int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
+int
+Device::allocMemory (size_t size, void **addr)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
+
+  if (size == 0 || addr == nullptr) {
+    logerr (TAG, "Invalid arguments\n");
+    return -EINVAL;
+  }
 
-  return host_handler->deallocGenericBuffer (buffer);
+  return mem_->allocMemory (size, addr);
 }
 
 /**
- * @brief Allocate input buffers, which have multiple instances of generic_buffer
- * @param[in] dev The NPU device handle
- * @param[in/out] input input buffers.
- * @return 0 if no error, otherwise a negative errno.
- * @note it reuses allocInputBuffer().
- * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
- *          memory mapping for multiple tensors (in a single inference, not batch size).
+ * @brief deallocate generic memory buffer
+ * @param[in] dmabuf_fd dmabuf file descriptor
+ * @param[in] size buffer size
+ * @param[in] addr mapped addr
+ * @return 0 if no error, otherwise a negative errno
  */
-int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
+int
+Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
+
+  if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
+    logerr (TAG, "Invalid arguments\n");
+    return -EINVAL;
+  }
 
-  return host_handler->allocGenericBuffer (input);
+  return mem_->deallocMemory (dmabuf_fd, size, addr);
 }
 
 /**
- * @brief Free input buffers allocated by allocInputBuffers().
- * @param[in] dev The NPU device handle
- * @param[in/out] input input buffers.
- * @note it reuses cleanInputbuffer().
- * @return 0 if no error, otherwise a negative errno.
+ * @brief extract the segment table instance from input generic buffers
+ * @param[in] model the model instance
+ * @param[in] input the input generic buffers
+ * @param[in] output the output generic buffers
+ * @return the segment table instance
  */
-int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
+SegmentTable *
+TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input,
+    const output_buffers *output)
 {
-  INIT_HOST_HANDLER (host_handler, dev);
+  const Metadata *meta = model->getMetadata ();
+  if (meta == nullptr || (input != nullptr &&
+        meta->getInputNum() != input->num_buffers)) {
+    logerr (TAG, "Invalid metadata info provided\n");
+    return nullptr;
+  }
+
+  SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
+  int status = segt->alloc ();
+  if (status != 0) {
+    logerr (TAG, "Failed to allocate segment table: %d\n", status);
+    goto delete_segt;
+  }
+
+  status = segt->createSegments (model, input, output);
+  if (status != 0) {
+    logerr (TAG, "Failed to create segments: %d\n", status);
+    goto delete_segt;
+  }
 
-  return host_handler->deallocGenericBuffer (input);
+  return segt;
+
+delete_segt:
+  delete segt;
+  return nullptr;
 }
 
 /**
- * @brief Get metadata for NPU model
- * @param[in] model The path of model binary file
- * @param[in] need_extra whether you want to extract the extra data in metadata
- * @return the metadata structure to be filled if no error, otherwise nullptr
- *
- * @note For most npu-engine users, the extra data is not useful because it will be
- *       used for second-party users (e.g., compiler, simulator).
- *       Also, the caller needs to free the metadata.
- *
- * @note the caller needs to free the metadata
+ * @brief implementation of TRIV2's setModel ()
+ * @param[in] model_buf the model generic buffer
+ * @param[out] model the model instance
+ * @return 0 if no error, otherwise a negative errno
  */
-npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
+int
+TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
 {
-  npubin_meta *meta;
-  FILE *fp;
-  size_t ret;
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
 
-  if (!model)
-    return nullptr;
+  if (model_buf == nullptr || model_ptr == nullptr)
+    return -EINVAL;
 
-  fp = fopen (model, "rb");
-  if (!fp) {
-    logerr (TAG, "Failed to open the model binary: %d\n", -errno);
-    return nullptr;
-  }
+  Model *model;
+  int status;
 
-  meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
-  if (!meta) {
-    logerr (TAG, "Failed to allocate metadata\n");
-    goto exit_err;
-  }
+  switch (model_buf->type) {
+  case BUFFER_FILE:
+  case BUFFER_MAPPED:
+    model = mem_->allocModel (new HWmemDevice);
+    if (model == nullptr) {
+      logerr (TAG, "Failed to allocate model\n");
+      return -ENOMEM;
+    }
 
-  ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
-  if (ret != NPUBIN_META_SIZE) {
-    logerr (TAG, "Failed to read the metadata\n");
-    goto exit_free;
-  }
+    status = model->alloc (NPUBIN_META_SIZE);
+    if (status != 0) {
+      logerr (TAG, "Failed to allocate model: %d\n", status);
+      goto delete_exit;
+    }
 
-  if (!CHECK_NPUBIN (meta->magiccode)) {
-    logerr (TAG, "Invalid metadata provided\n");
-    goto exit_free;
+    status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
+        0, NPUBIN_META_SIZE);
+    if (status != 0) {
+      logerr (TAG, "Failed to extract generic buffer: %d\n", status);
+      goto delete_exit;
+    }
+    break;
+  default:
+    return -EINVAL;
   }
 
-  if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
-    npubin_meta *new_meta;
+  status = model->setMetadata (model->getData());
+  if (status != 0)
+    goto delete_exit;
+
+  /** allocate program (optional; NOP) */
+  if (model->getMetadata()->getProgramSize() > 0) {
+    HWmem * hwmem_prog = new HWmem (new HWmemDevice);
+    hwmem_prog->setDriverAPI (api_.get());
+    hwmem_prog->setContiguous (true);
+
+    model->setProgramData (hwmem_prog);
+
+    status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
+    if (status != 0) {
+      logerr (TAG, "Failed to allocate program\n");
+      goto delete_exit;
+    }
 
-    new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
-    if (!new_meta) {
-      logerr (TAG, "Failed to allocate extra metadata\n");
-      goto exit_free;
+    status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
+        model->getMetadata()->getMetaSize(),
+        model->getMetadata()->getProgramSize());
+    if (status != 0) {
+      logerr (TAG, "Failed to extract generic buffer: %d\n", status);
+      goto delete_exit;
     }
 
-    ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
-    if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
-      logerr (TAG, "Invalid extra metadata provided\n");
-      free (new_meta);
-      goto exit_err;
+    /** register this model to the driver */
+    model_config_t config;
+    config.version = model->getMetadata()->getVersion ();
+    config.dbuf_fd = hwmem_prog->getDmabuf ();
+    config.program_size = hwmem_prog->getSize ();
+    config.program_offset_addr = 0;
+    config.metadata_dbuf_fd = model->getDmabuf ();
+
+    /** for metadata extended section */
+    size_t extended_size = model->getMetadata()->getMetaExtendedSize();
+    if (extended_size > 0) {
+      HWmem * hwmem_extended = new HWmem (new HWmemDevice);
+      hwmem_extended->setDriverAPI (api_.get ());
+
+      model->setExtendedMetadata (hwmem_extended);
+
+      status = hwmem_extended->alloc (extended_size);
+      if (status != 0) {
+        logerr (TAG, "Failed to allocate extended metadata: %d\n", status);
+        goto delete_exit;
+      }
+
+      config.metadata_ext_dbuf_fd = hwmem_extended->getDmabuf ();
+      config.metadata_ext_size = extended_size;
+
+      status = comm_.extractGenericBuffer (model_buf, hwmem_extended->getData (),
+          nullptr, NPUBIN_META_SIZE, extended_size);
+      if (status != 0) {
+        logerr (TAG, "Failed to extract generic buffer: %d\n", status);
+        goto delete_exit;
+      }
+    } else {
+      config.metadata_ext_dbuf_fd = -1;
+      config.metadata_ext_size = 0;
     }
 
-    meta = new_meta;
+    status = api_->registerModel (&config, model->getMetadata()->getNPUVersion());
+    if (status != 0)
+      goto delete_exit;
+
+    model->setInternalID(config.id);
   }
 
-  fclose (fp);
+  /** allocate weight (optional) */
+  if (model->getMetadata()->getWeightSize() > 0) {
+    HWmem * hwmem_weight = new HWmem (new HWmemDevice);
+    hwmem_weight->setDriverAPI (api_.get());
 
-  return meta;
+    model->setWeightData (hwmem_weight);
 
-exit_free:
-  free (meta);
-exit_err:
-  fclose (fp);
+    status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
+    if (status != 0) {
+      logerr (TAG, "Failed to allocate program\n");
+      goto delete_exit;
+    }
 
-  return nullptr;
-}
+    status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
+        model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
+        model->getMetadata()->getWeightSize());
+    if (status != 0) {
+      logerr (TAG, "Failed to extract generic buffer: %d\n", status);
+      goto delete_exit;
+    }
+  }
 
-/** deprecated buffer APIs; please use the above APIs */
+  *model_ptr = model;
+  return status;
 
-/**
- * @brief Returns the number of NPU devices (TRIV).
- */
-int getnumNPUdevice (void)
-{
-  logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
-  return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
+delete_exit:
+  delete model;
+  return status;
 }
 
 /**
- * @brief Returns the list of ASR devices (TRIA)
+ * @brief implementation of TRIV2's unsetModel ()
+ * @param[in] model the model instance
+ * @return 0 if no error, otherwise a negative errno
  */
-int getnumASRdevice (void)
+int
+TrinityVision2::unsetModel (Model * model)
 {
-  logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
-  return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
-}
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
 
-/**
- * @brief Returns the handle of the chosen TRIV device.
- */
-int getNPUdevice (npudev_h *dev, uint32_t id)
-{
-  logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
-  return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
-}
+  if (model == nullptr) {
+    logerr (TAG, "Invalid model instance\n");
+    return -EINVAL;
+  }
 
-/**
- * @brief Returns the handle of the chosen TRIA device.
- */
-int getASRdevice (npudev_h *dev, uint32_t id)
-{
-  logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
-  return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
-}
+  if (model->getMetadata()->getProgramSize() > 0)
+    return api_->deregisterModel (model->getInternalID ());
 
-/** @brief deprecated */
-int allocModelBuffer (generic_buffer *buffer)
-{
-  logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
-  return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
+  return 0;
 }
 
-/** @brief deprecated */
-int cleanModelBuffer (generic_buffer *buffer)
+/** @brief implementation of TRIV2's run() */
+int
+TrinityVision2::run (npu_input_opmode opmode, const Model *model,
+    const input_buffers *input, npuOutputNotify cb, void *cb_data,
+    uint64_t *sequence)
 {
-  logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
-  return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
-}
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
 
-/** @brief deprecated */
-int allocInputBuffer (generic_buffer *buffer)
-{
-  logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
-  return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
-}
+  if (opmode != NPUINPUT_HOST)
+    return -EINVAL;
 
-/** @brief deprecated */
-int cleanInputBuffer (generic_buffer *buffer)
-{
-  logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
-  return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
+  if (input == nullptr || input->num_buffers == 0 || model == nullptr)
+    return -EINVAL;
+
+  const_cast<Model *>(model)->updateDataInfo ();
+
+  /** this device uses segment table */
+  SegmentTable * segt = prepareSegmentTable (model, input);
+  if (segt == nullptr) {
+    logerr (TAG, "Failed to create segment table instance\n");
+    return -EINVAL;
+  }
+
+  /** extract input data */
+  for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
+    if (!segt->getInputSegment(idx)->isExternal ()) {
+      uint32_t seg_offset = segt->getInputSegmentOffset(idx);
+      auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
+          std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
+      int status = comm_.extractGenericBuffer (
+          &input->bufs[idx],
+          segt->getInputSegment(idx)->getData() + seg_offset,
+          func);
+      if (status != 0) {
+        logerr (TAG, "Failed to feed input segment: %d\n", status);
+        return status;
+      }
+    }
+  }
+
+  Request *req = new Request (opmode);
+  req->setModel (model);
+  req->setInferData (segt);
+  req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
+
+  if (sequence && req->getID () > 0) {
+    *sequence = (uint32_t) req->getID ();
+  }
+
+  return scheduler_->submitRequest (req);
 }
 
-/** @brief deprecated */
-int allocInputBuffers (input_buffers * input)
+/** @brief implementation of TRIV2's runInternal() */
+int
+TrinityVision2::runInternal (npu_input_opmode opmode, const Model *model,
+    std::string hw_dev)
 {
-  logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
-  return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
+  if (!initialized ()) {
+    logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
+    return -EPERM;
+  }
+
+  if (opmode != NPUINPUT_HW_RECURRING)
+    return -EINVAL;
+
+  /** this device uses segment table */
+  SegmentTable * segt = prepareSegmentTable (model, nullptr, nullptr);
+  if (segt == nullptr) {
+    logerr (TAG, "Failed to create segment table instance\n");
+    return -EINVAL;
+  }
+
+  Request *req = new Request (opmode);
+  req->setModel (model);
+  req->setInferData (segt);
+  req->setHwDevice (hw_dev);
+
+  return scheduler_->submitRequest (req);
 }
 
-/** @brief deprecated */
-int cleanInputBuffers (input_buffers * input)
+/** @brief callback of TRIV2 request */
+void
+TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
 {
-  logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
-  return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
+  if (cb == nullptr)
+    return;
+
+  const Model *model = req->getModel ();
+  SegmentTable *segt = dynamic_cast<SegmentTable *> (req->getInferData ());
+  /** internal logic error */
+  assert (segt != nullptr);
+
+  output_buffers output = {
+    .num_buffers = segt->getNumOutputSegments ()
+  };
+
+  for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
+    uint32_t output_tensor_size = model->getOutputTensorSize (idx);
+
+    output.bufs[idx].type = BUFFER_MAPPED;
+    output.bufs[idx].size = output_tensor_size;
+    /** user needs to free this */
+    output.bufs[idx].addr = calloc (1, output_tensor_size);
+
+#if defined(ENABLE_FPGA_WORKAROUND)
+    api_->fpga_memcpy (
+        segt->getOutputSegment(idx)->getDmabuf(),
+        segt->getOutputSegmentOffset(idx),
+        output.bufs[idx].addr,
+        output.bufs[idx].size);
+#else
+    auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
+        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
+    int status = comm_.insertGenericBuffer (
+        segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
+        &output.bufs[idx], func);
+
+    if (status != 0) {
+      logerr (TAG, "Failed to return output buffer: %d\n", status);
+    }
+#endif
+  }
+
+  cb (&output, req->getID(), cb_data);
+
+  delete segt;
 }
 
-/** @brief deprecated */
-int allocNPUBuffer (uint64_t size, buffer_types type,
-    const char * filepath, generic_buffer *buffer)
+/** Implement data manipulation (each device may have different impl.) */
+
+#ifdef ENABLE_MANIP
+/**
+ * @brief perform data manipulation
+ * @param[in] model model instance
+ * @param[in] idx tensor index
+ * @param[in] is_input indicate it's input manipulation
+ * @param[out] dst destination buffer
+ * @param[in] src source buffer (feature map)
+ * @param[in] size size to be copied
+ * @return size of memory copy if no error, otherwise zero
+ *
+ * @note the input data format should be NHWC
+ *
+ * @detail Feature map data in TRIV2, (x, y, z) = (width, height, depth)
+ *
+ *         1) Image input (depth == 1 or depth == 3)
+ *            Addr(x,y,z) = Addr(0,0,0) + z + depth * x + ymod * y
+ *
+ *         2) Common cases
+ *            Addr(x,y,z) = Addr(0,0,0) + (z % 64) + (64 * x) + ymod * y + zmod * (z / 64)
+ */
+size_t
+TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
+    void *dst, void *src, size_t size)
 {
-  if (buffer) {
-    buffer->size = size;
-    buffer->type = type;
-    buffer->filepath = filepath;
+  const Metadata *meta = model->getMetadata ();
+  DataConverter converter (is_input);
+
+  converter.setData (src, dst, size);
+  converter.setTops (meta->getTops ());
+  if (is_input) {
+    const tensor_data_info* info = model->getInputDataInfo (idx);
+    if (info == nullptr)
+      return 0;
+
+    converter.setDataLayout (info->layout, DATA_LAYOUT_TRIV2);
+    converter.setDataType (info->type, meta->getInputQuantType (idx));
+    converter.setDataDims (meta->getInputDims (idx));
+    converter.setQuantZero (meta->getInputQuantZero (idx));
+    converter.setQuantScale (meta->getInputQuantScale (idx));
+  } else {
+    const tensor_data_info* info = model->getOutputDataInfo (idx);
+    if (info == nullptr)
+      return 0;
+
+    converter.setDataLayout (DATA_LAYOUT_TRIV2, info->layout);
+    converter.setDataType (meta->getOutputQuantType (idx), info->type);
+    converter.setDataDims (meta->getOutputDims (idx));
+    converter.setQuantZero (meta->getOutputQuantZero (idx));
+    converter.setQuantScale (meta->getOutputQuantScale (idx));
   }
 
-  logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
-  return allocModelBuffer (buffer);
+  return converter.perform ();
 }
 
-/** @brief deprecated */
-int cleanNPUBuffer (generic_buffer * buffer)
+#else
+
+size_t
+TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
+    void *dst, void *src, size_t size)
 {
-  logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
-  return cleanModelBuffer (buffer);
+  memcpy (dst, src, size);
+  return size;
 }
+
+#endif