[UnitTests] Fix build warnings about -Werror=sign-compare
[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 metadata for NPU model
293  * @param[in] model The path of model binary file
294  * @param[in] need_extra whether you want to extract the extra data in metadata
295  * @return the metadata structure to be filled if no error, otherwise nullptr
296  *
297  * @note For most npu-engine users, the extra data is not useful because it will be
298  *       used for second-party users (e.g., compiler, simulator).
299  *       Also, the caller needs to free the metadata.
300  *
301  * @note the caller needs to free the metadata
302  */
303 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
304 {
305   npubin_meta *meta;
306   FILE *fp;
307   size_t ret;
308
309   if (!model)
310     return nullptr;
311
312   fp = fopen (model, "rb");
313   if (!fp) {
314     logerr (TAG, "Failed to open the model binary: %d\n", -errno);
315     return nullptr;
316   }
317
318   meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
319   if (!meta) {
320     logerr (TAG, "Failed to allocate metadata\n");
321     goto exit_err;
322   }
323
324   ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
325   if (ret != NPUBIN_META_SIZE) {
326     logerr (TAG, "Failed to read the metadata\n");
327     goto exit_free;
328   }
329
330   if (!CHECK_NPUBIN (meta->magiccode)) {
331     logerr (TAG, "Invalid metadata provided\n");
332     goto exit_free;
333   }
334
335   if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
336     npubin_meta *new_meta;
337
338     new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
339     if (!new_meta) {
340       logerr (TAG, "Failed to allocate extra metadata\n");
341       goto exit_free;
342     }
343
344     ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
345     if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
346       logerr (TAG, "Invalid extra metadata provided\n");
347       free (new_meta);
348       goto exit_err;
349     }
350
351     meta = new_meta;
352   }
353
354   fclose (fp);
355
356   return meta;
357
358 exit_free:
359   free (meta);
360 exit_err:
361   fclose (fp);
362
363   return nullptr;
364 }
365
366 /** deprecated buffer APIs; please use the above APIs */
367
368 /**
369  * @brief Returns the number of NPU devices (TRIV).
370  */
371 int getnumNPUdevice (void)
372 {
373   logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
374   return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
375 }
376
377 /**
378  * @brief Returns the list of ASR devices (TRIA)
379  */
380 int getnumASRdevice (void)
381 {
382   logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
383   return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
384 }
385
386 /**
387  * @brief Returns the handle of the chosen TRIV device.
388  */
389 int getNPUdevice (npudev_h *dev, uint32_t id)
390 {
391   logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
392   return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
393 }
394
395 /**
396  * @brief Returns the handle of the chosen TRIA device.
397  */
398 int getASRdevice (npudev_h *dev, uint32_t id)
399 {
400   logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
401   return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
402 }
403
404 /** @brief deprecated */
405 int allocModelBuffer (generic_buffer *buffer)
406 {
407   logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
408   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
409 }
410
411 /** @brief deprecated */
412 int cleanModelBuffer (generic_buffer *buffer)
413 {
414   logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
415   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
416 }
417
418 /** @brief deprecated */
419 int allocInputBuffer (generic_buffer *buffer)
420 {
421   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
422   return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
423 }
424
425 /** @brief deprecated */
426 int cleanInputBuffer (generic_buffer *buffer)
427 {
428   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
429   return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
430 }
431
432 /** @brief deprecated */
433 int allocInputBuffers (input_buffers * input)
434 {
435   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
436   return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
437 }
438
439 /** @brief deprecated */
440 int cleanInputBuffers (input_buffers * input)
441 {
442   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
443   return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
444 }
445
446 /** @brief deprecated */
447 int allocNPUBuffer (uint64_t size, buffer_types type,
448     const char * filepath, generic_buffer *buffer)
449 {
450   if (buffer) {
451     buffer->size = size;
452     buffer->type = type;
453     buffer->filepath = filepath;
454   }
455
456   logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
457   return allocModelBuffer (buffer);
458 }
459
460 /** @brief deprecated */
461 int cleanNPUBuffer (generic_buffer * buffer)
462 {
463   logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
464   return cleanModelBuffer (buffer);
465 }
466
467 /** implement methods of HostHandler class */
468
469 /** @brief host handler constructor */
470 HostHandler::HostHandler (Device *device)
471   : device_(device),
472     /* ignored as we don't use double buffering anymore, but for backward-compatibility */
473     async_mode_ (NPUASYNC_WAIT)
474 {
475 }
476
477 /** @brief host handler destructor */
478 HostHandler::~HostHandler ()
479 {
480 }
481
482 /**
483  * @brief register model from generic buffer
484  * @param[in] model_buf model buffer
485  * @param[out] modelid model id
486  * @return 0 if no error. otherwise a negative errno
487  */
488 int
489 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
490 {
491   if (model_buf == nullptr || modelid == nullptr) {
492     logerr (TAG, "Invalid arguments given\n");
493     return -EINVAL;
494   }
495
496   Model *model = nullptr;
497   int status = device_->setModel (model_buf, &model);
498   if (status != 0) {
499     logerr (TAG, "Failed to set model: %d\n", status);
500     return status;
501   }
502
503   assert (model != nullptr);
504
505   status = models_.insert (model->getID(), model);
506   if (status != 0) {
507     logerr (TAG, "Failed to insert model id\n");
508     delete model;
509     return status;
510   }
511
512   *modelid = model->getID();
513   return 0;
514 }
515
516 /**
517  * @brief remove the registered model
518  * @param[in] modelid model id
519  * @return 0 if no error. otherwise a negative errno
520  */
521 int
522 HostHandler::unregisterModel (uint32_t modelid)
523 {
524   return models_.remove (modelid);
525 }
526
527 /**
528  * @brief remove all registered models
529  * @return 0
530  */
531 int
532 HostHandler::unregisterModels ()
533 {
534   models_.clear ();
535   return 0;
536 }
537
538 /**
539  * @brief Set the data layout for input/output tensors
540  * @param[in] modelid The ID of model whose layouts are set
541  * @param[in] in the layout/type info for input tensors
542  * @param[in] out the layout/type info for output tensors
543  * @return @c 0 if no error. otherwise a negative error value
544  * @note if this function is not called, default layout/type will be used.
545  */
546 int
547 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
548     tensors_data_info *out)
549 {
550   Model *model = models_.find (modelid);
551   if (model == nullptr)
552     return -ENOENT;
553
554   return model->setDataInfo (in, out);
555 }
556
557 /**
558  * @brief Set the inference constraint for next NPU inferences
559  * @param[in] modelid The target model id
560  * @param[in] constraint inference constraint (e.g., timeout, priority)
561  * @return @c 0 if no error. otherwise a negative error value
562  * @note If this function is not called, default values are used.
563  */
564 int
565 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
566 {
567   Model *model = models_.find (modelid);
568   if (model == nullptr)
569     return -ENOENT;
570
571   model->setConstraint (constraint);
572
573   return 0;
574 }
575
576 /**
577  * @brief find and return model instance
578  * @param[in] modelid model id
579  * @return model instance if found. otherwise nullptr
580  */
581 Model *
582 HostHandler::getModel (uint32_t modelid)
583 {
584   return models_.find (modelid);
585 }
586
587 /** @brief dummay callback for runSync. */
588 class callbackSync {
589   public:
590     callbackSync (output_buffers *output) : output_(output), done_(false) {}
591
592     static void callback (output_buffers *output, uint64_t sequence, void *data) {
593       callbackSync *sync = static_cast<callbackSync *>(data);
594       sync->callback (output, sequence);
595     }
596
597     void callback (output_buffers *output, uint64_t sequence) {
598       if (output_ != nullptr) {
599         /** just copy internal variables of output buffers */
600         memcpy (output_, output, sizeof (output_buffers));
601       }
602       done_ = true;
603       cv_.notify_one ();
604     }
605
606     void wait () {
607       std::unique_lock<std::mutex> lock (m_);
608       cv_.wait (lock, [this]() { return done_; });
609     }
610
611   private:
612     std::mutex m_;
613     std::condition_variable cv_;
614     output_buffers *output_;
615     bool done_;
616 };
617
618 /**
619  * @brief Execute inference. Wait (block) until the output is available.
620  * @param[in] modelid The model to be inferred.
621  * @param[in] input The input data to be inferred.
622  * @param[out] output The output result.
623  * @return @c 0 if no error. otherwise a negative error value
624  */
625 int
626 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
627     output_buffers *output)
628 {
629   callbackSync sync (output);
630   int status = runAsync (modelid, input, callbackSync::callback,
631       static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
632   if (status == 0) {
633     /** sync needs to wait callback */
634     sync.wait ();
635   }
636   return status;
637 }
638
639 /**
640  * @brief Invoke NPU inference. Unblocking call.
641  * @param[in] modelid The model to be inferred.
642  * @param[in] input The input data to be inferred.
643  * @param[in] cb The output buffer handler.
644  * @param[in] cb_data The data given as a parameter to the runNPU_async call.
645  * @param[in] mode Configures how this operation works.
646  * @param[out] sequence The sequence number returned with runNPU_async.
647  * @return @c 0 if no error. otherwise a negative error value
648  */
649 int
650 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
651     npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
652 {
653   Model *model = nullptr;
654
655   if (device_->needModel()) {
656     model = getModel (modelid);
657     if (model == nullptr)
658       return -ENOENT;
659   }
660
661   device_->setAsyncMode (mode);
662   return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
663 }
664
665 /**
666  * @brief get number of available devices
667  * @param[in] type device type
668  * @return number of devices
669  */
670 int
671 HostHandler::getNumDevices (dev_type type)
672 {
673   return DriverAPI::getNumDevices (type);
674 }
675
676 /**
677  * @brief get device instance
678  * @param[out] dev device instance
679  * @param[in] type device type
680  * @param[in] id device id
681  * @return 0 if no error. otherwise a negative errno
682  */
683 int
684 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
685 {
686   int num_devices = getNumDevices (type);
687
688   /** check the validity of device id */
689   if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
690     logerr (TAG, "Invalid arguments provided\n");
691     return -ENODEV;
692   }
693
694   Device *device = Device::createInstance (type, id);
695   if (device == nullptr) {
696     logerr (TAG, "Failed to create a device with the given type\n");
697     return -EINVAL;
698   }
699
700   *dev = device;
701   /** This is just for backward-compatility; we don't guarantee its corresness */
702   latest_dev_ = *dev;
703
704   return 0;
705 }
706
707 /**
708  * @brief allocate generic buffer (just for users)
709  * @param[out] buffer buffer instance
710  * @return 0 if no error. otherwise a negative errno
711  */
712 int
713 HostHandler::allocGenericBuffer (generic_buffer *buffer)
714 {
715   if (buffer == NULL)
716     return -EINVAL;
717
718   if (buffer->size == 0) {
719     logerr (TAG, "Invalid size\n");
720     return -EINVAL;
721   }
722
723   if (buffer->size > UINT32_MAX) {
724     logerr (TAG, "Don't support such a large size");
725     return -ENOMEM;
726   }
727
728   switch (buffer->type) {
729     case BUFFER_FILE:
730       /* nothing to do */
731       if (buffer->filepath == nullptr)
732         return -EINVAL;
733       break;
734     case BUFFER_MAPPED:
735     case BUFFER_DMABUF:
736     {
737       /* now, npu-engine always provides dmabuf-based allocation */
738       HWmem *hwmem;
739       int status = device_->allocMemory (buffer->size, &hwmem);
740       if (status != 0)
741         return status;
742
743       buffer->dmabuf = hwmem->getDmabuf();
744       buffer->offset = hwmem->getOffset();
745       buffer->addr = hwmem->getData();
746     } break;
747     default:
748       return -EINVAL;
749   }
750
751   return 0;
752 }
753
754 /**
755  * @brief deallocate generic buffer (just for users)
756  * @param[in] buffer buffer instance
757  * @return 0 if no error. otherwise a negative errno
758  */
759 int
760 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
761 {
762   if (buffer == NULL)
763     return -EINVAL;
764
765   int status;
766   switch (buffer->type) {
767     case BUFFER_FILE:
768       status = 0; /** always true cuz nothing to do */
769       break;
770     case BUFFER_MAPPED:
771     case BUFFER_DMABUF:
772       status = device_->deallocMemory (buffer->dmabuf);
773       break;
774     default:
775       status = -EINVAL;
776       break;
777   }
778
779   return status;
780 }
781
782 /**
783  * @brief allocate multiple generic buffers (just for users)
784  * @param[out] buffers multi-buffer instance
785  * @return 0 if no error. otherwise a negative errno
786  */
787 int
788 HostHandler::allocGenericBuffer (generic_buffers *buffers)
789 {
790   if (buffers == NULL || buffers->num_buffers < 1)
791     return -EINVAL;
792
793   buffer_types type = buffers->bufs[0].type;
794   if (type == BUFFER_FILE)
795     return 0;
796
797   uint64_t total_size = 0;
798   for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
799     total_size += buffers->bufs[idx].size;
800
801   uint64_t first_size = buffers->bufs[0].size;
802   buffers->bufs[0].size = total_size;
803   int status = allocGenericBuffer (&buffers->bufs[0]);
804   if (status != 0)
805     return status;
806
807   uint64_t offset = first_size;
808   for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
809     buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
810     buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
811     buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
812     buffers->bufs[idx].type = type;
813
814     offset += buffers->bufs[idx].size;
815   }
816
817   buffers->bufs[0].size = first_size;
818
819   return 0;
820 }
821
822 /**
823  * @brief deallocate multiple generic buffers (just for users)
824  * @param[in] buffers multi-buffer instance
825  * @return 0 if no error. otherwise a negative errno
826  */
827 int
828 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
829 {
830   if (buffers == NULL || buffers->num_buffers < 1)
831     return -EINVAL;
832
833   return deallocGenericBuffer (&buffers->bufs[0]);
834 }
835
836 /** implement methods of Device class */
837
838 /** @brief constructor of device */
839 Device::Device (dev_type type, int id, bool need_model)
840   : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
841     mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
842 {
843 }
844
845 /**
846  * @brief create device instance depending on device type and id
847  * @param[in] type device type
848  * @param[in] id device id
849  * @return device instance
850  */
851 Device *
852 Device::createInstance (dev_type type, int id)
853 {
854   Device *device = nullptr;
855
856   switch (type & DEVICETYPE_MASK) {
857     case DEVICETYPE_TRIV:
858       device = new TrinityVision (id);
859       break;
860     case DEVICETYPE_TRIV2:
861       device = new TrinityVision2 (id);
862       break;
863     case DEVICETYPE_TRIA:
864       device = new TrinityAsr (id);
865       break;
866     default:
867       break;
868   }
869
870   if (device != nullptr && device->init () != 0) {
871     delete device;
872     device = nullptr;
873   }
874
875   return device;
876 }
877
878 /**
879  * @brief device initialization
880  * @return 0 if no error, otherwise a negative errno
881  * @note Init failures come from createDriverAPI() only.
882  */
883 int
884 Device::init ()
885 {
886   /** should be initilizaed only once */
887   if (!atomic_flag_.test_and_set()) {
888     /** create the corresponding driver API */
889     api_ = DriverAPI::createDriverAPI (type_, id_);
890     if (api_.get() == nullptr) {
891       atomic_flag_.clear();
892       logerr (TAG, "Failed to create driver API\n");
893       return -EINVAL;
894     }
895
896     handler_.reset (new HostHandler (this));
897     scheduler_.reset (new Scheduler (api_.get()));
898     mem_ = MemAllocator::createInstance (api_.get());
899
900     initialized_ = true;  /** c++11 does not provide test() of atomic flag */
901   }
902
903   return 0;
904 }
905
906 /**
907  * @brief stop all requests from this device
908  * @param[in] force_stop indicate the schedduler waits until to handle previous requests
909  * @return 0 if no error, otherwise a negative errno
910  */
911 int
912 Device::stop (bool force_stop)
913 {
914   if (!initialized ()) {
915     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
916     return -EPERM;
917   }
918
919   Request *req = new Request (NPUINPUT_STOP);
920   req->setForceStop (force_stop);
921   return scheduler_->submitRequest (req);
922 }
923
924 /**
925  * @brief allocate generic memory buffer
926  * @param[out] hwmem_ptr hwmem instance pointer
927  * @return 0 if no error, otherwise a negative errno
928  */
929 int
930 Device::allocMemory (size_t size, HWmem ** hwmem_ptr)
931 {
932   if (!initialized ()) {
933     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
934     return -EPERM;
935   }
936
937   if (size == 0 || hwmem_ptr == nullptr)
938     return -EINVAL;
939
940   HWmem *hwmem = mem_->allocMemory (size);
941   if (hwmem == nullptr)
942     return -ENOMEM;
943
944   *hwmem_ptr = hwmem;
945   return 0;
946 }
947
948 /**
949  * @brief deallocate generic memory buffer
950  * @param[in] dmabuf_fd dmabuf file descriptor
951  * @return 0 if no error, otherwise a negative errno
952  */
953 int
954 Device::deallocMemory (int dmabuf_fd)
955 {
956   if (!initialized ()) {
957     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
958     return -EPERM;
959   }
960
961   return mem_->deallocMemory (dmabuf_fd);
962 }
963
964 /**
965  * @brief extract the buffer instance from input generic buffers
966  * @param[in] meta the model metadata
967  * @param[in] input the input generic buffers
968  * @return the buffer instance
969  */
970 Buffer *
971 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
972 {
973   if (meta == nullptr ||
974       meta->getInputNum() != input->num_buffers) {
975     logerr (TAG, "Invalid metadata info provided\n");
976     return nullptr;
977   }
978
979   Buffer * buffer = mem_->allocBuffer ();
980   if (buffer != nullptr) {
981     const generic_buffer *first = &input->bufs[0];
982     if (first->type == BUFFER_DMABUF) {
983       buffer->setDmabuf (first->dmabuf);
984       buffer->setOffset (first->offset);
985       buffer->setSize (meta->getBufferSize());
986     } else {
987       int status = buffer->alloc (meta->getBufferSize ());
988       if (status != 0) {
989         logerr (TAG, "Failed to allocate buffer: %d\n", status);
990         delete buffer;
991         return nullptr;
992       }
993     }
994   }
995
996   try {
997     buffer->createTensors (meta);
998   } catch (std::bad_alloc& bad) {
999     logerr (TAG, "Failed to allocate buffer: No enough memory\n");
1000     delete buffer;
1001     buffer = nullptr;
1002   } catch (std::exception& exp) {
1003     logerr (TAG, "Failed to allocate buffer: %s\n", exp.what());
1004     delete buffer;
1005     buffer = nullptr;
1006   }
1007   return buffer;
1008 }
1009
1010 /**
1011  * @brief implementation of TRIV's setModel ()
1012  * @param[in] model_buf the model generic buffer
1013  * @param[out] model the model instance
1014  * @return 0 if no error, otherwise a negative errno
1015  */
1016 int
1017 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1018 {
1019   if (!initialized ()) {
1020     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1021     return -EPERM;
1022   }
1023
1024   if (model_buf == nullptr || model_ptr == nullptr)
1025     return -EINVAL;
1026
1027   Model *model = mem_->allocModel ();
1028   if (model == nullptr) {
1029     logerr (TAG, "Failed to allocate model\n");
1030     return -ENOMEM;
1031   }
1032
1033   int status = 0;
1034   switch (model_buf->type) {
1035   case BUFFER_DMABUF:
1036     model->setDmabuf (model_buf->dmabuf);
1037     model->setOffset (model_buf->offset);
1038     model->setSize (model_buf->size);
1039     break;
1040   case BUFFER_FILE:
1041   case BUFFER_MAPPED:
1042     status = model->alloc (model_buf->size);
1043     if (status != 0) {
1044       logerr (TAG, "Failed to allocate model: %d\n", status);
1045       goto delete_exit;
1046     }
1047
1048     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1049     if (status != 0) {
1050       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1051       goto delete_exit;
1052     }
1053     break;
1054   default:
1055     status = -EINVAL;
1056     goto delete_exit;
1057   }
1058
1059   status = model->setMetadata (model->getData());
1060   if (status != 0)
1061     goto delete_exit;
1062
1063   model_config_t config;
1064   config.dmabuf_id = model->getDmabuf();
1065   config.program_size = model->getMetadata()->getProgramSize();
1066   config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
1067   config.weight_offset_addr = config.program_offset_addr + config.program_size;
1068
1069   status = api_->setModel (&config);
1070   if (status != 0)
1071     goto delete_exit;
1072
1073   *model_ptr = model;
1074   return status;
1075
1076 delete_exit:
1077   delete model;
1078   return status;
1079 }
1080
1081
1082 /**
1083  * @brief implementation of TRIV's run()
1084  * @param[in] opmode input opmode
1085  * @param[in] model the model instance
1086  * @param[in] input generic buffers of input data
1087  * @param[in] cb the output callback
1088  * @param[in] cb_data the output callback data
1089  * @param[out] sequence The sequence number returned with runNPU_async.
1090  */
1091 int
1092 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1093     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1094     uint64_t *sequence)
1095 {
1096   if (!initialized ()) {
1097     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1098     return -EPERM;
1099   }
1100
1101   if (opmode != NPUINPUT_HOST) {
1102     logerr (TAG, "TRIV supports only host inputservice\n");
1103     return -EINVAL;
1104   }
1105
1106   if (model == nullptr || input == nullptr) {
1107     logerr (TAG, "TRIV requires both model and input buffers\n");
1108     return -EINVAL;
1109   }
1110
1111   Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1112   if (buffer == nullptr) {
1113     logerr (TAG, "Failed to extract buffer instance\n");
1114     return -EINVAL;
1115   }
1116
1117   for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1118     auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1119         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1120     int status = comm_.extractGenericBuffer (&input->bufs[idx],
1121         buffer->getInputTensor(idx)->getData(), func);
1122     if (status != 0) {
1123       logerr (TAG, "Failed to feed input buffer: %d\n", status);
1124       return status;
1125     }
1126   }
1127
1128   /** this device uses CMA buffer */
1129
1130   Request *req = new Request (opmode);
1131   req->setModel (model);
1132   req->setBuffer (buffer);
1133
1134   if (cb != nullptr)
1135     req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1136
1137   if (sequence != nullptr)
1138     *sequence = req->getID();
1139
1140   return scheduler_->submitRequest (req);
1141 }
1142
1143 /**
1144  * @brief callback of TRIV2 request
1145  * @param[in] req the request instance
1146  * @param[in] cb callback for completion
1147  * @param[in] cb_data callback data
1148  * @note The callback invoke does not gurantee the request was successful
1149  * @todo Check the request failures
1150  */
1151 void
1152 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1153 {
1154   const Model *model = req->getModel ();
1155   Buffer *buffer = req->getBuffer ();
1156   output_buffers output = {
1157     .num_buffers = buffer->getOutputNum ()
1158   };
1159
1160   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1161     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1162
1163     output.bufs[idx].type = BUFFER_MAPPED;
1164     output.bufs[idx].size = output_tensor_size;
1165     /** user needs to free this */
1166     output.bufs[idx].addr = malloc (output_tensor_size);
1167
1168     auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1169         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1170     int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1171         &output.bufs[idx], func);
1172     if (status != 0) {
1173       logerr (TAG, "Failed to return output buffer: %d\n", status);
1174     }
1175   }
1176
1177   cb (&output, req->getID(), cb_data);
1178 }
1179
1180 /** @brief implementation of TRIV2's setModel (): WIP */
1181 int
1182 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1183 {
1184   if (!initialized ()) {
1185     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1186     return -EPERM;
1187   }
1188
1189   /** TODO: model's weight values are stored in segments */
1190   *model_ptr = nullptr;
1191   return -EINVAL;
1192 }
1193
1194 /** @brief implementation of TRIV2's run(): WIP */
1195 int
1196 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1197     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1198     uint64_t *sequence)
1199 {
1200   if (!initialized ()) {
1201     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1202     return -EPERM;
1203   }
1204
1205   if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1206     return -EINVAL;
1207
1208   /** this device uses segment table */
1209
1210   Request *req = new Request (opmode);
1211   req->setModel (model);
1212 #if 0
1213   req->setSegmentTable (segt);
1214 #endif
1215   req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1216
1217   if (sequence)
1218     *sequence = req->getID();
1219
1220   return scheduler_->submitRequest (req);
1221 }
1222
1223 /** @brief callback of TRIV2 request: WIP */
1224 void
1225 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1226 {
1227 }
1228
1229 /** @brief implementation of TRIA's run(): WIP */
1230 int
1231 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1232     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1233     uint64_t *sequence)
1234 {
1235   if (!initialized ()) {
1236     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1237     return -EPERM;
1238   }
1239
1240   if (opmode != NPUINPUT_HOST)
1241     return -EINVAL;
1242
1243   /** ASR does not require model and support only a single tensor */
1244   const generic_buffer *first_buf = &input->bufs[0];
1245   Buffer * buffer = mem_->allocBuffer ();
1246   int status;
1247   if (first_buf->type == BUFFER_DMABUF) {
1248     buffer->setDmabuf (first_buf->dmabuf);
1249     buffer->setOffset (first_buf->offset);
1250     buffer->setSize (first_buf->size);
1251   } else {
1252     status = buffer->alloc (first_buf->size);
1253     if (status != 0) {
1254       delete buffer;
1255       return status;
1256     }
1257   }
1258   buffer->createTensors ();
1259
1260   status = comm_.extractGenericBuffer (first_buf,
1261       buffer->getInputTensor(0)->getData(), nullptr);
1262   if (status != 0)
1263     return status;
1264
1265   Request *req = new Request (opmode);
1266   req->setBuffer (buffer);
1267   req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1268
1269   if (sequence)
1270     *sequence = req->getID();
1271
1272   return scheduler_->submitRequest (req);
1273 }
1274
1275 /** @brief callback of TRIA request: WIP */
1276 void
1277 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1278 {
1279 }
1280
1281 /** Implement data manipulation (each device may have different impl.) */
1282
1283 #ifdef ENABLE_MANIP
1284
1285 #define do_quantized_memcpy(type) do {\
1286     idx = 0;\
1287     if (quant) {\
1288       while (idx < num_elems) {\
1289           val = ((type *) src)[idx];\
1290           val = val / _scale;\
1291           val += _zero_point;\
1292           val = (val > 255.0) ? 255.0 : 0.0;\
1293           ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1294       }\
1295     } else {\
1296       while (idx < num_elems) {\
1297           val = *(uint8_t *) src;\
1298           val -= _zero_point;\
1299           val *= _scale;\
1300           ((type *) dst)[idx++] = (type) val;\
1301           dst = (void*)(((uint8_t *) dst) + data_size);\
1302           src = (void*)(((uint8_t *) src) + 1);\
1303       }\
1304     }\
1305   } while (0)
1306
1307 /**
1308  * @brief memcpy during quantization
1309  */
1310 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1311     void *dst, const void *src, uint32_t num_elems)
1312 {
1313   double _scale = (double) scale;
1314   double _zero_point = (double) zero_point;
1315   double val;
1316   uint32_t data_size = get_data_size (type);
1317   uint32_t idx;
1318
1319   switch (type) {
1320     case DATA_TYPE_INT8:
1321       do_quantized_memcpy (int8_t);
1322       break;
1323     case DATA_TYPE_UINT8:
1324       do_quantized_memcpy (uint8_t);
1325       break;
1326     case DATA_TYPE_INT16:
1327       do_quantized_memcpy (int16_t);
1328       break;
1329     case DATA_TYPE_UINT16:
1330       do_quantized_memcpy (uint16_t);
1331       break;
1332     case DATA_TYPE_INT32:
1333       do_quantized_memcpy (int32_t);
1334       break;
1335     case DATA_TYPE_UINT32:
1336       do_quantized_memcpy (uint32_t);
1337       break;
1338     case DATA_TYPE_INT64:
1339       do_quantized_memcpy (int64_t);
1340       break;
1341     case DATA_TYPE_UINT64:
1342       do_quantized_memcpy (uint64_t);
1343       break;
1344     case DATA_TYPE_FLOAT32:
1345       do_quantized_memcpy (float);
1346       break;
1347     case DATA_TYPE_FLOAT64:
1348       do_quantized_memcpy (double);
1349       break;
1350     default:
1351       logerr (TAG, "Unsupported datatype %d\n", type);
1352   }
1353 }
1354
1355 /**
1356  * @brief perform data manipulation
1357  * @param[in] model model instance
1358  * @param[in] idx tensor index
1359  * @param[in] is_input indicate it's input manipulation
1360  * @param[out] dst destination buffer
1361  * @param[in] src source buffer (feature map)
1362  * @param[in] size size to be copied
1363  * @return size of memory copy if no error, otherwise zero
1364  *
1365  * @note the input data format should be NHWC
1366  * @detail rules for the memory address of activations in NPU HW.
1367  *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1368  *
1369  * 1) Special case (depth == 3)
1370  * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1371  *
1372  * 2) Common case
1373  * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1374  *
1375  * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1376  */
1377 size_t
1378 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1379     void *dst, void *src, size_t size)
1380 {
1381   const Metadata *meta = model->getMetadata();
1382   const tensor_data_info* info;
1383   const uint32_t *dims;
1384   uint32_t zero_point;
1385   float scale;
1386
1387   /** extract required information from the metadata */
1388   if (is_input) {
1389     if (idx >= meta->getInputNum()) {
1390       logerr (TAG, "Wrong information for input tensors in metadata\n");
1391       return 0;
1392     }
1393
1394     info = model->getInputDataInfo (idx);
1395     dims = meta->getInputDims (idx);
1396     zero_point = meta->getInputQuantZero (idx);
1397     scale = meta->getInputQuantScale (idx);
1398   } else {
1399     if (idx >= meta->getOutputNum()) {
1400       logerr (TAG, "Wrong information for output tensors in metadata\n");
1401       return 0;
1402     }
1403
1404     info = model->getOutputDataInfo (idx);
1405     dims = meta->getOutputDims (idx);
1406     zero_point = meta->getOutputQuantZero (idx);
1407     scale = meta->getOutputQuantScale (idx);
1408   }
1409
1410   if (info == nullptr) {
1411     logerr (TAG, "Unmatched tensors info\n");
1412     return 0;
1413   }
1414
1415   uint32_t batch = dims[0];
1416   uint32_t height = dims[1];
1417   uint32_t width = dims[2];
1418   uint32_t depth = dims[3];
1419
1420   uint32_t data_size = get_data_size (info->type);
1421   if (data_size == 0) {
1422     logerr (TAG, "Invalid data size\n");
1423     return 0;
1424   }
1425
1426   bool need_quantization = false;
1427   /**
1428    * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1429    * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1430    */
1431   if (info->type != DATA_TYPE_SRNPU) {
1432     assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1433
1434     if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1435         !(zero_point == default_zero_point && scale == default_scale))
1436       need_quantization = true;
1437   }
1438
1439   /** check data manipulation is required */
1440   if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1441     uint32_t MPA_L = DATA_GRANULARITY;
1442     uint32_t n, h, w, d;
1443     uint32_t std_offset;  /* standard offset in NHWC data format */
1444     uint32_t npu_offset;  /* npu offset in NPU HW data format*/
1445     uint32_t src_offset;
1446     uint32_t dst_offset;
1447     uint32_t slice_size;
1448
1449     /* @todo we currently support only NHWC */
1450     if (info->layout != DATA_LAYOUT_NHWC) {
1451       logerr (TAG, "data manipulation is supported for NHWC only\n");
1452       return 0;
1453     }
1454
1455     for (n = 0; n < batch; n++) {
1456       for (h = 0; h < height; h++) {
1457         for (w = 0; w < width; w++) {
1458           for (d = 0; d < depth; d += MPA_L) {
1459             std_offset = d + depth * (w + width * (h + n * height));
1460             npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1461             slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1462
1463             if (is_input) {
1464               src_offset = std_offset * data_size;
1465               dst_offset = npu_offset;
1466             } else {
1467               src_offset = npu_offset;
1468               dst_offset = std_offset * data_size;
1469             }
1470
1471             /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1472             if (need_quantization) {
1473               memcpy_with_quant (is_input, info->type, scale, zero_point,
1474                   static_cast<char*>(dst) + dst_offset,
1475                   static_cast<char*>(src) + src_offset,
1476                   slice_size);
1477             } else {
1478               memcpy (
1479                   static_cast<char*>(dst) + dst_offset,
1480                   static_cast<char*>(src) + src_offset,
1481                   slice_size);
1482             }
1483           }
1484         }
1485       }
1486     }
1487   } else if (need_quantization) {
1488     /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1489     memcpy_with_quant (is_input, info->type, scale, zero_point,
1490         dst, src, is_input ? size / data_size : size);
1491   } else {
1492     memcpy (dst, src, size);
1493   }
1494
1495   return size;
1496 }
1497
1498 #else
1499
1500 size_t
1501 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1502     void *dst, void *src, size_t size)
1503 {
1504   memcpy (dst, src, size);
1505   return size;
1506 }
1507
1508 #endif
1509
1510 /** other device types don't have data manip impl. yet */
1511
1512 size_t
1513 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1514     void *dst, void *src, size_t size)
1515 {
1516   memcpy (dst, src, size);
1517   return size;
1518 }
1519
1520 size_t
1521 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1522     void *dst, void *src, size_t size)
1523 {
1524   memcpy (dst, src, size);
1525   return size;
1526 }