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