[Core/DrvAPI] Implement the driver api for triv1
[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.dbuf_fd = 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_->registerModel (&config);
1109   if (status != 0)
1110     goto delete_exit;
1111
1112   model->setInternalID(config.id);
1113   *model_ptr = model;
1114   return status;
1115
1116 delete_exit:
1117   delete model;
1118   return status;
1119 }
1120
1121
1122 /**
1123  * @brief implementation of TRIV's run()
1124  * @param[in] opmode input opmode
1125  * @param[in] model the model instance
1126  * @param[in] input generic buffers of input data
1127  * @param[in] cb the output callback
1128  * @param[in] cb_data the output callback data
1129  * @param[out] sequence The sequence number returned with runNPU_async.
1130  */
1131 int
1132 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1133     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1134     uint64_t *sequence)
1135 {
1136   if (!initialized ()) {
1137     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1138     return -EPERM;
1139   }
1140
1141   if (opmode != NPUINPUT_HOST) {
1142     logerr (TAG, "TRIV supports only host inputservice\n");
1143     return -EINVAL;
1144   }
1145
1146   if (model == nullptr || input == nullptr) {
1147     logerr (TAG, "TRIV requires both model and input buffers\n");
1148     return -EINVAL;
1149   }
1150
1151   Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1152   if (buffer == nullptr) {
1153     logerr (TAG, "Failed to extract buffer instance\n");
1154     return -EINVAL;
1155   }
1156
1157   if (!buffer->isExternal ()) {
1158     for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1159       auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1160           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1161       int status = comm_.extractGenericBuffer (&input->bufs[idx],
1162           buffer->getInputTensor(idx)->getData(), func);
1163       if (status != 0) {
1164         logerr (TAG, "Failed to feed input buffer: %d\n", status);
1165         return status;
1166       }
1167     }
1168   }
1169
1170   /** this device uses CMA buffer */
1171
1172   Request *req = new Request (opmode);
1173   req->setModel (model);
1174   req->setBuffer (buffer);
1175
1176   if (cb != nullptr)
1177     req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1178
1179   if (sequence != nullptr)
1180     *sequence = req->getID();
1181
1182   return scheduler_->submitRequest (req);
1183 }
1184
1185 /**
1186  * @brief callback of TRIV2 request
1187  * @param[in] req the request instance
1188  * @param[in] cb callback for completion
1189  * @param[in] cb_data callback data
1190  * @note The callback invoke does not gurantee the request was successful
1191  * @todo Check the request failures
1192  */
1193 void
1194 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1195 {
1196   const Model *model = req->getModel ();
1197   Buffer *buffer = req->getBuffer ();
1198   output_buffers output = {
1199     .num_buffers = buffer->getOutputNum ()
1200   };
1201
1202   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1203     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1204
1205     if (buffer->isExternal ()) {
1206       output.bufs[idx].type = BUFFER_DMABUF;
1207       output.bufs[idx].size = output_tensor_size;
1208       output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1209     } else {
1210       output.bufs[idx].type = BUFFER_MAPPED;
1211       output.bufs[idx].size = output_tensor_size;
1212       /** user needs to free this */
1213       output.bufs[idx].addr = malloc (output_tensor_size);
1214
1215       auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1216           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1217       int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1218           &output.bufs[idx], func);
1219       if (status != 0) {
1220         logerr (TAG, "Failed to return output buffer: %d\n", status);
1221       }
1222     }
1223   }
1224
1225   cb (&output, req->getID(), cb_data);
1226
1227   delete buffer;
1228 }
1229
1230 /**
1231  * @brief extract the segment table instance from input generic buffers
1232  * @param[in] model the model instance
1233  * @param[in] input the input generic buffers
1234  * @return the segment table instance
1235  */
1236 SegmentTable *
1237 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1238 {
1239   if (model == nullptr || input == nullptr) {
1240     logerr (TAG, "Invalid arguments provided\n");
1241     return nullptr;
1242   }
1243
1244   const Metadata *meta = model->getMetadata ();
1245   if (meta == nullptr ||
1246       meta->getInputNum() != input->num_buffers) {
1247     logerr (TAG, "Invalid metadata info provided\n");
1248     return nullptr;
1249   }
1250
1251   SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1252   int status = segt->alloc ();
1253   if (status != 0) {
1254     logerr (TAG, "Failed to allocate segment table: %d\n", status);
1255     goto delete_segt;
1256   }
1257
1258   status = segt->createSegments (model, input);
1259   if (status != 0) {
1260     logerr (TAG, "Failed to create segments: %d\n", status);
1261     goto delete_segt;
1262   }
1263
1264   return segt;
1265
1266 delete_segt:
1267   delete segt;
1268   return nullptr;
1269 }
1270
1271 /** @brief implementation of TRIV2's setModel () */
1272 int
1273 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1274 {
1275   if (!initialized ()) {
1276     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1277     return -EPERM;
1278   }
1279
1280         if (model_buf == nullptr || model_ptr == nullptr)
1281                 return -EINVAL;
1282
1283   Model *model;
1284   int status;
1285
1286   switch (model_buf->type) {
1287   case BUFFER_DMABUF:
1288     model = mem_->allocModel (new HWmemExternal);
1289     if (model == nullptr) {
1290       logerr (TAG, "Failed to allocate model\n");
1291       return -ENOMEM;
1292     }
1293
1294     model->setDmabuf (model_buf->dmabuf);
1295     model->setOffset (model_buf->offset);
1296     model->setSize (model_buf->size);
1297     break;
1298   case BUFFER_FILE:
1299   case BUFFER_MAPPED:
1300     model = mem_->allocModel (new HWmemDevice);
1301     if (model == nullptr) {
1302       logerr (TAG, "Failed to allocate model\n");
1303       return -ENOMEM;
1304     }
1305
1306     status = model->alloc (model_buf->size);
1307     if (status != 0) {
1308       logerr (TAG, "Failed to allocate model: %d\n", status);
1309       goto delete_exit;
1310     }
1311
1312     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1313     if (status != 0) {
1314       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1315       goto delete_exit;
1316     }
1317     break;
1318   default:
1319     return -EINVAL;
1320   }
1321
1322   status = model->setMetadata (model->getData());
1323   if (status != 0)
1324     goto delete_exit;
1325
1326   model_config_t config;
1327   config.dbuf_fd = model->getDmabuf();
1328   config.program_size = model->getMetadata()->getProgramSize();
1329   config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
1330   /** [TRIV2] weight is stored in a segment */
1331   model->setWeightData (model->getData () + model->getMetadata()->getMetaSize() +
1332       model->getMetadata()->getProgramSize());
1333
1334   status = api_->registerModel (&config);
1335   if (status != 0)
1336     goto delete_exit;
1337
1338   *model_ptr = model;
1339   return status;
1340
1341 delete_exit:
1342   delete model;
1343   return status;
1344 }
1345
1346 /** @brief implementation of TRIV2's run() */
1347 int
1348 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1349     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1350     uint64_t *sequence)
1351 {
1352   if (!initialized ()) {
1353     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1354     return -EPERM;
1355   }
1356
1357   if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1358     return -EINVAL;
1359
1360   /** this device uses segment table */
1361   SegmentTable * segt = prepareSegmentTable (model, input);
1362   if (segt == nullptr) {
1363     logerr (TAG, "Failed to create segment table instance\n");
1364     return -EINVAL;
1365   }
1366
1367   if (!model->isExternal ()) {
1368     /** set weight data */
1369     HWmem * weight = segt->getWeightSegment ();
1370     if (weight == nullptr) {
1371       logerr (TAG, "Failed to get a weight segment\n");
1372       return -ENOENT;
1373     }
1374
1375     const Metadata * meta = model->getMetadata ();
1376     memcpy (weight->getData (), model->getWeightData (), meta->getWeightSize ());
1377   }
1378
1379   if (!segt->isExternal ()) {
1380     /** extract input data */
1381     for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1382       auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1383           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1384       int status = comm_.extractGenericBuffer (
1385           &input->bufs[idx],
1386           segt->getInputSegment(idx)->getData() + segt->getInputSegmentOffset(idx),
1387           func);
1388       if (status != 0) {
1389         logerr (TAG, "Failed to feed input segment: %d\n", status);
1390         return status;
1391       }
1392     }
1393   }
1394
1395   Request *req = new Request (opmode);
1396   req->setModel (model);
1397   req->setSegmentTable (segt);
1398   req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1399
1400   if (sequence)
1401     *sequence = req->getID();
1402
1403   return scheduler_->submitRequest (req);
1404 }
1405
1406 /** @brief callback of TRIV2 request */
1407 void
1408 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1409 {
1410   const Model *model = req->getModel ();
1411   SegmentTable *segt = req->getSegmentTable ();
1412   output_buffers output = {
1413     .num_buffers = segt->getNumOutputSegments ()
1414   };
1415
1416   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1417     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1418
1419     output.bufs[idx].type = BUFFER_MAPPED;
1420     output.bufs[idx].size = output_tensor_size;
1421     /** user needs to free this */
1422     output.bufs[idx].addr = malloc (output_tensor_size);
1423
1424     auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1425         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1426     int status = comm_.insertGenericBuffer (
1427         segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1428         &output.bufs[idx], func);
1429     if (status != 0) {
1430       logerr (TAG, "Failed to return output buffer: %d\n", status);
1431     }
1432   }
1433
1434   cb (&output, req->getID(), cb_data);
1435
1436   delete segt;
1437 }
1438
1439 /** @brief implementation of TRIA's run(): WIP */
1440 int
1441 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1442     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1443     uint64_t *sequence)
1444 {
1445   if (!initialized ()) {
1446     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1447     return -EPERM;
1448   }
1449
1450   if (opmode != NPUINPUT_HOST)
1451     return -EINVAL;
1452
1453   Buffer * buffer;
1454   int status;
1455   /** ASR does not require model and support only a single tensor */
1456   const generic_buffer *first_buf = &input->bufs[0];
1457   if (first_buf->type == BUFFER_DMABUF) {
1458     buffer = mem_->allocBuffer (new HWmemExternal);
1459     if (buffer == nullptr)
1460       return -ENOMEM;
1461
1462     buffer->setDmabuf (first_buf->dmabuf);
1463     buffer->setOffset (first_buf->offset);
1464     buffer->setSize (first_buf->size);
1465   } else {
1466     buffer = mem_->allocBuffer (new HWmemDevice);
1467     if (buffer == nullptr)
1468       return -ENOMEM;
1469
1470     status = buffer->alloc (first_buf->size);
1471     if (status != 0) {
1472       delete buffer;
1473       return status;
1474     }
1475   }
1476
1477   status = buffer->createTensors ();
1478   if (status != 0) {
1479     logerr (TAG, "Failed to create tensors: %d\n", status);
1480     delete buffer;
1481     return status;
1482   }
1483
1484   if (!buffer->isExternal ()) {
1485     status = comm_.extractGenericBuffer (first_buf,
1486         buffer->getInputTensor(0)->getData(), nullptr);
1487     if (status != 0)
1488       return status;
1489   }
1490
1491   Request *req = new Request (opmode);
1492   req->setBuffer (buffer);
1493   req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1494
1495   if (sequence)
1496     *sequence = req->getID();
1497
1498   return scheduler_->submitRequest (req);
1499 }
1500
1501 /** @brief callback of TRIA request: WIP */
1502 void
1503 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1504 {
1505 }
1506
1507 /** Implement data manipulation (each device may have different impl.) */
1508
1509 #ifdef ENABLE_MANIP
1510
1511 #define do_quantized_memcpy(type) do {\
1512     idx = 0;\
1513     if (quant) {\
1514       while (idx < num_elems) {\
1515           val = ((type *) src)[idx];\
1516           val = val / _scale;\
1517           val += _zero_point;\
1518           val = (val > 255.0) ? 255.0 : 0.0;\
1519           ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1520       }\
1521     } else {\
1522       while (idx < num_elems) {\
1523           val = *(uint8_t *) src;\
1524           val -= _zero_point;\
1525           val *= _scale;\
1526           ((type *) dst)[idx++] = (type) val;\
1527           dst = (void*)(((uint8_t *) dst) + data_size);\
1528           src = (void*)(((uint8_t *) src) + 1);\
1529       }\
1530     }\
1531   } while (0)
1532
1533 /**
1534  * @brief memcpy during quantization
1535  */
1536 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1537     void *dst, const void *src, uint32_t num_elems)
1538 {
1539   double _scale = (double) scale;
1540   double _zero_point = (double) zero_point;
1541   double val;
1542   uint32_t data_size = get_data_size (type);
1543   uint32_t idx;
1544
1545   switch (type) {
1546     case DATA_TYPE_INT8:
1547       do_quantized_memcpy (int8_t);
1548       break;
1549     case DATA_TYPE_UINT8:
1550       do_quantized_memcpy (uint8_t);
1551       break;
1552     case DATA_TYPE_INT16:
1553       do_quantized_memcpy (int16_t);
1554       break;
1555     case DATA_TYPE_UINT16:
1556       do_quantized_memcpy (uint16_t);
1557       break;
1558     case DATA_TYPE_INT32:
1559       do_quantized_memcpy (int32_t);
1560       break;
1561     case DATA_TYPE_UINT32:
1562       do_quantized_memcpy (uint32_t);
1563       break;
1564     case DATA_TYPE_INT64:
1565       do_quantized_memcpy (int64_t);
1566       break;
1567     case DATA_TYPE_UINT64:
1568       do_quantized_memcpy (uint64_t);
1569       break;
1570     case DATA_TYPE_FLOAT32:
1571       do_quantized_memcpy (float);
1572       break;
1573     case DATA_TYPE_FLOAT64:
1574       do_quantized_memcpy (double);
1575       break;
1576     default:
1577       logerr (TAG, "Unsupported datatype %d\n", type);
1578   }
1579 }
1580
1581 /**
1582  * @brief perform data manipulation
1583  * @param[in] model model instance
1584  * @param[in] idx tensor index
1585  * @param[in] is_input indicate it's input manipulation
1586  * @param[out] dst destination buffer
1587  * @param[in] src source buffer (feature map)
1588  * @param[in] size size to be copied
1589  * @return size of memory copy if no error, otherwise zero
1590  *
1591  * @note the input data format should be NHWC
1592  * @detail rules for the memory address of activations in NPU HW.
1593  *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1594  *
1595  * 1) Special case (depth == 3)
1596  * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1597  *
1598  * 2) Common case
1599  * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1600  *
1601  * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1602  */
1603 size_t
1604 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1605     void *dst, void *src, size_t size)
1606 {
1607   const Metadata *meta = model->getMetadata();
1608   const tensor_data_info* info;
1609   const uint32_t *dims;
1610   uint32_t zero_point;
1611   float scale;
1612
1613   /** extract required information from the metadata */
1614   if (is_input) {
1615     if (idx >= meta->getInputNum()) {
1616       logerr (TAG, "Wrong information for input tensors in metadata\n");
1617       return 0;
1618     }
1619
1620     info = model->getInputDataInfo (idx);
1621     dims = meta->getInputDims (idx);
1622     zero_point = meta->getInputQuantZero (idx);
1623     scale = meta->getInputQuantScale (idx);
1624   } else {
1625     if (idx >= meta->getOutputNum()) {
1626       logerr (TAG, "Wrong information for output tensors in metadata\n");
1627       return 0;
1628     }
1629
1630     info = model->getOutputDataInfo (idx);
1631     dims = meta->getOutputDims (idx);
1632     zero_point = meta->getOutputQuantZero (idx);
1633     scale = meta->getOutputQuantScale (idx);
1634   }
1635
1636   if (info == nullptr) {
1637     logerr (TAG, "Unmatched tensors info\n");
1638     return 0;
1639   }
1640
1641   uint32_t batch = dims[0];
1642   uint32_t height = dims[1];
1643   uint32_t width = dims[2];
1644   uint32_t depth = dims[3];
1645
1646   uint32_t data_size = get_data_size (info->type);
1647   if (data_size == 0) {
1648     logerr (TAG, "Invalid data size\n");
1649     return 0;
1650   }
1651
1652   bool need_quantization = false;
1653   /**
1654    * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1655    * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1656    */
1657   if (info->type != DATA_TYPE_SRNPU) {
1658     assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1659
1660     if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1661         !(zero_point == default_quant_zero && scale == default_quant_scale))
1662       need_quantization = true;
1663   }
1664
1665   /** check data manipulation is required */
1666   if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1667     uint32_t MPA_L = DATA_GRANULARITY;
1668     uint32_t n, h, w, d;
1669     uint32_t std_offset;  /* standard offset in NHWC data format */
1670     uint32_t npu_offset;  /* npu offset in NPU HW data format*/
1671     uint32_t src_offset;
1672     uint32_t dst_offset;
1673     uint32_t slice_size;
1674
1675     /* @todo we currently support only NHWC */
1676     if (info->layout != DATA_LAYOUT_NHWC) {
1677       logerr (TAG, "data manipulation is supported for NHWC only\n");
1678       return 0;
1679     }
1680
1681     for (n = 0; n < batch; n++) {
1682       for (h = 0; h < height; h++) {
1683         for (w = 0; w < width; w++) {
1684           for (d = 0; d < depth; d += MPA_L) {
1685             std_offset = d + depth * (w + width * (h + n * height));
1686             npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1687             slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1688
1689             if (is_input) {
1690               src_offset = std_offset * data_size;
1691               dst_offset = npu_offset;
1692             } else {
1693               src_offset = npu_offset;
1694               dst_offset = std_offset * data_size;
1695             }
1696
1697             /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1698             if (need_quantization) {
1699               memcpy_with_quant (is_input, info->type, scale, zero_point,
1700                   static_cast<char*>(dst) + dst_offset,
1701                   static_cast<char*>(src) + src_offset,
1702                   slice_size);
1703             } else {
1704               memcpy (
1705                   static_cast<char*>(dst) + dst_offset,
1706                   static_cast<char*>(src) + src_offset,
1707                   slice_size);
1708             }
1709           }
1710         }
1711       }
1712     }
1713   } else if (need_quantization) {
1714     /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1715     memcpy_with_quant (is_input, info->type, scale, zero_point,
1716         dst, src, is_input ? size / data_size : size);
1717   } else {
1718     memcpy (dst, src, size);
1719   }
1720
1721   return size;
1722 }
1723
1724 #else
1725
1726 size_t
1727 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1728     void *dst, void *src, size_t size)
1729 {
1730   memcpy (dst, src, size);
1731   return size;
1732 }
1733
1734 #endif
1735
1736 /** other device types don't have data manip impl. yet */
1737
1738 size_t
1739 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1740     void *dst, void *src, size_t size)
1741 {
1742   memcpy (dst, src, size);
1743   return size;
1744 }
1745
1746 size_t
1747 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1748     void *dst, void *src, size_t size)
1749 {
1750   memcpy (dst, src, size);
1751   return size;
1752 }