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