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