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