[Coverage] Increase the code coverage by excluding some files
[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 Allocate a buffer for NPU model with the requested buffer type.
195  * @param[in] dev The NPU device handle
196  * @param[in/out] Buffer the buffer pointer where memory is allocated.
197  * @return 0 if no error, otherwise a negative errno.
198  */
199 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
200 {
201   INIT_HOST_HANDLER (host_handler, dev);
202
203   return host_handler->allocGenericBuffer (buffer);
204 }
205
206 /**
207  * @brief Free the buffer and remove the address mapping.
208  * @param[in] dev The NPU device handle
209  * @param[in] buffer the model buffer
210  * @return 0 if no error, otherwise a negative errno.
211  */
212 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
213 {
214   INIT_HOST_HANDLER (host_handler, dev);
215
216   return host_handler->deallocGenericBuffer (buffer);
217 }
218
219 /**
220  * @brief Allocate a buffer for NPU input with the requested buffer type.
221  * @param[in] dev The NPU device handle
222  * @param[in/out] Buffer the buffer pointer where memory is allocated.
223  * @return 0 if no error, otherwise a negative errno.
224  * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
225  *       calls of allocInputBuffer() don't gurantee contiguous allocations between them.
226  */
227 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
228 {
229   INIT_HOST_HANDLER (host_handler, dev);
230
231   return host_handler->allocGenericBuffer (buffer);
232 }
233
234 /**
235  * @brief Free the buffer and remove the address mapping.
236  * @param[in] dev The NPU device handle
237  * @param[in] buffer the input buffer
238  * @return 0 if no error, otherwise a negative errno.
239  */
240 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
241 {
242   INIT_HOST_HANDLER (host_handler, dev);
243
244   return host_handler->deallocGenericBuffer (buffer);
245 }
246
247 /**
248  * @brief Allocate input buffers, which have multiple instances of generic_buffer
249  * @param[in] dev The NPU device handle
250  * @param[in/out] input input buffers.
251  * @return 0 if no error, otherwise a negative errno.
252  * @note it reuses allocInputBuffer().
253  * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
254  *          memory mapping for multiple tensors (in a single inference, not batch size).
255  */
256 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
257 {
258   INIT_HOST_HANDLER (host_handler, dev);
259
260   return host_handler->allocGenericBuffer (input);
261 }
262
263 /**
264  * @brief Free input buffers allocated by allocInputBuffers().
265  * @param[in] dev The NPU device handle
266  * @param[in/out] input input buffers.
267  * @note it reuses cleanInputbuffer().
268  * @return 0 if no error, otherwise a negative errno.
269  */
270 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
271 {
272   INIT_HOST_HANDLER (host_handler, dev);
273
274   return host_handler->deallocGenericBuffer (input);
275 }
276
277 /**
278  * @brief get the current memory status for the given device
279  * @param[in] dev The NPU device handle
280  * @param[out] alloc_total The size of allocated memory until now
281  * @param[out] free_total The size of freed memory until now
282  * @return @c 0 if no error. otherwise a negatice error value
283  */
284 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
285 {
286   INIT_HOST_HANDLER (host_handler, dev);
287
288   return host_handler->getMemoryStatus (alloc_total, free_total);
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 /** implement methods of HostHandler class */
367
368 /** @brief host handler constructor */
369 HostHandler::HostHandler (Device *device)
370   : device_(device),
371     /* ignored as we don't use double buffering anymore, but for backward-compatibility */
372     async_mode_ (NPUASYNC_WAIT)
373 {
374 }
375
376 /** @brief host handler destructor */
377 HostHandler::~HostHandler ()
378 {
379 }
380
381 /**
382  * @brief register model from generic buffer
383  * @param[in] model_buf model buffer
384  * @param[out] modelid model id
385  * @return 0 if no error. otherwise a negative errno
386  */
387 int
388 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
389 {
390   if (model_buf == nullptr || modelid == nullptr) {
391     logerr (TAG, "Invalid arguments given\n");
392     return -EINVAL;
393   }
394
395   Model *model = nullptr;
396   int status = device_->setModel (model_buf, &model);
397   if (status != 0) {
398     logerr (TAG, "Failed to set model: %d\n", status);
399     return status;
400   }
401
402   assert (model != nullptr);
403
404   status = models_.insert (model->getID(), model);
405   if (status != 0) {
406     logerr (TAG, "Failed to insert model id\n");
407     delete model;
408     return status;
409   }
410
411   *modelid = model->getID();
412   return 0;
413 }
414
415 /**
416  * @brief remove the registered model
417  * @param[in] modelid model id
418  * @return 0 if no error. otherwise a negative errno
419  */
420 int
421 HostHandler::unregisterModel (uint32_t modelid)
422 {
423   Model *model = models_.find (modelid);
424   if (model == nullptr)
425     return -ENOENT;
426
427   int status = device_->unsetModel (model);
428   if (status != 0) {
429     logerr (TAG, "Failed to unset model: %d\n", status);
430     return status;
431   }
432
433   return models_.remove (modelid);
434 }
435
436 /**
437  * @brief remove all registered models
438  * @return 0
439  */
440 int
441 HostHandler::unregisterModels ()
442 {
443   models_.clear ();
444   return 0;
445 }
446
447 /**
448  * @brief Set the data layout for input/output tensors
449  * @param[in] modelid The ID of model whose layouts are set
450  * @param[in] in the layout/type info for input tensors
451  * @param[in] out the layout/type info for output tensors
452  * @return @c 0 if no error. otherwise a negative error value
453  * @note if this function is not called, default layout/type will be used.
454  */
455 int
456 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
457     tensors_data_info *out)
458 {
459   Model *model = models_.find (modelid);
460   if (model == nullptr)
461     return -ENOENT;
462
463   return model->setDataInfo (in, out);
464 }
465
466 /**
467  * @brief Set the inference constraint for next NPU inferences
468  * @param[in] modelid The target model id
469  * @param[in] constraint inference constraint (e.g., timeout, priority)
470  * @return @c 0 if no error. otherwise a negative error value
471  * @note If this function is not called, default values are used.
472  */
473 int
474 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
475 {
476   Model *model = models_.find (modelid);
477   if (model == nullptr)
478     return -ENOENT;
479
480   model->setConstraint (constraint);
481
482   return 0;
483 }
484
485 /**
486  * @brief find and return model instance
487  * @param[in] modelid model id
488  * @return model instance if found. otherwise nullptr
489  */
490 Model *
491 HostHandler::getModel (uint32_t modelid)
492 {
493   return models_.find (modelid);
494 }
495
496 /** @brief dummay callback for runSync. */
497 class callbackSync {
498   public:
499     callbackSync (output_buffers *output) : output_(output), done_(false) {}
500
501     static void callback (output_buffers *output, uint64_t sequence, void *data) {
502       callbackSync *sync = static_cast<callbackSync *>(data);
503       sync->callback (output, sequence);
504     }
505
506     void callback (output_buffers *output, uint64_t sequence) {
507       if (output_ != nullptr) {
508         /** just copy internal variables of output buffers */
509         memcpy (output_, output, sizeof (output_buffers));
510       }
511       done_ = true;
512       cv_.notify_one ();
513     }
514
515     void wait () {
516       std::unique_lock<std::mutex> lock (m_);
517       cv_.wait (lock, [this]() { return done_; });
518     }
519
520   private:
521     std::mutex m_;
522     std::condition_variable cv_;
523     output_buffers *output_;
524     bool done_;
525 };
526
527 /**
528  * @brief Execute inference. Wait (block) until the output is available.
529  * @param[in] modelid The model to be inferred.
530  * @param[in] input The input data to be inferred.
531  * @param[out] output The output result.
532  * @return @c 0 if no error. otherwise a negative error value
533  */
534 int
535 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
536     output_buffers *output)
537 {
538   callbackSync sync (output);
539   int status = runAsync (modelid, input, callbackSync::callback,
540       static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
541   if (status == 0) {
542     /** sync needs to wait callback */
543     sync.wait ();
544   }
545   return status;
546 }
547
548 /**
549  * @brief Invoke NPU inference. Unblocking call.
550  * @param[in] modelid The model to be inferred.
551  * @param[in] input The input data to be inferred.
552  * @param[in] cb The output buffer handler.
553  * @param[in] cb_data The data given as a parameter to the runNPU_async call.
554  * @param[in] mode Configures how this operation works.
555  * @param[out] sequence The sequence number returned with runNPU_async.
556  * @return @c 0 if no error. otherwise a negative error value
557  */
558 int
559 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
560     npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
561 {
562   Model *model = nullptr;
563
564   if (device_->needModel()) {
565     model = getModel (modelid);
566     if (model == nullptr)
567       return -ENOENT;
568   }
569
570   device_->setAsyncMode (mode);
571   return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
572 }
573
574 /**
575  * @brief get number of available devices
576  * @param[in] type device type
577  * @return number of devices
578  */
579 int
580 HostHandler::getNumDevices (dev_type type)
581 {
582   return DriverAPI::getNumDevices (type);
583 }
584
585 /**
586  * @brief get device instance
587  * @param[out] dev device instance
588  * @param[in] type device type
589  * @param[in] id device id
590  * @return 0 if no error. otherwise a negative errno
591  */
592 int
593 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
594 {
595   int num_devices = getNumDevices (type);
596
597   /** check the validity of device id */
598   if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
599     logerr (TAG, "Invalid arguments provided\n");
600     return -ENODEV;
601   }
602
603   Device *device = Device::createInstance (type, id);
604   if (device == nullptr) {
605     logerr (TAG, "Failed to create a device with the given type\n");
606     return -EINVAL;
607   }
608
609   *dev = device;
610   /** This is just for backward-compatility; we don't guarantee its corresness */
611   latest_dev_ = *dev;
612
613   return 0;
614 }
615
616 /**
617  * @brief allocate generic buffer (just for users)
618  * @param[out] buffer buffer instance
619  * @return 0 if no error. otherwise a negative errno
620  */
621 int
622 HostHandler::allocGenericBuffer (generic_buffer *buffer)
623 {
624   if (buffer == NULL)
625     return -EINVAL;
626
627   if (buffer->size == 0) {
628     logerr (TAG, "Invalid size\n");
629     return -EINVAL;
630   }
631
632   if (buffer->size > UINT32_MAX) {
633     logerr (TAG, "Don't support such a large size");
634     return -ENOMEM;
635   }
636
637   switch (buffer->type) {
638     case BUFFER_FILE:
639       /* nothing to do */
640       if (buffer->filepath == nullptr)
641         return -EINVAL;
642       break;
643     case BUFFER_MAPPED:
644     case BUFFER_DMABUF:
645     {
646       /* now, npu-engine always provides dmabuf-based allocation */
647       void *addr = nullptr;
648       int dmabuf = device_->allocMemory (buffer->size, &addr);
649       if (dmabuf < 0)
650         return dmabuf;
651
652       buffer->dmabuf = dmabuf;
653       buffer->offset = 0;
654       buffer->addr = addr;
655     } break;
656     default:
657       return -EINVAL;
658   }
659
660   return 0;
661 }
662
663 /**
664  * @brief deallocate generic buffer (just for users)
665  * @param[in] buffer buffer instance
666  * @return 0 if no error. otherwise a negative errno
667  */
668 int
669 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
670 {
671   if (buffer == NULL)
672     return -EINVAL;
673
674   int status;
675   switch (buffer->type) {
676     case BUFFER_FILE:
677       status = 0; /** always true cuz nothing to do */
678       break;
679     case BUFFER_MAPPED:
680     case BUFFER_DMABUF:
681       status = device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
682       break;
683     default:
684       status = -EINVAL;
685       break;
686   }
687
688   return status;
689 }
690
691 /**
692  * @brief allocate multiple generic buffers (just for users)
693  * @param[out] buffers multi-buffer instance
694  * @return 0 if no error. otherwise a negative errno
695  */
696 int
697 HostHandler::allocGenericBuffer (generic_buffers *buffers)
698 {
699   if (buffers == NULL || buffers->num_buffers < 1)
700     return -EINVAL;
701
702   buffer_types type = buffers->bufs[0].type;
703   if (type == BUFFER_FILE)
704     return 0;
705
706   uint64_t total_size = 0;
707   for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
708     total_size += buffers->bufs[idx].size;
709
710   uint64_t first_size = buffers->bufs[0].size;
711   buffers->bufs[0].size = total_size;
712   int status = allocGenericBuffer (&buffers->bufs[0]);
713   if (status != 0)
714     return status;
715
716   uint64_t offset = first_size;
717   for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
718     buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
719     buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
720     buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
721     buffers->bufs[idx].type = type;
722
723     offset += buffers->bufs[idx].size;
724   }
725
726   buffers->bufs[0].size = first_size;
727
728   return 0;
729 }
730
731 /**
732  * @brief deallocate multiple generic buffers (just for users)
733  * @param[in] buffers multi-buffer instance
734  * @return 0 if no error. otherwise a negative errno
735  */
736 int
737 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
738 {
739   if (buffers == NULL || buffers->num_buffers < 1)
740     return -EINVAL;
741
742   return deallocGenericBuffer (&buffers->bufs[0]);
743 }
744
745 /**
746  * @brief get the current memory status
747  * @param[out] alloc_total The size of allocated memory until now
748  * @param[out] free_total The size of freed memory until now
749  * @return 0 if no error. otherwise a negatice error value
750  */
751 int
752 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
753 {
754   /** API is always set in initialize () */
755   const DriverAPI * api = device_->getDriverAPI ();
756   assert (api != nullptr);
757
758   return api->getMemoryStatus (alloc_total, free_total);
759 }
760
761 /** implement methods of Device class */
762
763 /** @brief constructor of device */
764 Device::Device (dev_type type, int id, bool need_model)
765   : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
766     mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
767 {
768 }
769
770 /**
771  * @brief create device instance depending on device type and id
772  * @param[in] type device type
773  * @param[in] id device id
774  * @return device instance
775  */
776 Device *
777 Device::createInstance (dev_type type, int id)
778 {
779   Device *device = nullptr;
780
781   switch (type & DEVICETYPE_MASK) {
782     case DEVICETYPE_TRIV:
783       device = new TrinityVision (id);
784       break;
785     case DEVICETYPE_TRIV2:
786       device = new TrinityVision2 (id);
787       break;
788     case DEVICETYPE_TRIA:
789       device = new TrinityAsr (id);
790       break;
791     default:
792       break;
793   }
794
795   if (device != nullptr && device->init () != 0) {
796     delete device;
797     device = nullptr;
798   }
799
800   return device;
801 }
802
803 /**
804  * @brief device initialization
805  * @return 0 if no error, otherwise a negative errno
806  * @note Init failures come from createDriverAPI() only.
807  */
808 int
809 Device::init ()
810 {
811   /** should be initilizaed only once */
812   if (!atomic_flag_.test_and_set()) {
813     /** create the corresponding driver API */
814     api_ = DriverAPI::createDriverAPI (type_, id_);
815     if (api_.get() == nullptr) {
816       atomic_flag_.clear();
817       logerr (TAG, "Failed to create driver API\n");
818       return -EINVAL;
819     }
820
821     handler_.reset (new HostHandler (this));
822     scheduler_.reset (new Scheduler (api_.get()));
823     mem_ = MemAllocator::createInstance (api_.get());
824
825     initialized_ = true;  /** c++11 does not provide test() of atomic flag */
826   }
827
828   return 0;
829 }
830
831 /**
832  * @brief stop all requests from this device
833  * @param[in] force_stop indicate the schedduler waits until to handle previous requests
834  * @return 0 if no error, otherwise a negative errno
835  */
836 int
837 Device::stop (bool force_stop)
838 {
839   if (!initialized ()) {
840     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
841     return -EPERM;
842   }
843
844   Request *req = new Request (NPUINPUT_STOP);
845   req->setForceStop (force_stop);
846   return scheduler_->submitRequest (req);
847 }
848
849 /**
850  * @brief allocate generic memory buffer
851  * @param[in] size the size to allocate
852  * @param[out] addr the mapped address
853  * @return dmabuf fd if no error, otherwise a negative errno
854  */
855 int
856 Device::allocMemory (size_t size, void **addr)
857 {
858   if (!initialized ()) {
859     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
860     return -EPERM;
861   }
862
863   if (size == 0 || addr == nullptr) {
864     logerr (TAG, "Invalid arguments\n");
865     return -EINVAL;
866   }
867
868   return mem_->allocMemory (size, addr);
869 }
870
871 /**
872  * @brief deallocate generic memory buffer
873  * @param[in] dmabuf_fd dmabuf file descriptor
874  * @param[in] size buffer size
875  * @param[in] addr mapped addr
876  * @return 0 if no error, otherwise a negative errno
877  */
878 int
879 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
880 {
881   if (!initialized ()) {
882     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
883     return -EPERM;
884   }
885
886   if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
887     logerr (TAG, "Invalid arguments\n");
888     return -EINVAL;
889   }
890
891   return mem_->deallocMemory (dmabuf_fd, size, addr);
892 }
893
894 /**
895  * @brief extract the buffer instance from input generic buffers
896  * @param[in] meta the model metadata
897  * @param[in] input the input generic buffers
898  * @return the buffer instance
899  */
900 Buffer *
901 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
902 {
903   if (meta == nullptr || input == nullptr ||
904       meta->getInputNum() != input->num_buffers) {
905     logerr (TAG, "Invalid metadata info provided\n");
906     return nullptr;
907   }
908
909   Buffer * buffer;
910   const generic_buffer *first = &input->bufs[0];
911   if (first->type == BUFFER_DMABUF) {
912     buffer = mem_->allocBuffer (new HWmemExternal);
913     if (buffer == nullptr)
914       return nullptr;
915
916     buffer->setDmabuf (first->dmabuf);
917     buffer->setOffset (first->offset);
918     buffer->setSize (meta->getBufferSize());
919   } else {
920     buffer = mem_->allocBuffer (new HWmemDevice);
921     if (buffer == nullptr)
922       return nullptr;
923
924     int status = buffer->alloc (meta->getBufferSize ());
925     if (status != 0) {
926       logerr (TAG, "Failed to allocate buffer: %d\n", status);
927       delete buffer;
928       return nullptr;
929     }
930   }
931
932   int status = buffer->createTensors (meta);
933   if (status != 0) {
934     logerr (TAG, "Failed to create tensors: %d\n", status);
935     delete buffer;
936     buffer = nullptr;
937   }
938
939   return buffer;
940 }
941
942 /**
943  * @brief implementation of TRIV's setModel ()
944  * @param[in] model_buf the model generic buffer
945  * @param[out] model the model instance
946  * @return 0 if no error, otherwise a negative errno
947  */
948 int
949 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
950 {
951   if (!initialized ()) {
952     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
953     return -EPERM;
954   }
955
956   if (model_buf == nullptr || model_ptr == nullptr)
957     return -EINVAL;
958
959   Model *model;
960   int status;
961
962   /** In TRIV1, model data (including program/weight) should be contiguous */
963
964   switch (model_buf->type) {
965   case BUFFER_FILE:
966   case BUFFER_MAPPED:
967     model = mem_->allocModel (new HWmemDevice);
968     if (model == nullptr) {
969       logerr (TAG, "Failed to allocate model\n");
970       return -ENOMEM;
971     }
972
973     status = model->alloc (model_buf->size);
974     if (status != 0) {
975       logerr (TAG, "Failed to allocate model: %d\n", status);
976       goto delete_exit;
977     }
978
979     /** extract the whole model data */
980     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
981     if (status != 0) {
982       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
983       goto delete_exit;
984     }
985     break;
986   default:
987     return -EINVAL;
988   }
989
990   status = model->setMetadata (model->getData());
991   if (status != 0)
992     goto delete_exit;
993
994   /** allocate program (optional; NOP) */
995   if (model->getMetadata()->getProgramSize() > 0) {
996     HWmem * hwmem_prog = new HWmem (new HWmemChunk);
997     model->setProgramData (hwmem_prog);
998
999     hwmem_prog->setParent (model);
1000     hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1001     status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1002     if (status != 0) {
1003       logerr (TAG, "Failed to allocate program\n");
1004       goto delete_exit;
1005     }
1006
1007     /** register this model to the driver */
1008     model_config_t config;
1009     config.dbuf_fd = hwmem_prog->getDmabuf ();
1010     config.program_size = hwmem_prog->getSize ();
1011     config.program_offset_addr = hwmem_prog->getOffset ();
1012
1013     status = api_->registerModel (&config);
1014     if (status != 0)
1015       goto delete_exit;
1016
1017     model->setInternalID(config.id);
1018   }
1019
1020   /** allocate weight (optional) */
1021   if (model->getMetadata()->getWeightSize() > 0) {
1022     HWmem * hwmem_weight = new HWmem (new HWmemChunk);
1023     model->setWeightData (hwmem_weight);
1024
1025     hwmem_weight->setParent (model);
1026     hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1027         model->getMetadata()->getProgramSize());
1028     status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1029     if (status != 0) {
1030       logerr (TAG, "Failed to allocate program\n");
1031       goto delete_exit;
1032     }
1033   }
1034
1035   *model_ptr = model;
1036   return status;
1037
1038 delete_exit:
1039   delete model;
1040   return status;
1041 }
1042
1043 /**
1044  * @brief implementation of TRIV's unsetModel ()
1045  * @param[in] model the model instance
1046  * @return 0 if no error, otherwise a negative errno
1047  */
1048 int
1049 TrinityVision::unsetModel (Model * model)
1050 {
1051   if (!initialized ()) {
1052     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1053     return -EPERM;
1054   }
1055
1056   if (model == nullptr) {
1057     logerr (TAG, "Invalid model instance\n");
1058     return -EINVAL;
1059   }
1060
1061   if (model->getMetadata()->getProgramSize() > 0)
1062     return api_->deregisterModel (model->getInternalID ());
1063
1064   return 0;
1065 }
1066
1067 /**
1068  * @brief implementation of TRIV's run()
1069  * @param[in] opmode input opmode
1070  * @param[in] model the model instance
1071  * @param[in] input generic buffers of input data
1072  * @param[in] cb the output callback
1073  * @param[in] cb_data the output callback data
1074  * @param[out] sequence The sequence number returned with runNPU_async.
1075  */
1076 int
1077 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1078     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1079     uint64_t *sequence)
1080 {
1081   if (!initialized ()) {
1082     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1083     return -EPERM;
1084   }
1085
1086   if (opmode != NPUINPUT_HOST) {
1087     logerr (TAG, "TRIV supports only host inputservice\n");
1088     return -EINVAL;
1089   }
1090
1091   if (model == nullptr || input == nullptr) {
1092     logerr (TAG, "TRIV requires both model and input buffers\n");
1093     return -EINVAL;
1094   }
1095
1096   Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1097   if (buffer == nullptr) {
1098     logerr (TAG, "Failed to extract buffer instance\n");
1099     return -EINVAL;
1100   }
1101
1102   if (!buffer->isExternal ()) {
1103     for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1104       auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1105           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1106       int status = comm_.extractGenericBuffer (&input->bufs[idx],
1107           buffer->getInputTensor(idx)->getData(), func);
1108       if (status != 0) {
1109         logerr (TAG, "Failed to feed input buffer: %d\n", status);
1110         return status;
1111       }
1112     }
1113   }
1114
1115   /** this device uses CMA buffer */
1116
1117   Request *req = new Request (opmode);
1118   req->setModel (model);
1119   req->setBuffer (buffer);
1120
1121   if (cb != nullptr)
1122     req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1123
1124   if (sequence != nullptr)
1125     *sequence = req->getID();
1126
1127   return scheduler_->submitRequest (req);
1128 }
1129
1130 /**
1131  * @brief callback of TRIV2 request
1132  * @param[in] req the request instance
1133  * @param[in] cb callback for completion
1134  * @param[in] cb_data callback data
1135  * @note The callback invoke does not gurantee the request was successful
1136  * @todo Check the request failures
1137  */
1138 void
1139 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1140 {
1141   const Model *model = req->getModel ();
1142   Buffer *buffer = req->getBuffer ();
1143   output_buffers output = {
1144     .num_buffers = buffer->getOutputNum ()
1145   };
1146
1147   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1148     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1149
1150     if (buffer->isExternal ()) {
1151       output.bufs[idx].type = BUFFER_DMABUF;
1152       output.bufs[idx].size = output_tensor_size;
1153       output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1154     } else {
1155       output.bufs[idx].type = BUFFER_MAPPED;
1156       output.bufs[idx].size = output_tensor_size;
1157       /** user needs to free this */
1158       output.bufs[idx].addr = malloc (output_tensor_size);
1159
1160       auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1161           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1162       int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1163           &output.bufs[idx], func);
1164       if (status != 0) {
1165         logerr (TAG, "Failed to return output buffer: %d\n", status);
1166       }
1167     }
1168   }
1169
1170   cb (&output, req->getID(), cb_data);
1171
1172   delete buffer;
1173 }
1174
1175 /**
1176  * @brief extract the segment table instance from input generic buffers
1177  * @param[in] model the model instance
1178  * @param[in] input the input generic buffers
1179  * @return the segment table instance
1180  */
1181 SegmentTable *
1182 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1183 {
1184   if (model == nullptr || input == nullptr) {
1185     logerr (TAG, "Invalid arguments provided\n");
1186     return nullptr;
1187   }
1188
1189   const Metadata *meta = model->getMetadata ();
1190   if (meta == nullptr ||
1191       meta->getInputNum() != input->num_buffers) {
1192     logerr (TAG, "Invalid metadata info provided\n");
1193     return nullptr;
1194   }
1195
1196   SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1197   int status = segt->alloc ();
1198   if (status != 0) {
1199     logerr (TAG, "Failed to allocate segment table: %d\n", status);
1200     goto delete_segt;
1201   }
1202
1203   status = segt->createSegments (model, input);
1204   if (status != 0) {
1205     logerr (TAG, "Failed to create segments: %d\n", status);
1206     goto delete_segt;
1207   }
1208
1209   return segt;
1210
1211 delete_segt:
1212   delete segt;
1213   return nullptr;
1214 }
1215
1216 /**
1217  * @brief implementation of TRIV2's setModel ()
1218  * @param[in] model_buf the model generic buffer
1219  * @param[out] model the model instance
1220  * @return 0 if no error, otherwise a negative errno
1221  */
1222 int
1223 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1224 {
1225   if (!initialized ()) {
1226     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1227     return -EPERM;
1228   }
1229
1230         if (model_buf == nullptr || model_ptr == nullptr)
1231                 return -EINVAL;
1232
1233   Model *model;
1234   int status;
1235
1236   switch (model_buf->type) {
1237   case BUFFER_FILE:
1238   case BUFFER_MAPPED:
1239     model = mem_->allocModel (new HWmemDevice);
1240     if (model == nullptr) {
1241       logerr (TAG, "Failed to allocate model\n");
1242       return -ENOMEM;
1243     }
1244
1245     status = model->alloc (NPUBIN_META_SIZE);
1246     if (status != 0) {
1247       logerr (TAG, "Failed to allocate model: %d\n", status);
1248       goto delete_exit;
1249     }
1250
1251     status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1252         0, NPUBIN_META_SIZE);
1253     if (status != 0) {
1254       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1255       goto delete_exit;
1256     }
1257     break;
1258   default:
1259     return -EINVAL;
1260   }
1261
1262   status = model->setMetadata (model->getData());
1263   if (status != 0)
1264     goto delete_exit;
1265
1266   /** allocate program (optional; NOP) */
1267   if (model->getMetadata()->getProgramSize() > 0) {
1268     HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1269     hwmem_prog->setDriverAPI (api_.get());
1270
1271     model->setProgramData (hwmem_prog);
1272
1273     status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1274     if (status != 0) {
1275       logerr (TAG, "Failed to allocate program\n");
1276       goto delete_exit;
1277     }
1278
1279     status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1280         model->getMetadata()->getMetaSize(),
1281         model->getMetadata()->getProgramSize());
1282     if (status != 0) {
1283       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1284       goto delete_exit;
1285     }
1286
1287     /** register this model to the driver */
1288     model_config_t config;
1289     config.dbuf_fd = hwmem_prog->getDmabuf ();
1290     config.program_size = hwmem_prog->getSize ();
1291     config.program_offset_addr = 0;
1292
1293     status = api_->registerModel (&config);
1294     if (status != 0)
1295       goto delete_exit;
1296
1297     model->setInternalID(config.id);
1298   }
1299
1300   /** allocate weight (optional) */
1301   if (model->getMetadata()->getWeightSize() > 0) {
1302     HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1303     hwmem_weight->setDriverAPI (api_.get());
1304
1305     model->setWeightData (hwmem_weight);
1306
1307     status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1308     if (status != 0) {
1309       logerr (TAG, "Failed to allocate program\n");
1310       goto delete_exit;
1311     }
1312
1313     status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1314         model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1315         model->getMetadata()->getWeightSize());
1316     if (status != 0) {
1317       logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1318       goto delete_exit;
1319     }
1320   }
1321
1322   *model_ptr = model;
1323   return status;
1324
1325 delete_exit:
1326   delete model;
1327   return status;
1328 }
1329
1330 /**
1331  * @brief implementation of TRIV2's unsetModel ()
1332  * @param[in] model the model instance
1333  * @return 0 if no error, otherwise a negative errno
1334  */
1335 int
1336 TrinityVision2::unsetModel (Model * model)
1337 {
1338   if (!initialized ()) {
1339     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1340     return -EPERM;
1341   }
1342
1343   if (model == nullptr) {
1344     logerr (TAG, "Invalid model instance\n");
1345     return -EINVAL;
1346   }
1347
1348   if (model->getMetadata()->getProgramSize() > 0)
1349     return api_->deregisterModel (model->getInternalID ());
1350
1351   return 0;
1352 }
1353
1354 /** @brief implementation of TRIV2's run() */
1355 int
1356 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1357     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1358     uint64_t *sequence)
1359 {
1360   if (!initialized ()) {
1361     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1362     return -EPERM;
1363   }
1364
1365   if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1366     return -EINVAL;
1367
1368   /** this device uses segment table */
1369   SegmentTable * segt = prepareSegmentTable (model, input);
1370   if (segt == nullptr) {
1371     logerr (TAG, "Failed to create segment table instance\n");
1372     return -EINVAL;
1373   }
1374
1375   /** extract input data */
1376   for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1377     if (!segt->getInputSegment(idx)->isExternal ()) {
1378       auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1379           std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1380       int status = comm_.extractGenericBuffer (
1381           &input->bufs[idx],
1382           segt->getInputSegment(idx)->getData() + segt->getInputSegmentOffset(idx),
1383           func);
1384       if (status != 0) {
1385         logerr (TAG, "Failed to feed input segment: %d\n", status);
1386         return status;
1387       }
1388     }
1389   }
1390
1391   Request *req = new Request (opmode);
1392   req->setModel (model);
1393   req->setSegmentTable (segt);
1394   req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1395
1396   if (sequence)
1397     *sequence = req->getID();
1398
1399   return scheduler_->submitRequest (req);
1400 }
1401
1402 /** @brief callback of TRIV2 request */
1403 void
1404 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1405 {
1406   const Model *model = req->getModel ();
1407   SegmentTable *segt = req->getSegmentTable ();
1408   output_buffers output = {
1409     .num_buffers = segt->getNumOutputSegments ()
1410   };
1411
1412   for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1413     uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1414
1415     output.bufs[idx].type = BUFFER_MAPPED;
1416     output.bufs[idx].size = output_tensor_size;
1417     /** user needs to free this */
1418     output.bufs[idx].addr = malloc (output_tensor_size);
1419
1420     auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1421         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1422     int status = comm_.insertGenericBuffer (
1423         segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1424         &output.bufs[idx], func);
1425     if (status != 0) {
1426       logerr (TAG, "Failed to return output buffer: %d\n", status);
1427     }
1428   }
1429
1430   cb (&output, req->getID(), cb_data);
1431
1432   delete segt;
1433 }
1434
1435 /** @brief implementation of TRIA's run(): WIP */
1436 int
1437 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1438     const input_buffers *input, npuOutputNotify cb, void *cb_data,
1439     uint64_t *sequence)
1440 {
1441   if (!initialized ()) {
1442     logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1443     return -EPERM;
1444   }
1445
1446   if (opmode != NPUINPUT_HOST)
1447     return -EINVAL;
1448
1449   Buffer * buffer;
1450   int status;
1451   /** ASR does not require model and support only a single tensor */
1452   const generic_buffer *first_buf = &input->bufs[0];
1453   if (first_buf->type == BUFFER_DMABUF) {
1454     buffer = mem_->allocBuffer (new HWmemExternal);
1455     if (buffer == nullptr)
1456       return -ENOMEM;
1457
1458     buffer->setDmabuf (first_buf->dmabuf);
1459     buffer->setOffset (first_buf->offset);
1460     buffer->setSize (first_buf->size);
1461   } else {
1462     buffer = mem_->allocBuffer (new HWmemDevice);
1463     if (buffer == nullptr)
1464       return -ENOMEM;
1465
1466     status = buffer->alloc (first_buf->size);
1467     if (status != 0) {
1468       delete buffer;
1469       return status;
1470     }
1471   }
1472
1473   status = buffer->createTensors ();
1474   if (status != 0) {
1475     logerr (TAG, "Failed to create tensors: %d\n", status);
1476     delete buffer;
1477     return status;
1478   }
1479
1480   if (!buffer->isExternal ()) {
1481     status = comm_.extractGenericBuffer (first_buf,
1482         buffer->getInputTensor(0)->getData(), nullptr);
1483     if (status != 0)
1484       return status;
1485   }
1486
1487   Request *req = new Request (opmode);
1488   req->setBuffer (buffer);
1489   req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1490
1491   if (sequence)
1492     *sequence = req->getID();
1493
1494   return scheduler_->submitRequest (req);
1495 }
1496
1497 /** @brief callback of TRIA request: WIP */
1498 void
1499 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1500 {
1501 }
1502
1503 /** Implement data manipulation (each device may have different impl.) */
1504
1505 #ifdef ENABLE_MANIP
1506
1507 #define do_quantized_memcpy(type) do {\
1508     idx = 0;\
1509     if (quant) {\
1510       while (idx < num_elems) {\
1511           val = ((type *) src)[idx];\
1512           val = val / _scale;\
1513           val += _zero_point;\
1514           val = (val > 255.0) ? 255.0 : 0.0;\
1515           ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1516       }\
1517     } else {\
1518       while (idx < num_elems) {\
1519           val = *(uint8_t *) src;\
1520           val -= _zero_point;\
1521           val *= _scale;\
1522           ((type *) dst)[idx++] = (type) val;\
1523           dst = (void*)(((uint8_t *) dst) + data_size);\
1524           src = (void*)(((uint8_t *) src) + 1);\
1525       }\
1526     }\
1527   } while (0)
1528
1529 /**
1530  * @brief memcpy during quantization
1531  */
1532 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1533     void *dst, const void *src, uint32_t num_elems)
1534 {
1535   double _scale = (double) scale;
1536   double _zero_point = (double) zero_point;
1537   double val;
1538   uint32_t data_size = get_data_size (type);
1539   uint32_t idx;
1540
1541   switch (type) {
1542     case DATA_TYPE_INT8:
1543       do_quantized_memcpy (int8_t);
1544       break;
1545     case DATA_TYPE_UINT8:
1546       do_quantized_memcpy (uint8_t);
1547       break;
1548     case DATA_TYPE_INT16:
1549       do_quantized_memcpy (int16_t);
1550       break;
1551     case DATA_TYPE_UINT16:
1552       do_quantized_memcpy (uint16_t);
1553       break;
1554     case DATA_TYPE_INT32:
1555       do_quantized_memcpy (int32_t);
1556       break;
1557     case DATA_TYPE_UINT32:
1558       do_quantized_memcpy (uint32_t);
1559       break;
1560     case DATA_TYPE_INT64:
1561       do_quantized_memcpy (int64_t);
1562       break;
1563     case DATA_TYPE_UINT64:
1564       do_quantized_memcpy (uint64_t);
1565       break;
1566     case DATA_TYPE_FLOAT32:
1567       do_quantized_memcpy (float);
1568       break;
1569     case DATA_TYPE_FLOAT64:
1570       do_quantized_memcpy (double);
1571       break;
1572     default:
1573       logerr (TAG, "Unsupported datatype %d\n", type);
1574   }
1575 }
1576
1577 /**
1578  * @brief perform data manipulation
1579  * @param[in] model model instance
1580  * @param[in] idx tensor index
1581  * @param[in] is_input indicate it's input manipulation
1582  * @param[out] dst destination buffer
1583  * @param[in] src source buffer (feature map)
1584  * @param[in] size size to be copied
1585  * @return size of memory copy if no error, otherwise zero
1586  *
1587  * @note the input data format should be NHWC
1588  * @detail rules for the memory address of activations in NPU HW.
1589  *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1590  *
1591  * 1) Special case (depth == 3)
1592  * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1593  *
1594  * 2) Common case
1595  * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1596  *
1597  * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1598  */
1599 size_t
1600 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1601     void *dst, void *src, size_t size)
1602 {
1603   const Metadata *meta = model->getMetadata();
1604   const tensor_data_info* info;
1605   const uint32_t *dims;
1606   uint32_t zero_point;
1607   float scale;
1608
1609   /** extract required information from the metadata */
1610   if (is_input) {
1611     if (idx >= meta->getInputNum()) {
1612       logerr (TAG, "Wrong information for input tensors in metadata\n");
1613       return 0;
1614     }
1615
1616     info = model->getInputDataInfo (idx);
1617     dims = meta->getInputDims (idx);
1618     zero_point = meta->getInputQuantZero (idx);
1619     scale = meta->getInputQuantScale (idx);
1620   } else {
1621     if (idx >= meta->getOutputNum()) {
1622       logerr (TAG, "Wrong information for output tensors in metadata\n");
1623       return 0;
1624     }
1625
1626     info = model->getOutputDataInfo (idx);
1627     dims = meta->getOutputDims (idx);
1628     zero_point = meta->getOutputQuantZero (idx);
1629     scale = meta->getOutputQuantScale (idx);
1630   }
1631
1632   if (info == nullptr) {
1633     logerr (TAG, "Unmatched tensors info\n");
1634     return 0;
1635   }
1636
1637   uint32_t batch = dims[0];
1638   uint32_t height = dims[1];
1639   uint32_t width = dims[2];
1640   uint32_t depth = dims[3];
1641
1642   uint32_t data_size = get_data_size (info->type);
1643   if (data_size == 0) {
1644     logerr (TAG, "Invalid data size\n");
1645     return 0;
1646   }
1647
1648   bool need_quantization = false;
1649   /**
1650    * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1651    * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1652    */
1653   if (info->type != DATA_TYPE_SRNPU) {
1654     assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1655
1656     if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1657         !(zero_point == default_quant_zero && scale == default_quant_scale))
1658       need_quantization = true;
1659   }
1660
1661   /** check data manipulation is required */
1662   if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1663     uint32_t MPA_L = DATA_GRANULARITY;
1664     uint32_t n, h, w, d;
1665     uint32_t std_offset;  /* standard offset in NHWC data format */
1666     uint32_t npu_offset;  /* npu offset in NPU HW data format*/
1667     uint32_t src_offset;
1668     uint32_t dst_offset;
1669     uint32_t slice_size;
1670
1671     /* @todo we currently support only NHWC */
1672     if (info->layout != DATA_LAYOUT_NHWC) {
1673       logerr (TAG, "data manipulation is supported for NHWC only\n");
1674       return 0;
1675     }
1676
1677     for (n = 0; n < batch; n++) {
1678       for (h = 0; h < height; h++) {
1679         for (w = 0; w < width; w++) {
1680           for (d = 0; d < depth; d += MPA_L) {
1681             std_offset = d + depth * (w + width * (h + n * height));
1682             npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1683             slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1684
1685             if (is_input) {
1686               src_offset = std_offset * data_size;
1687               dst_offset = npu_offset;
1688             } else {
1689               src_offset = npu_offset;
1690               dst_offset = std_offset * data_size;
1691             }
1692
1693             /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1694             if (need_quantization) {
1695               memcpy_with_quant (is_input, info->type, scale, zero_point,
1696                   static_cast<char*>(dst) + dst_offset,
1697                   static_cast<char*>(src) + src_offset,
1698                   slice_size);
1699             } else {
1700               memcpy (
1701                   static_cast<char*>(dst) + dst_offset,
1702                   static_cast<char*>(src) + src_offset,
1703                   slice_size);
1704             }
1705           }
1706         }
1707       }
1708     }
1709   } else if (need_quantization) {
1710     /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1711     memcpy_with_quant (is_input, info->type, scale, zero_point,
1712         dst, src, is_input ? size / data_size : size);
1713   } else {
1714     memcpy (dst, src, size);
1715   }
1716
1717   return size;
1718 }
1719
1720 #else
1721
1722 size_t
1723 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1724     void *dst, void *src, size_t size)
1725 {
1726   memcpy (dst, src, size);
1727   return size;
1728 }
1729
1730 #endif
1731
1732 /** other device types don't have data manip impl. yet */
1733
1734 size_t
1735 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1736     void *dst, void *src, size_t size)
1737 {
1738   memcpy (dst, src, size);
1739   return size;
1740 }
1741
1742 size_t
1743 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1744     void *dst, void *src, size_t size)
1745 {
1746   memcpy (dst, src, size);
1747   return size;
1748 }