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