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