[HWmemExternal] Support external hwmem (dmabuf)
[platform/adaptation/npu/trix-engine.git] / src / core / ne-handler.cc
1 /**
2  * Proprietary
3  * Copyright (C) 2020 Samsung Electronics
4  * Copyright (C) 2020 Dongju Chae <dongju.chae@samsung.com>
5  */
6 /**
7  * @file ne-host-handler.cc
8  * @date 03 Apr 2020
9  * @brief Implementation of APIs to access NPU from Host
10  * @see https://code.sec.samsung.net/confluence/display/ODLC/2020+Overall+Software+Stack
11  * @author Dongju Chae <dongju.chae@samsung.com>
12  * @bug No known bugs except for NYI items
13  */
14
15 #include "ne-handler.h"
16
17 #include <libnpuhost.h>
18 #include <npubinfmt.h>
19 #include <NPUdrvAPI.h>
20 #include <CommPlugin.h>
21
22 #include <string.h>
23 #include <assert.h>
24
25 #include <condition_variable>
26 #include <functional>
27 #include <atomic>
28 #include <map>
29
30 #define TAG _N2
31
32 #define INIT_HOST_HANDLER(handler, dev) \
33   Device *tdev = static_cast <Device *> (dev); \
34   if (tdev == nullptr) return -EINVAL; \
35   HostHandler *handler = tdev->getHostHandler (); \
36   if (handler == nullptr) return -EINVAL;
37
38 /** just for backward-compatability */
39 npudev_h HostHandler::latest_dev_ = nullptr;
40
41 /** implement libnpuhost APIs */
42
43 /**
44  * @brief Returns the number of available NPU devices.
45  * @return @c The number of NPU devices.
46  * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
47  * @note the caller should call putNPUdevice() to release the device handle
48  */
49 int getnumNPUdeviceByType (dev_type type)
50 {
51   return HostHandler::getNumDevices (type);
52 }
53
54 /**
55  * @brief Returns the handle of the chosen NPU devices.
56  * @param[out] dev The NPU device handle
57  * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
58  * @return @c 0 if no error. otherwise a negative error value
59  * @note the caller should call putNPUdevice() to release the device handle
60  */
61 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
62 {
63   return HostHandler::getDevice (dev, type, id);
64 }
65
66 /**
67  * @brief Returns the handle of an NPU device meeting the condition
68  * @param[out] dev The NPU device handle
69  * @param[in] cond The condition for device search.
70  * @return @c 0 if no error. otherwise a negative error value
71  * @note the caller should call putNPUdevice() to release the device handle
72  * @note it's not supported yet
73  */
74 int getNPUdeviceByCondition(npudev_h *dev, const npucondition *cond)
75 {
76   /** not implmeneted yet */
77   return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, 0);
78 }
79
80 /**
81  * @brief release the NPU device instance obtained by getDevice ()
82  * @param[in] dev the NPU device handle
83  */
84 void putNPUdevice (npudev_h dev)
85 {
86   if (dev != nullptr)
87     delete static_cast<Device *> (dev);
88 }
89
90 /**
91  * @brief Send the NN model to NPU.
92  * @param[in] dev The NPU device handle
93  * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
94  * @param[out] modelid The modelid allocated for this instance of NN model.
95  * @return @c 0 if no error. otherwise a negative error value
96  *
97  * @detail For ASR devices, which do not accept models, but have models
98  *         embedded in devices, you do not need to call register and
99  *         register calls for ASR are ignored.
100  *
101  * @todo Add a variation: in-memory model register.
102  */
103 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
104 {
105   INIT_HOST_HANDLER (host_handler, dev);
106
107   return host_handler->registerModel (modelfile, modelid);
108 }
109
110 /**
111  * @brief Remove the NN model from NPU
112  * @param[in] dev The NPU device handle
113  * @param[in] modelid The model to be removed from the NPU.
114  * @return @c 0 if no error. otherwise a negative error value
115  * @detail This may incur some latency with memory compatcion.
116  */
117 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
118 {
119   INIT_HOST_HANDLER (host_handler, dev);
120
121   return host_handler->unregisterModel (modelid);
122 }
123
124 /**
125  * @brief Remove all NN models from NPU
126  * @param[in] dev The NPU device handle
127  * @return @c 0 if no error. otherwise a negative error value
128  */
129 int unregisterNPUmodel_all(npudev_h dev)
130 {
131   INIT_HOST_HANDLER (host_handler, dev);
132
133   return host_handler->unregisterModels ();
134 }
135
136 /**
137  * @brief [OPTIONAL] Set the data layout for input/output tensors
138  * @param[in] dev The NPU device handle
139  * @param[in] modelid The ID of model whose layouts are set
140  * @param[in] info_in the layout/type info for input tensors
141  * @param[in] info_out the layout/type info for output tensors
142  * @return @c 0 if no error. otherwise a negative error value
143  * @note if this function is not called, default layout/type will be used.
144  */
145 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
146     tensors_data_info *info_in, tensors_data_info *info_out)
147 {
148   INIT_HOST_HANDLER (host_handler, dev);
149
150   return host_handler->setDataInfo (modelid, info_in, info_out);
151 }
152
153 /**
154  * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
155  * @param[in] dev The NPU device handle
156  * @param[in] modelid The target model id
157  * @param[in] constraint inference constraint (e.g., timeout, priority)
158  * @return @c 0 if no error. otherwise a negative error value
159  * @note If this function is not called, default values are used.
160  */
161 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
162 {
163   INIT_HOST_HANDLER (host_handler, dev);
164
165   return host_handler->setConstraint (modelid, constraint);
166 }
167
168 /**
169  * @brief Execute inference. Wait (block) until the output is available.
170  * @param[in] dev The NPU device handle
171  * @param[in] modelid The model to be inferred.
172  * @param[in] input The input data to be inferred.
173  * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
174  * @return @c 0 if no error. otherwise a negative error value
175  *
176  * @detail This is a syntactic sugar of runNPU_async().
177  *         CAUTION: There is a memcpy for the output buffer.
178  */
179 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
180     output_buffers *output)
181 {
182   INIT_HOST_HANDLER (host_handler, dev);
183
184   return host_handler->runSync (modelid, input, output);
185 }
186
187 /**
188  * @brief Invoke NPU inference. Unblocking call.
189  * @param[in] dev The NPU device handle
190  * @param[in] modelid The model to be inferred.
191  * @param[in] input The input data to be inferred.
192  * @param[in] cb The output buffer handler.
193  * @param[out] sequence The sequence number returned with runNPU_async.
194  * @param[in] data The data given as a parameter to the runNPU_async call.
195  * @param[in] mode Configures how this operation works.
196  * @return @c 0 if no error. otherwise a negative error value
197  */
198 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
199     npuOutputNotify cb, uint64_t *sequence, void *data,
200     npu_async_mode mode)
201 {
202   INIT_HOST_HANDLER (host_handler, dev);
203
204   return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
205 }
206
207 /**
208  * @brief Allocate a buffer for NPU model with the requested buffer type.
209  * @param[in] dev The NPU device handle
210  * @param[in/out] Buffer the buffer pointer where memory is allocated.
211  * @return 0 if no error, otherwise a negative errno.
212  */
213 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
214 {
215   INIT_HOST_HANDLER (host_handler, dev);
216
217   return host_handler->allocGenericBuffer (buffer);
218 }
219
220 /**
221  * @brief Free the buffer and remove the address mapping.
222  * @param[in] dev The NPU device handle
223  * @param[in] buffer the model buffer
224  * @return 0 if no error, otherwise a negative errno.
225  */
226 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
227 {
228   INIT_HOST_HANDLER (host_handler, dev);
229
230   return host_handler->deallocGenericBuffer (buffer);
231 }
232
233 /**
234  * @brief Allocate a buffer for NPU input with the requested buffer type.
235  * @param[in] dev The NPU device handle
236  * @param[in/out] Buffer the buffer pointer where memory is allocated.
237  * @return 0 if no error, otherwise a negative errno.
238  * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
239  *       calls of allocInputBuffer() don't gurantee contiguous allocations between them.
240  */
241 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
242 {
243   INIT_HOST_HANDLER (host_handler, dev);
244
245   return host_handler->allocGenericBuffer (buffer);
246 }
247
248 /**
249  * @brief Free the buffer and remove the address mapping.
250  * @param[in] dev The NPU device handle
251  * @param[in] buffer the input buffer
252  * @return 0 if no error, otherwise a negative errno.
253  */
254 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
255 {
256   INIT_HOST_HANDLER (host_handler, dev);
257
258   return host_handler->deallocGenericBuffer (buffer);
259 }
260
261 /**
262  * @brief Allocate input buffers, which have multiple instances of generic_buffer
263  * @param[in] dev The NPU device handle
264  * @param[in/out] input input buffers.
265  * @return 0 if no error, otherwise a negative errno.
266  * @note it reuses allocInputBuffer().
267  * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
268  *          memory mapping for multiple tensors (in a single inference, not batch size).
269  */
270 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
271 {
272   INIT_HOST_HANDLER (host_handler, dev);
273
274   return host_handler->allocGenericBuffer (input);
275 }
276
277 /**
278  * @brief Free input buffers allocated by allocInputBuffers().
279  * @param[in] dev The NPU device handle
280  * @param[in/out] input input buffers.
281  * @note it reuses cleanInputbuffer().
282  * @return 0 if no error, otherwise a negative errno.
283  */
284 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
285 {
286   INIT_HOST_HANDLER (host_handler, dev);
287
288   return host_handler->deallocGenericBuffer (input);
289 }
290
291 /**
292  * @brief get the current memory status for the given device
293  * @param[in] dev The NPU device handle
294  * @param[out] alloc_total The size of allocated memory until now
295  * @param[out] free_total The size of freed memory until now
296  * @return @c 0 if no error. otherwise a negatice error value
297  */
298 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
299 {
300   INIT_HOST_HANDLER (host_handler, dev);
301
302   return host_handler->getMemoryStatus (alloc_total, free_total);
303 }
304
305 /**
306  * @brief Get metadata for NPU model
307  * @param[in] model The path of model binary file
308  * @param[in] need_extra whether you want to extract the extra data in metadata
309  * @return the metadata structure to be filled if no error, otherwise nullptr
310  *
311  * @note For most npu-engine users, the extra data is not useful because it will be
312  *       used for second-party users (e.g., compiler, simulator).
313  *       Also, the caller needs to free the metadata.
314  *
315  * @note the caller needs to free the metadata
316  */
317 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
318 {
319   npubin_meta *meta;
320   FILE *fp;
321   size_t ret;
322
323   if (!model)
324     return nullptr;
325
326   fp = fopen (model, "rb");
327   if (!fp) {
328     logerr (TAG, "Failed to open the model binary: %d\n", -errno);
329     return nullptr;
330   }
331
332   meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
333   if (!meta) {
334     logerr (TAG, "Failed to allocate metadata\n");
335     goto exit_err;
336   }
337
338   ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
339   if (ret != NPUBIN_META_SIZE) {
340     logerr (TAG, "Failed to read the metadata\n");
341     goto exit_free;
342   }
343
344   if (!CHECK_NPUBIN (meta->magiccode)) {
345     logerr (TAG, "Invalid metadata provided\n");
346     goto exit_free;
347   }
348
349   if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
350     npubin_meta *new_meta;
351
352     new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
353     if (!new_meta) {
354       logerr (TAG, "Failed to allocate extra metadata\n");
355       goto exit_free;
356     }
357
358     ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
359     if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
360       logerr (TAG, "Invalid extra metadata provided\n");
361       free (new_meta);
362       goto exit_err;
363     }
364
365     meta = new_meta;
366   }
367
368   fclose (fp);
369
370   return meta;
371
372 exit_free:
373   free (meta);
374 exit_err:
375   fclose (fp);
376
377   return nullptr;
378 }
379
380 /** deprecated buffer APIs; please use the above APIs */
381
382 /**
383  * @brief Returns the number of NPU devices (TRIV).
384  */
385 int getnumNPUdevice (void)
386 {
387   logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
388   return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
389 }
390
391 /**
392  * @brief Returns the list of ASR devices (TRIA)
393  */
394 int getnumASRdevice (void)
395 {
396   logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
397   return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
398 }
399
400 /**
401  * @brief Returns the handle of the chosen TRIV device.
402  */
403 int getNPUdevice (npudev_h *dev, uint32_t id)
404 {
405   logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
406   return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
407 }
408
409 /**
410  * @brief Returns the handle of the chosen TRIA device.
411  */
412 int getASRdevice (npudev_h *dev, uint32_t id)
413 {
414   logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
415   return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
416 }
417
418 /** @brief deprecated */
419 int allocModelBuffer (generic_buffer *buffer)
420 {
421   logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
422   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
423 }
424
425 /** @brief deprecated */
426 int cleanModelBuffer (generic_buffer *buffer)
427 {
428   logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
429   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
430 }
431
432 /** @brief deprecated */
433 int allocInputBuffer (generic_buffer *buffer)
434 {
435   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
436   return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
437 }
438
439 /** @brief deprecated */
440 int cleanInputBuffer (generic_buffer *buffer)
441 {
442   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
443   return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
444 }
445
446 /** @brief deprecated */
447 int allocInputBuffers (input_buffers * input)
448 {
449   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
450   return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
451 }
452
453 /** @brief deprecated */
454 int cleanInputBuffers (input_buffers * input)
455 {
456   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
457   return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
458 }
459
460 /** @brief deprecated */
461 int allocNPUBuffer (uint64_t size, buffer_types type,
462     const char * filepath, generic_buffer *buffer)
463 {
464   if (buffer) {
465     buffer->size = size;
466     buffer->type = type;
467     buffer->filepath = filepath;
468   }
469
470   logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
471   return allocModelBuffer (buffer);
472 }
473
474 /** @brief deprecated */
475 int cleanNPUBuffer (generic_buffer * buffer)
476 {
477   logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
478   return cleanModelBuffer (buffer);
479 }
480
481 /** implement methods of HostHandler class */
482
483 /** @brief host handler constructor */
484 HostHandler::HostHandler (Device *device)
485   : device_(device),
486     /* ignored as we don't use double buffering anymore, but for backward-compatibility */
487     async_mode_ (NPUASYNC_WAIT)
488 {
489 }
490
491 /** @brief host handler destructor */
492 HostHandler::~HostHandler ()
493 {
494 }
495
496 /**
497  * @brief register model from generic buffer
498  * @param[in] model_buf model buffer
499  * @param[out] modelid model id
500  * @return 0 if no error. otherwise a negative errno
501  */
502 int
503 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
504 {
505   if (model_buf == nullptr || modelid == nullptr) {
506     logerr (TAG, "Invalid arguments given\n");
507     return -EINVAL;
508   }
509
510   Model *model = nullptr;
511   int status = device_->setModel (model_buf, &model);
512   if (status != 0) {
513     logerr (TAG, "Failed to set model: %d\n", status);
514     return status;
515   }
516
517   assert (model != nullptr);
518
519   status = models_.insert (model->getID(), model);
520   if (status != 0) {
521     logerr (TAG, "Failed to insert model id\n");
522     delete model;
523     return status;
524   }
525
526   *modelid = model->getID();
527   return 0;
528 }
529
530 /**
531  * @brief remove the registered model
532  * @param[in] modelid model id
533  * @return 0 if no error. otherwise a negative errno
534  */
535 int
536 HostHandler::unregisterModel (uint32_t modelid)
537 {
538   return models_.remove (modelid);
539 }
540
541 /**
542  * @brief remove all registered models
543  * @return 0
544  */
545 int
546 HostHandler::unregisterModels ()
547 {
548   models_.clear ();
549   return 0;
550 }
551
552 /**
553  * @brief Set the data layout for input/output tensors
554  * @param[in] modelid The ID of model whose layouts are set
555  * @param[in] in the layout/type info for input tensors
556  * @param[in] out the layout/type info for output tensors
557  * @return @c 0 if no error. otherwise a negative error value
558  * @note if this function is not called, default layout/type will be used.
559  */
560 int
561 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
562     tensors_data_info *out)
563 {
564   Model *model = models_.find (modelid);
565   if (model == nullptr)
566     return -ENOENT;
567
568   return model->setDataInfo (in, out);
569 }
570
571 /**
572  * @brief Set the inference constraint for next NPU inferences
573  * @param[in] modelid The target model id
574  * @param[in] constraint inference constraint (e.g., timeout, priority)
575  * @return @c 0 if no error. otherwise a negative error value
576  * @note If this function is not called, default values are used.
577  */
578 int
579 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
580 {
581   Model *model = models_.find (modelid);
582   if (model == nullptr)
583     return -ENOENT;
584
585   model->setConstraint (constraint);
586
587   return 0;
588 }
589
590 /**
591  * @brief find and return model instance
592  * @param[in] modelid model id
593  * @return model instance if found. otherwise nullptr
594  */
595 Model *
596 HostHandler::getModel (uint32_t modelid)
597 {
598   return models_.find (modelid);
599 }
600
601 /** @brief dummay callback for runSync. */
602 class callbackSync {
603   public:
604     callbackSync (output_buffers *output) : output_(output), done_(false) {}
605
606     static void callback (output_buffers *output, uint64_t sequence, void *data) {
607       callbackSync *sync = static_cast<callbackSync *>(data);
608       sync->callback (output, sequence);
609     }
610
611     void callback (output_buffers *output, uint64_t sequence) {
612       if (output_ != nullptr) {
613         /** just copy internal variables of output buffers */
614         memcpy (output_, output, sizeof (output_buffers));
615       }
616       done_ = true;
617       cv_.notify_one ();
618     }
619
620     void wait () {
621       std::unique_lock<std::mutex> lock (m_);
622       cv_.wait (lock, [this]() { return done_; });
623     }
624
625   private:
626     std::mutex m_;
627     std::condition_variable cv_;
628     output_buffers *output_;
629     bool done_;
630 };
631
632 /**
633  * @brief Execute inference. Wait (block) until the output is available.
634  * @param[in] modelid The model to be inferred.
635  * @param[in] input The input data to be inferred.
636  * @param[out] output The output result.
637  * @return @c 0 if no error. otherwise a negative error value
638  */
639 int
640 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
641     output_buffers *output)
642 {
643   callbackSync sync (output);
644   int status = runAsync (modelid, input, callbackSync::callback,
645       static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
646   if (status == 0) {
647     /** sync needs to wait callback */
648     sync.wait ();
649   }
650   return status;
651 }
652
653 /**
654  * @brief Invoke NPU inference. Unblocking call.
655  * @param[in] modelid The model to be inferred.
656  * @param[in] input The input data to be inferred.
657  * @param[in] cb The output buffer handler.
658  * @param[in] cb_data The data given as a parameter to the runNPU_async call.
659  * @param[in] mode Configures how this operation works.
660  * @param[out] sequence The sequence number returned with runNPU_async.
661  * @return @c 0 if no error. otherwise a negative error value
662  */
663 int
664 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
665     npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
666 {
667   Model *model = nullptr;
668
669   if (device_->needModel()) {
670     model = getModel (modelid);
671     if (model == nullptr)
672       return -ENOENT;
673   }
674
675   device_->setAsyncMode (mode);
676   return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
677 }
678
679 /**
680  * @brief get number of available devices
681  * @param[in] type device type
682  * @return number of devices
683  */
684 int
685 HostHandler::getNumDevices (dev_type type)
686 {
687   return DriverAPI::getNumDevices (type);
688 }
689
690 /**
691  * @brief get device instance
692  * @param[out] dev device instance
693  * @param[in] type device type
694  * @param[in] id device id
695  * @return 0 if no error. otherwise a negative errno
696  */
697 int
698 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
699 {
700   int num_devices = getNumDevices (type);
701
702   /** check the validity of device id */
703   if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
704     logerr (TAG, "Invalid arguments provided\n");
705     return -ENODEV;
706   }
707
708   Device *device = Device::createInstance (type, id);
709   if (device == nullptr) {
710     logerr (TAG, "Failed to create a device with the given type\n");
711     return -EINVAL;
712   }
713
714   *dev = device;
715   /** This is just for backward-compatility; we don't guarantee its corresness */
716   latest_dev_ = *dev;
717
718   return 0;
719 }
720
721 /**
722  * @brief allocate generic buffer (just for users)
723  * @param[out] buffer buffer instance
724  * @return 0 if no error. otherwise a negative errno
725  */
726 int
727 HostHandler::allocGenericBuffer (generic_buffer *buffer)
728 {
729   if (buffer == NULL)
730     return -EINVAL;
731
732   if (buffer->size == 0) {
733     logerr (TAG, "Invalid size\n");
734     return -EINVAL;
735   }
736
737   if (buffer->size > UINT32_MAX) {
738     logerr (TAG, "Don't support such a large size");
739     return -ENOMEM;
740   }
741
742   switch (buffer->type) {
743     case BUFFER_FILE:
744       /* nothing to do */
745       if (buffer->filepath == nullptr)
746         return -EINVAL;
747       break;
748     case BUFFER_MAPPED:
749     case BUFFER_DMABUF:
750     {
751       /* now, npu-engine always provides dmabuf-based allocation */
752       HWmem *hwmem;
753       int status = device_->allocMemory (buffer->size, &hwmem);
754       if (status != 0)
755         return status;
756
757       buffer->dmabuf = hwmem->getDmabuf();
758       buffer->offset = hwmem->getOffset();
759       buffer->addr = hwmem->getData();
760     } break;
761     default:
762       return -EINVAL;
763   }
764
765   return 0;
766 }
767
768 /**
769  * @brief deallocate generic buffer (just for users)
770  * @param[in] buffer buffer instance
771  * @return 0 if no error. otherwise a negative errno
772  */
773 int
774 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
775 {
776   if (buffer == NULL)
777     return -EINVAL;
778
779   int status;
780   switch (buffer->type) {
781     case BUFFER_FILE:
782       status = 0; /** always true cuz nothing to do */
783       break;
784     case BUFFER_MAPPED:
785     case BUFFER_DMABUF:
786       status = device_->deallocMemory (buffer->dmabuf);
787       break;
788     default:
789       status = -EINVAL;
790       break;
791   }
792
793   return status;
794 }
795
796 /**
797  * @brief allocate multiple generic buffers (just for users)
798  * @param[out] buffers multi-buffer instance
799  * @return 0 if no error. otherwise a negative errno
800  */
801 int
802 HostHandler::allocGenericBuffer (generic_buffers *buffers)
803 {
804   if (buffers == NULL || buffers->num_buffers < 1)
805     return -EINVAL;
806
807   buffer_types type = buffers->bufs[0].type;
808   if (type == BUFFER_FILE)
809     return 0;
810
811   uint64_t total_size = 0;
812   for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
813     total_size += buffers->bufs[idx].size;
814
815   uint64_t first_size = buffers->bufs[0].size;
816   buffers->bufs[0].size = total_size;
817   int status = allocGenericBuffer (&buffers->bufs[0]);
818   if (status != 0)
819     return status;
820
821   uint64_t offset = first_size;
822   for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
823     buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
824     buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
825     buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
826     buffers->bufs[idx].type = type;
827
828     offset += buffers->bufs[idx].size;
829   }
830
831   buffers->bufs[0].size = first_size;
832
833   return 0;
834 }
835
836 /**
837  * @brief deallocate multiple generic buffers (just for users)
838  * @param[in] buffers multi-buffer instance
839  * @return 0 if no error. otherwise a negative errno
840  */
841 int
842 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
843 {
844   if (buffers == NULL || buffers->num_buffers < 1)
845     return -EINVAL;
846
847   return deallocGenericBuffer (&buffers->bufs[0]);
848 }
849
850 /**
851  * @brief get the current memory status
852  * @param[out] alloc_total The size of allocated memory until now
853  * @param[out] free_total The size of freed memory until now
854  * @return 0 if no error. otherwise a negatice error value
855  */
856 int
857 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
858 {
859   /** API is always set in initialize () */
860   const DriverAPI * api = device_->getDriverAPI ();
861   assert (api != nullptr);
862
863   return api->getMemoryStatus (alloc_total, free_total);
864 }
865
866 /** implement methods of Device class */
867
868 /** @brief constructor of device */
869 Device::Device (dev_type type, int id, bool need_model)
870   : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
871     mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
872 {
873 }
874
875 /**
876  * @brief create device instance depending on device type and id
877  * @param[in] type device type
878  * @param[in] id device id
879  * @return device instance
880  */
881 Device *
882 Device::createInstance (dev_type type, int id)
883 {
884   Device *device = nullptr;
885
886   switch (type & DEVICETYPE_MASK) {
887     case DEVICETYPE_TRIV:
888       device = new TrinityVision (id);
889       break;
890     case DEVICETYPE_TRIV2:
891       device = new TrinityVision2 (id);
892       break;
893     case DEVICETYPE_TRIA:
894       device = new TrinityAsr (id);
895       break;
896     default:
897       break;
898   }
899
900   if (device != nullptr && device->init () != 0) {
901     delete device;
902     device = nullptr;
903   }
904
905   return device;
906 }
907
908 /**
909  * @brief device initialization
910  * @return 0 if no error, otherwise a negative errno
911  * @note Init failures come from createDriverAPI() only.
912  */
913 int
914 Device::init ()
915 {
916   /** should be initilizaed only once */
917   if (!atomic_flag_.test_and_set()) {
918     /** create the corresponding driver API */
919     api_ = DriverAPI::createDriverAPI (type_, id_);
920     if (api_.get() == nullptr) {
921       atomic_flag_.clear();
922       logerr (TAG, "Failed to create driver API\n");
923       return -EINVAL;
924     }
925
926     handler_.reset (new HostHandler (this));
927     scheduler_.reset (new Scheduler (api_.get()));
928     mem_ = MemAllocator::createInstance (api_.get());
929
930     initialized_ = true;  /** c++11 does not provide test() of atomic flag */
931   }
932
933   return 0;
934 }
935
936 /**
937  * @brief stop all requests from this device
938  * @param[in] force_stop indicate the schedduler waits until to handle previous requests
939  * @return 0 if no error, otherwise a negative errno
940  */
941 int
942 Device::stop (bool force_stop)
943 {
944   if (!initialized ()) {
945     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
946     return -EPERM;
947   }
948
949   Request *req = new Request (NPUINPUT_STOP);
950   req->setForceStop (force_stop);
951   return scheduler_->submitRequest (req);
952 }
953
954 /**
955  * @brief allocate generic memory buffer
956  * @param[out] hwmem_ptr hwmem instance pointer
957  * @return 0 if no error, otherwise a negative errno
958  */
959 int
960 Device::allocMemory (size_t size, HWmem ** hwmem_ptr)
961 {
962   if (!initialized ()) {
963     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
964     return -EPERM;
965   }
966
967   if (size == 0 || hwmem_ptr == nullptr)
968     return -EINVAL;
969
970   HWmem *hwmem = mem_->allocMemory (size);
971   if (hwmem == nullptr)
972     return -ENOMEM;
973
974   *hwmem_ptr = hwmem;
975   return 0;
976 }
977
978 /**
979  * @brief deallocate generic memory buffer
980  * @param[in] dmabuf_fd dmabuf file descriptor
981  * @return 0 if no error, otherwise a negative errno
982  */
983 int
984 Device::deallocMemory (int dmabuf_fd)
985 {
986   if (!initialized ()) {
987     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
988     return -EPERM;
989   }
990
991   return mem_->deallocMemory (dmabuf_fd);
992 }
993
994 /**
995  * @brief extract the buffer instance from input generic buffers
996  * @param[in] meta the model metadata
997  * @param[in] input the input generic buffers
998  * @return the buffer instance
999  */
1000 Buffer *
1001 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
1002 {
1003   if (meta == nullptr || input == nullptr ||
1004       meta->getInputNum() != input->num_buffers) {
1005     logerr (TAG, "Invalid metadata info provided\n");
1006     return nullptr;
1007   }
1008
1009   Buffer * buffer;
1010   const generic_buffer *first = &input->bufs[0];
1011   if (first->type == BUFFER_DMABUF) {
1012     buffer = mem_->allocBuffer (new HWmemExternal);
1013     if (buffer == nullptr)
1014       return nullptr;
1015
1016     buffer->setDmabuf (first->dmabuf);
1017     buffer->setOffset (first->offset);
1018     buffer->setSize (meta->getBufferSize());
1019   } else {
1020     buffer = mem_->allocBuffer (new HWmemDevice);
1021     if (buffer == nullptr)
1022       return nullptr;
1023
1024     int status = buffer->alloc (meta->getBufferSize ());
1025     if (status != 0) {
1026       logerr (TAG, "Failed to allocate buffer: %d\n", status);
1027       delete buffer;
1028       return nullptr;
1029     }
1030   }
1031
1032   int status = buffer->createTensors (meta);
1033   if (status != 0) {
1034     logerr (TAG, "Failed to create tensors: %d\n", status);
1035     delete buffer;
1036     buffer = nullptr;
1037   }
1038
1039   return buffer;
1040 }
1041
1042 /**
1043  * @brief implementation of TRIV's setModel ()
1044  * @param[in] model_buf the model generic buffer
1045  * @param[out] model the model instance
1046  * @return 0 if no error, otherwise a negative errno
1047  */
1048 int
1049 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1050 {
1051   if (!initialized ()) {
1052     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1053     return -EPERM;
1054   }
1055
1056   if (model_buf == nullptr || model_ptr == nullptr)
1057     return -EINVAL;
1058
1059   Model *model;
1060   int status;
1061
1062   switch (model_buf->type) {
1063   case BUFFER_DMABUF:
1064     model = mem_->allocModel (new HWmemExternal);
1065     if (model == nullptr) {
1066       logerr (TAG, "Failed to allocate model\n");
1067       return -ENOMEM;
1068     }
1069
1070     model->setDmabuf (model_buf->dmabuf);
1071     model->setOffset (model_buf->offset);
1072     model->setSize (model_buf->size);
1073     break;
1074   case BUFFER_FILE:
1075   case BUFFER_MAPPED:
1076     model = mem_->allocModel (new HWmemDevice);
1077     if (model == nullptr) {
1078       logerr (TAG, "Failed to allocate model\n");
1079       return -ENOMEM;
1080     }
1081
1082     status = model->alloc (model_buf->size);
1083     if (status != 0) {
1084       logerr (TAG, "Failed to allocate model: %d\n", status);
1085       goto delete_exit;
1086     }
1087
1088     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1089     if (status != 0) {
1090       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1091       goto delete_exit;
1092     }
1093     break;
1094   default:
1095     return -EINVAL;
1096   }
1097
1098   status = model->setMetadata (model->getData());
1099   if (status != 0)
1100     goto delete_exit;
1101
1102   model_config_t config;
1103   config.dmabuf_id = model->getDmabuf();
1104   config.program_size = model->getMetadata()->getProgramSize();
1105   config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
1106   config.weight_offset_addr = config.program_offset_addr + config.program_size;
1107
1108   status = api_->setModel (&config);
1109   if (status != 0)
1110     goto delete_exit;
1111
1112   *model_ptr = model;
1113   return status;
1114
1115 delete_exit:
1116   delete model;
1117   return status;
1118 }
1119
1120
1121 /**
1122  * @brief implementation of TRIV's run()
1123  * @param[in] opmode input opmode
1124  * @param[in] model the model instance
1125  * @param[in] input generic buffers of input data
1126  * @param[in] cb the output callback
1127  * @param[in] cb_data the output callback data
1128  * @param[out] sequence The sequence number returned with runNPU_async.
1129  */
1130 int
1131 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1132     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1133     uint64_t *sequence)
1134 {
1135   if (!initialized ()) {
1136     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1137     return -EPERM;
1138   }
1139
1140   if (opmode != NPUINPUT_HOST) {
1141     logerr (TAG, "TRIV supports only host inputservice\n");
1142     return -EINVAL;
1143   }
1144
1145   if (model == nullptr || input == nullptr) {
1146     logerr (TAG, "TRIV requires both model and input buffers\n");
1147     return -EINVAL;
1148   }
1149
1150   Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1151   if (buffer == nullptr) {
1152     logerr (TAG, "Failed to extract buffer instance\n");
1153     return -EINVAL;
1154   }
1155
1156   if (!buffer->isExternal ()) {
1157     for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1158       auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1159           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1160       int status = comm_.extractGenericBuffer (&input->bufs[idx],
1161           buffer->getInputTensor(idx)->getData(), func);
1162       if (status != 0) {
1163         logerr (TAG, "Failed to feed input buffer: %d\n", status);
1164         return status;
1165       }
1166     }
1167   }
1168
1169   /** this device uses CMA buffer */
1170
1171   Request *req = new Request (opmode);
1172   req->setModel (model);
1173   req->setBuffer (buffer);
1174
1175   if (cb != nullptr)
1176     req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1177
1178   if (sequence != nullptr)
1179     *sequence = req->getID();
1180
1181   return scheduler_->submitRequest (req);
1182 }
1183
1184 /**
1185  * @brief callback of TRIV2 request
1186  * @param[in] req the request instance
1187  * @param[in] cb callback for completion
1188  * @param[in] cb_data callback data
1189  * @note The callback invoke does not gurantee the request was successful
1190  * @todo Check the request failures
1191  */
1192 void
1193 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1194 {
1195   const Model *model = req->getModel ();
1196   Buffer *buffer = req->getBuffer ();
1197   output_buffers output = {
1198     .num_buffers = buffer->getOutputNum ()
1199   };
1200
1201   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1202     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1203
1204     if (buffer->isExternal ()) {
1205       output.bufs[idx].type = BUFFER_DMABUF;
1206       output.bufs[idx].size = output_tensor_size;
1207       output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1208     } else {
1209       output.bufs[idx].type = BUFFER_MAPPED;
1210       output.bufs[idx].size = output_tensor_size;
1211       /** user needs to free this */
1212       output.bufs[idx].addr = malloc (output_tensor_size);
1213
1214       auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1215           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1216       int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1217           &output.bufs[idx], func);
1218       if (status != 0) {
1219         logerr (TAG, "Failed to return output buffer: %d\n", status);
1220       }
1221     }
1222   }
1223
1224   cb (&output, req->getID(), cb_data);
1225
1226   delete buffer;
1227 }
1228
1229 /**
1230  * @brief extract the segment table instance from input generic buffers
1231  * @param[in] model the model instance
1232  * @param[in] input the input generic buffers
1233  * @return the segment table instance
1234  */
1235 SegmentTable *
1236 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1237 {
1238   if (model == nullptr || input == nullptr) {
1239     logerr (TAG, "Invalid arguments provided\n");
1240     return nullptr;
1241   }
1242
1243   const Metadata *meta = model->getMetadata ();
1244   if (meta == nullptr ||
1245       meta->getInputNum() != input->num_buffers) {
1246     logerr (TAG, "Invalid metadata info provided\n");
1247     return nullptr;
1248   }
1249
1250   SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1251   int status = segt->alloc ();
1252   if (status != 0) {
1253     logerr (TAG, "Failed to allocate segment table: %d\n", status);
1254     goto delete_segt;
1255   }
1256
1257   status = segt->createSegments (model, input);
1258   if (status != 0) {
1259     logerr (TAG, "Failed to create segments: %d\n", status);
1260     goto delete_segt;
1261   }
1262
1263   return segt;
1264
1265 delete_segt:
1266   delete segt;
1267   return nullptr;
1268 }
1269
1270 /** @brief implementation of TRIV2's setModel () */
1271 int
1272 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1273 {
1274   if (!initialized ()) {
1275     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1276     return -EPERM;
1277   }
1278
1279         if (model_buf == nullptr || model_ptr == nullptr)
1280                 return -EINVAL;
1281
1282   Model *model;
1283   int status;
1284
1285   switch (model_buf->type) {
1286   case BUFFER_DMABUF:
1287     model = mem_->allocModel (new HWmemExternal);
1288     if (model == nullptr) {
1289       logerr (TAG, "Failed to allocate model\n");
1290       return -ENOMEM;
1291     }
1292
1293     model->setDmabuf (model_buf->dmabuf);
1294     model->setOffset (model_buf->offset);
1295     model->setSize (model_buf->size);
1296     break;
1297   case BUFFER_FILE:
1298   case BUFFER_MAPPED:
1299     model = mem_->allocModel (new HWmemDevice);
1300     if (model == nullptr) {
1301       logerr (TAG, "Failed to allocate model\n");
1302       return -ENOMEM;
1303     }
1304
1305     status = model->alloc (model_buf->size);
1306     if (status != 0) {
1307       logerr (TAG, "Failed to allocate model: %d\n", status);
1308       goto delete_exit;
1309     }
1310
1311     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1312     if (status != 0) {
1313       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1314       goto delete_exit;
1315     }
1316     break;
1317   default:
1318     return -EINVAL;
1319   }
1320
1321   status = model->setMetadata (model->getData());
1322   if (status != 0)
1323     goto delete_exit;
1324
1325   model_config_t config;
1326   config.dmabuf_id = model->getDmabuf();
1327   config.program_size = model->getMetadata()->getProgramSize();
1328   config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
1329   /** [TRIV2] weight is stored in a segment */
1330   model->setWeightData (model->getData () + model->getMetadata()->getMetaSize() +
1331       model->getMetadata()->getProgramSize());
1332
1333   status = api_->setModel (&config);
1334   if (status != 0)
1335     goto delete_exit;
1336
1337   *model_ptr = model;
1338   return status;
1339
1340 delete_exit:
1341   delete model;
1342   return status;
1343 }
1344
1345 /** @brief implementation of TRIV2's run() */
1346 int
1347 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1348     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1349     uint64_t *sequence)
1350 {
1351   if (!initialized ()) {
1352     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1353     return -EPERM;
1354   }
1355
1356   if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1357     return -EINVAL;
1358
1359   /** this device uses segment table */
1360   SegmentTable * segt = prepareSegmentTable (model, input);
1361   if (segt == nullptr) {
1362     logerr (TAG, "Failed to create segment table instance\n");
1363     return -EINVAL;
1364   }
1365
1366   if (!model->isExternal ()) {
1367     /** set weight data */
1368     HWmem * weight = segt->getWeightSegment ();
1369     if (weight == nullptr) {
1370       logerr (TAG, "Failed to get a weight segment\n");
1371       return -ENOENT;
1372     }
1373
1374     const Metadata * meta = model->getMetadata ();
1375     memcpy (weight->getData (), model->getWeightData (), meta->getWeightSize ());
1376   }
1377
1378   if (!segt->isExternal ()) {
1379     /** extract input data */
1380     for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1381       auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1382           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1383       int status = comm_.extractGenericBuffer (&input->bufs[idx],
1384           segt->getInputSegment(idx)->getData(), func);
1385       if (status != 0) {
1386         logerr (TAG, "Failed to feed input segment: %d\n", status);
1387         return status;
1388       }
1389     }
1390   }
1391
1392   Request *req = new Request (opmode);
1393   req->setModel (model);
1394   req->setSegmentTable (segt);
1395   req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1396
1397   if (sequence)
1398     *sequence = req->getID();
1399
1400   return scheduler_->submitRequest (req);
1401 }
1402
1403 /** @brief callback of TRIV2 request */
1404 void
1405 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1406 {
1407   const Model *model = req->getModel ();
1408   SegmentTable *segt = req->getSegmentTable ();
1409   output_buffers output = {
1410     .num_buffers = segt->getNumOutputSegments ()
1411   };
1412
1413   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1414     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1415
1416     output.bufs[idx].type = BUFFER_MAPPED;
1417     output.bufs[idx].size = output_tensor_size;
1418     /** user needs to free this */
1419     output.bufs[idx].addr = malloc (output_tensor_size);
1420
1421     auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1422         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1423     int status = comm_.insertGenericBuffer (segt->getOutputSegment(idx)->getData(),
1424         &output.bufs[idx], func);
1425     if (status != 0) {
1426       logerr (TAG, "Failed to return output buffer: %d\n", status);
1427     }
1428   }
1429
1430   cb (&output, req->getID(), cb_data);
1431
1432   delete segt;
1433 }
1434
1435 /** @brief implementation of TRIA's run(): WIP */
1436 int
1437 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1438     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1439     uint64_t *sequence)
1440 {
1441   if (!initialized ()) {
1442     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1443     return -EPERM;
1444   }
1445
1446   if (opmode != NPUINPUT_HOST)
1447     return -EINVAL;
1448
1449   Buffer * buffer;
1450   int status;
1451   /** ASR does not require model and support only a single tensor */
1452   const generic_buffer *first_buf = &input->bufs[0];
1453   if (first_buf->type == BUFFER_DMABUF) {
1454     buffer = mem_->allocBuffer (new HWmemExternal);
1455     if (buffer == nullptr)
1456       return -ENOMEM;
1457
1458     buffer->setDmabuf (first_buf->dmabuf);
1459     buffer->setOffset (first_buf->offset);
1460     buffer->setSize (first_buf->size);
1461   } else {
1462     buffer = mem_->allocBuffer (new HWmemDevice);
1463     if (buffer == nullptr)
1464       return -ENOMEM;
1465
1466     status = buffer->alloc (first_buf->size);
1467     if (status != 0) {
1468       delete buffer;
1469       return status;
1470     }
1471   }
1472
1473   status = buffer->createTensors ();
1474   if (status != 0) {
1475     logerr (TAG, "Failed to create tensors: %d\n", status);
1476     delete buffer;
1477     return status;
1478   }
1479
1480   if (!buffer->isExternal ()) {
1481     status = comm_.extractGenericBuffer (first_buf,
1482         buffer->getInputTensor(0)->getData(), nullptr);
1483     if (status != 0)
1484       return status;
1485   }
1486
1487   Request *req = new Request (opmode);
1488   req->setBuffer (buffer);
1489   req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1490
1491   if (sequence)
1492     *sequence = req->getID();
1493
1494   return scheduler_->submitRequest (req);
1495 }
1496
1497 /** @brief callback of TRIA request: WIP */
1498 void
1499 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1500 {
1501 }
1502
1503 /** Implement data manipulation (each device may have different impl.) */
1504
1505 #ifdef ENABLE_MANIP
1506
1507 #define do_quantized_memcpy(type) do {\
1508     idx = 0;\
1509     if (quant) {\
1510       while (idx < num_elems) {\
1511           val = ((type *) src)[idx];\
1512           val = val / _scale;\
1513           val += _zero_point;\
1514           val = (val > 255.0) ? 255.0 : 0.0;\
1515           ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1516       }\
1517     } else {\
1518       while (idx < num_elems) {\
1519           val = *(uint8_t *) src;\
1520           val -= _zero_point;\
1521           val *= _scale;\
1522           ((type *) dst)[idx++] = (type) val;\
1523           dst = (void*)(((uint8_t *) dst) + data_size);\
1524           src = (void*)(((uint8_t *) src) + 1);\
1525       }\
1526     }\
1527   } while (0)
1528
1529 /**
1530  * @brief memcpy during quantization
1531  */
1532 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1533     void *dst, const void *src, uint32_t num_elems)
1534 {
1535   double _scale = (double) scale;
1536   double _zero_point = (double) zero_point;
1537   double val;
1538   uint32_t data_size = get_data_size (type);
1539   uint32_t idx;
1540
1541   switch (type) {
1542     case DATA_TYPE_INT8:
1543       do_quantized_memcpy (int8_t);
1544       break;
1545     case DATA_TYPE_UINT8:
1546       do_quantized_memcpy (uint8_t);
1547       break;
1548     case DATA_TYPE_INT16:
1549       do_quantized_memcpy (int16_t);
1550       break;
1551     case DATA_TYPE_UINT16:
1552       do_quantized_memcpy (uint16_t);
1553       break;
1554     case DATA_TYPE_INT32:
1555       do_quantized_memcpy (int32_t);
1556       break;
1557     case DATA_TYPE_UINT32:
1558       do_quantized_memcpy (uint32_t);
1559       break;
1560     case DATA_TYPE_INT64:
1561       do_quantized_memcpy (int64_t);
1562       break;
1563     case DATA_TYPE_UINT64:
1564       do_quantized_memcpy (uint64_t);
1565       break;
1566     case DATA_TYPE_FLOAT32:
1567       do_quantized_memcpy (float);
1568       break;
1569     case DATA_TYPE_FLOAT64:
1570       do_quantized_memcpy (double);
1571       break;
1572     default:
1573       logerr (TAG, "Unsupported datatype %d\n", type);
1574   }
1575 }
1576
1577 /**
1578  * @brief perform data manipulation
1579  * @param[in] model model instance
1580  * @param[in] idx tensor index
1581  * @param[in] is_input indicate it's input manipulation
1582  * @param[out] dst destination buffer
1583  * @param[in] src source buffer (feature map)
1584  * @param[in] size size to be copied
1585  * @return size of memory copy if no error, otherwise zero
1586  *
1587  * @note the input data format should be NHWC
1588  * @detail rules for the memory address of activations in NPU HW.
1589  *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1590  *
1591  * 1) Special case (depth == 3)
1592  * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1593  *
1594  * 2) Common case
1595  * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1596  *
1597  * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1598  */
1599 size_t
1600 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1601     void *dst, void *src, size_t size)
1602 {
1603   const Metadata *meta = model->getMetadata();
1604   const tensor_data_info* info;
1605   const uint32_t *dims;
1606   uint32_t zero_point;
1607   float scale;
1608
1609   /** extract required information from the metadata */
1610   if (is_input) {
1611     if (idx >= meta->getInputNum()) {
1612       logerr (TAG, "Wrong information for input tensors in metadata\n");
1613       return 0;
1614     }
1615
1616     info = model->getInputDataInfo (idx);
1617     dims = meta->getInputDims (idx);
1618     zero_point = meta->getInputQuantZero (idx);
1619     scale = meta->getInputQuantScale (idx);
1620   } else {
1621     if (idx >= meta->getOutputNum()) {
1622       logerr (TAG, "Wrong information for output tensors in metadata\n");
1623       return 0;
1624     }
1625
1626     info = model->getOutputDataInfo (idx);
1627     dims = meta->getOutputDims (idx);
1628     zero_point = meta->getOutputQuantZero (idx);
1629     scale = meta->getOutputQuantScale (idx);
1630   }
1631
1632   if (info == nullptr) {
1633     logerr (TAG, "Unmatched tensors info\n");
1634     return 0;
1635   }
1636
1637   uint32_t batch = dims[0];
1638   uint32_t height = dims[1];
1639   uint32_t width = dims[2];
1640   uint32_t depth = dims[3];
1641
1642   uint32_t data_size = get_data_size (info->type);
1643   if (data_size == 0) {
1644     logerr (TAG, "Invalid data size\n");
1645     return 0;
1646   }
1647
1648   bool need_quantization = false;
1649   /**
1650    * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1651    * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1652    */
1653   if (info->type != DATA_TYPE_SRNPU) {
1654     assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1655
1656     if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1657         !(zero_point == default_quant_zero && scale == default_quant_scale))
1658       need_quantization = true;
1659   }
1660
1661   /** check data manipulation is required */
1662   if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1663     uint32_t MPA_L = DATA_GRANULARITY;
1664     uint32_t n, h, w, d;
1665     uint32_t std_offset;  /* standard offset in NHWC data format */
1666     uint32_t npu_offset;  /* npu offset in NPU HW data format*/
1667     uint32_t src_offset;
1668     uint32_t dst_offset;
1669     uint32_t slice_size;
1670
1671     /* @todo we currently support only NHWC */
1672     if (info->layout != DATA_LAYOUT_NHWC) {
1673       logerr (TAG, "data manipulation is supported for NHWC only\n");
1674       return 0;
1675     }
1676
1677     for (n = 0; n < batch; n++) {
1678       for (h = 0; h < height; h++) {
1679         for (w = 0; w < width; w++) {
1680           for (d = 0; d < depth; d += MPA_L) {
1681             std_offset = d + depth * (w + width * (h + n * height));
1682             npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1683             slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1684
1685             if (is_input) {
1686               src_offset = std_offset * data_size;
1687               dst_offset = npu_offset;
1688             } else {
1689               src_offset = npu_offset;
1690               dst_offset = std_offset * data_size;
1691             }
1692
1693             /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1694             if (need_quantization) {
1695               memcpy_with_quant (is_input, info->type, scale, zero_point,
1696                   static_cast<char*>(dst) + dst_offset,
1697                   static_cast<char*>(src) + src_offset,
1698                   slice_size);
1699             } else {
1700               memcpy (
1701                   static_cast<char*>(dst) + dst_offset,
1702                   static_cast<char*>(src) + src_offset,
1703                   slice_size);
1704             }
1705           }
1706         }
1707       }
1708     }
1709   } else if (need_quantization) {
1710     /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1711     memcpy_with_quant (is_input, info->type, scale, zero_point,
1712         dst, src, is_input ? size / data_size : size);
1713   } else {
1714     memcpy (dst, src, size);
1715   }
1716
1717   return size;
1718 }
1719
1720 #else
1721
1722 size_t
1723 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1724     void *dst, void *src, size_t size)
1725 {
1726   memcpy (dst, src, size);
1727   return size;
1728 }
1729
1730 #endif
1731
1732 /** other device types don't have data manip impl. yet */
1733
1734 size_t
1735 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1736     void *dst, void *src, size_t size)
1737 {
1738   memcpy (dst, src, size);
1739   return size;
1740 }
1741
1742 size_t
1743 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1744     void *dst, void *src, size_t size)
1745 {
1746   memcpy (dst, src, size);
1747   return size;
1748 }