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