Update software stack url and log tag info
[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 <npubinfmt.h>
16 #include <NPUdrvAPI.h>
17 #include <CommPlugin.h>
18
19 #include "ne-utils.h"
20 #include "ne-mem.h"
21 #include "ne-scheduler.h"
22 #include "ne-handler.h"
23
24 #include <string.h>
25 #include <assert.h>
26
27 #include <condition_variable>
28 #include <functional>
29 #include <atomic>
30 #include <map>
31
32 #define TAG _N2
33
34 #define INIT_HOST_HANDLER(handler, dev) \
35   Device *tdev = static_cast <Device *> (dev); \
36   if (tdev == nullptr) return -EINVAL; \
37   HostHandler *handler = tdev->getHostHandler (); \
38   if (handler == nullptr) return -EINVAL;
39
40 /** @brief device class. it contains all related instances */
41 class Device {
42   public:
43     /** @brief Factory method to create a trinity device dependong on dev type */
44     static Device *createInstance (dev_type device_type, int device_id);
45
46     /** @brief constructor of device */
47     Device (dev_type type, int id, bool need_model = true)
48       : comm_(CommPlugin::getCommPlugin()), type_ (type), id_ (id),
49         need_model_ (true), mode_ (NPUASYNC_WAIT), initialized_ (ATOMIC_FLAG_INIT) {}
50
51     /** @brief destructor of device */
52     virtual ~Device () {}
53
54     /** @brief initialization */
55     int init () {
56       if (!initialized_.test_and_set()) {
57         /** create the corresponding driver API */
58         api_ = DriverAPI::createDriverAPI (type_, id_);
59         if (api_.get() == nullptr) {
60           initialized_.clear();
61           logerr (TAG, "Failed to create driver API\n");
62           return -EINVAL;
63         }
64
65         handler_.reset (new HostHandler (this));
66         scheduler_.reset (new Scheduler (api_.get()));
67         mem_ = MemAllocator::createInstance (api_.get());
68       }
69
70       return 0;
71     }
72
73     HostHandler *getHostHandler () { return handler_.get(); }
74     dev_type getType () { return type_; }
75     int getID () { return id_; }
76     bool needModel () { return need_model_; }
77     void setAsyncMode (npu_async_mode mode) { mode_ = mode; }
78
79     HWmem * allocMemory () { return mem_->allocMemory (); }
80     void deallocMemory (int dmabuf_fd) { mem_->deallocMemory (dmabuf_fd); }
81
82     /** it stops all requests in this device (choose wait or force) */
83     int stop (bool force_stop) {
84       Request *req = new Request (NPUINPUT_STOP);
85       req->setForceStop (force_stop);
86       return scheduler_->submitRequest (req);
87     }
88
89     virtual Model * registerModel (const generic_buffer *model) = 0;
90     virtual int run (npu_input_opmode opmode, const Model *model,
91         const input_buffers *input, npuOutputNotify cb, void *cb_data,
92         uint64_t *sequence) = 0;
93
94   protected:
95     /** the device instance has ownership of all related components */
96     std::unique_ptr<DriverAPI>    api_;       /**< device api */
97     std::unique_ptr<MemAllocator> mem_;       /**< memory allocator */
98     std::unique_ptr<HostHandler>  handler_;   /**< host handler */
99     std::unique_ptr<Scheduler>    scheduler_; /**< scheduler */
100
101     CommPlugin& comm_;                        /**< plugin communicator */
102
103     dev_type type_;                           /**< device type */
104     int id_;                                  /**< device id */
105     bool need_model_;                         /**< indicates whether the device needs model */
106     npu_async_mode mode_;                     /**< async run mode */
107
108   private:
109     std::atomic_flag initialized_;
110 };
111
112 /** @brief Trinity Vision (TRIV) classs */
113 class TrinityVision : public Device {
114   public:
115     TrinityVision (int id) : Device (NPUCOND_TRIV_CONN_SOCIP, id) {}
116
117     static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
118         void *dst, void *src, size_t size);
119
120     Model * registerModel (const generic_buffer *model_buf) {
121       Model *model = mem_->allocModel ();
122       if (model == nullptr) {
123         logerr (TAG, "Failed to allocate model\n");
124         return nullptr;
125       }
126
127       int status;
128       if (model_buf->type == BUFFER_DMABUF) {
129         model->setDmabuf (model_buf->dmabuf);
130         model->setOffset (model_buf->offset);
131         model->setSize (model_buf->size);
132       } else {
133         status = model->alloc (model_buf->size);
134         if (status != 0) {
135           logerr (TAG, "Failed to allocate model: %d\n", status);
136           goto delete_exit;
137         }
138
139         status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
140         if (status != 0) {
141           logerr (TAG, "Failed to extract generic buffer: %d\n", status);
142           goto delete_exit;
143         }
144       }
145
146       status = model->setMetadata (model->getData());
147       if (status != 0)
148         goto delete_exit;
149
150       model_config_t config;
151       config.dmabuf_id = model->getDmabuf();
152       config.program_size = model->getMetadata()->getProgramSize();
153       config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
154       config.weight_offset_addr = config.program_offset_addr + config.program_size;
155
156       status = api_->setModel (&config);
157       if (status != 0)
158         goto delete_exit;
159
160       return model;
161
162 delete_exit:
163       delete model;
164       return nullptr;
165     }
166
167     Buffer * prepareInputBuffers (const Model *model, const input_buffers *input) {
168       const Metadata *meta = model->getMetadata();
169       const generic_buffer *first = &input->bufs[0];
170
171       if (meta->getInputNum() != input->num_buffers)
172         return nullptr;
173
174       Buffer * buffer = mem_->allocBuffer ();
175       if (buffer != nullptr) {
176         if (first->type == BUFFER_DMABUF) {
177           buffer->setDmabuf (first->dmabuf);
178           buffer->setOffset (first->offset);
179           buffer->setSize (meta->getBufferSize());
180         } else {
181           int status = buffer->alloc (meta->getBufferSize ());
182           if (status != 0) {
183             logerr (TAG, "Failed to allocate buffer: %d\n", status);
184             delete buffer;
185             return nullptr;
186           }
187         }
188       }
189
190       buffer->createTensors (meta);
191       return buffer;
192     }
193
194     int run (npu_input_opmode opmode, const Model *model,
195         const input_buffers *input, npuOutputNotify cb, void *cb_data,
196         uint64_t *sequence) {
197       if (opmode != NPUINPUT_HOST)
198         return -EINVAL;
199
200       Buffer *buffer = prepareInputBuffers (model, input);
201       if (buffer == nullptr)
202         return -EINVAL;
203
204       for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
205         auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
206             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
207         int status = comm_.extractGenericBuffer (&input->bufs[idx],
208             buffer->getInputTensor(idx)->getData(), func);
209         if (status != 0) {
210           logerr (TAG, "Failed to feed input buffer: %d\n", status);
211           return status;
212         }
213       }
214
215       /** this device uses CMA buffer */
216
217       Request *req = new Request (opmode);
218       req->setModel (model);
219       req->setBuffer (buffer);
220       req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
221
222       if (sequence)
223         *sequence = req->getID();
224
225       return scheduler_->submitRequest (req);
226     }
227
228     void callback (Request *req, npuOutputNotify cb, void *cb_data) {
229       const Model *model = req->getModel ();
230       Buffer *buffer = req->getBuffer ();
231       output_buffers output = {
232         .num_buffers = buffer->getOutputNum ()
233       };
234
235       for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
236         uint32_t output_tensor_size = model->getOutputTensorSize (idx);
237
238         output.bufs[idx].type = BUFFER_MAPPED;
239         output.bufs[idx].size = output_tensor_size;
240         /** user needs to free this */
241         output.bufs[idx].addr = malloc (output_tensor_size);
242
243         auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
244             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
245         int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
246             &output.bufs[idx], func);
247         if (status != 0) {
248           logerr (TAG, "Failed to return output buffer: %d\n", status);
249         }
250       }
251
252       cb (&output, req->getID(), cb_data);
253     }
254 };
255
256 /** @brief Trinity Vision2 (TRIV2) classs */
257 class TrinityVision2 : public Device {
258   public:
259     TrinityVision2 (int id) : Device (NPUCOND_TRIV2_CONN_SOCIP, id) {}
260
261     static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
262         void *dst, void *src, size_t size) {
263       memcpy (dst, src, size);
264       return size;
265     }
266
267     Model * registerModel (const generic_buffer *model_buf) {
268       /** TODO: model's weight values are stored in segments */
269       return nullptr;
270     }
271
272     int run (npu_input_opmode opmode, const Model *model,
273         const input_buffers *input, npuOutputNotify cb, void *cb_data,
274         uint64_t *sequence) {
275       if (opmode != NPUINPUT_HOST || opmode != NPUINPUT_HW_RECURRING)
276         return -EINVAL;
277
278       /** this device uses segment table */
279
280       Request *req = new Request (opmode);
281       req->setModel (model);
282 #if 0
283       req->setSegmentTable (segt);
284 #endif
285       req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
286
287       if (sequence)
288         *sequence = req->getID();
289
290       return scheduler_->submitRequest (req);
291     }
292
293     void callback (Request *req, npuOutputNotify cb, void *cb_data) {
294     }
295 };
296
297 /** @brief Trinity Asr (TRIA) classs */
298 class TrinityAsr : public Device {
299   public:
300     TrinityAsr (int id) : Device (NPUCOND_TRIA_CONN_SOCIP, id, false) {}
301
302     static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
303         void *dst, void *src, size_t size) {
304       memcpy (dst, src, size);
305       return size;
306     }
307
308     Model * registerModel (const generic_buffer *model_buf) { return nullptr; }
309
310     int run (npu_input_opmode opmode, const Model *model,
311         const input_buffers *input, npuOutputNotify cb, void *cb_data,
312         uint64_t *sequence) {
313       if (opmode != NPUINPUT_HOST)
314         return -EINVAL;
315
316       /** ASR does not require model and support only a single tensor */
317       const generic_buffer *first_buf = &input->bufs[0];
318       Buffer * buffer = mem_->allocBuffer ();
319       int status;
320       if (first_buf->type == BUFFER_DMABUF) {
321         buffer->setDmabuf (first_buf->dmabuf);
322         buffer->setOffset (first_buf->offset);
323         buffer->setSize (first_buf->size);
324       } else {
325         status = buffer->alloc (first_buf->size);
326         if (status != 0) {
327           delete buffer;
328           return status;
329         }
330       }
331       buffer->createTensors ();
332
333       status = comm_.extractGenericBuffer (first_buf,
334           buffer->getInputTensor(0)->getData(), nullptr);
335       if (status != 0)
336         return status;
337
338       Request *req = new Request (opmode);
339       req->setBuffer (buffer);
340       req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
341
342       if (sequence)
343         *sequence = req->getID();
344
345       return scheduler_->submitRequest (req);
346     }
347
348     void callback (Request *req, npuOutputNotify cb, void *cb_data) {
349     }
350 };
351
352 #ifdef ENABLE_MANIP
353
354 #define do_quantized_memcpy(type) do {\
355     idx = 0;\
356     if (quant) {\
357       while (idx < num_elems) {\
358           val = ((type *) src)[idx];\
359           val = val / _scale;\
360           val += _zero_point;\
361           val = (val > 255.0) ? 255.0 : 0.0;\
362           ((uint8_t *) dst)[idx++] = (uint8_t) val;\
363       }\
364     } else {\
365       while (idx < num_elems) {\
366           val = *(uint8_t *) src;\
367           val -= _zero_point;\
368           val *= _scale;\
369           ((type *) dst)[idx++] = (type) val;\
370           dst = (void*)(((uint8_t *) dst) + data_size);\
371           src = (void*)(((uint8_t *) src) + 1);\
372       }\
373     }\
374   } while (0)
375
376 /**
377  * @brief memcpy during quantization
378  */
379 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
380     void *dst, const void *src, uint32_t num_elems)
381 {
382   double _scale = (double) scale;
383   double _zero_point = (double) zero_point;
384   double val;
385   uint32_t data_size = get_data_size (type);
386   uint32_t idx;
387
388   switch (type) {
389     case DATA_TYPE_INT8:
390       do_quantized_memcpy (int8_t);
391       break;
392     case DATA_TYPE_UINT8:
393       do_quantized_memcpy (uint8_t);
394       break;
395     case DATA_TYPE_INT16:
396       do_quantized_memcpy (int16_t);
397       break;
398     case DATA_TYPE_UINT16:
399       do_quantized_memcpy (uint16_t);
400       break;
401     case DATA_TYPE_INT32:
402       do_quantized_memcpy (int32_t);
403       break;
404     case DATA_TYPE_UINT32:
405       do_quantized_memcpy (uint32_t);
406       break;
407     case DATA_TYPE_INT64:
408       do_quantized_memcpy (int64_t);
409       break;
410     case DATA_TYPE_UINT64:
411       do_quantized_memcpy (uint64_t);
412       break;
413     case DATA_TYPE_FLOAT32:
414       do_quantized_memcpy (float);
415       break;
416     case DATA_TYPE_FLOAT64:
417       do_quantized_memcpy (double);
418       break;
419     default:
420       logerr (TAG, "Unsupported datatype %d\n", type);
421   }
422 }
423
424 /**
425  * @brief perform data manipulation
426  * @param[in] model model instance
427  * @param[in] idx tensor index
428  * @param[in] is_input indicate it's input manipulation
429  * @param[out] dst destination buffer
430  * @param[in] src source buffer (feature map)
431  * @param[in] size size to be copied
432  * @return size of memory copy if no error, otherwise zero
433  *
434  * @note the input data format should be NHWC
435  * @detail rules for the memory address of activations in NPU HW.
436  *         (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
437  *
438  * 1) Special case (depth == 3)
439  * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
440  *
441  * 2) Common case
442  * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
443  *
444  * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
445  */
446 size_t
447 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
448     void *dst, void *src, size_t size)
449 {
450   const Metadata *meta = model->getMetadata();
451   const tensor_data_info* info;
452   const uint32_t *dims;
453   uint32_t zero_point;
454   float scale;
455
456   /** extract required information from the metadata */
457   if (is_input) {
458     if (idx >= meta->getInputNum()) {
459       logerr (TAG, "Wrong information for input tensors in metadata\n");
460       return 0;
461     }
462
463     info = model->getInputDataInfo (idx);
464     dims = meta->getInputDims (idx);
465     zero_point = meta->getInputQuantZero (idx);
466     scale = meta->getInputQuantScale (idx);
467   } else {
468     if (idx >= meta->getOutputNum()) {
469       logerr (TAG, "Wrong information for output tensors in metadata\n");
470       return 0;
471     }
472
473     info = model->getOutputDataInfo (idx);
474     dims = meta->getOutputDims (idx);
475     zero_point = meta->getOutputQuantZero (idx);
476     scale = meta->getOutputQuantScale (idx);
477   }
478
479   if (info == nullptr) {
480     logerr (TAG, "Unmatched tensors info\n");
481     return 0;
482   }
483
484   uint32_t batch = dims[0];
485   uint32_t height = dims[1];
486   uint32_t width = dims[2];
487   uint32_t depth = dims[3];
488
489   uint32_t data_size = get_data_size (info->type);
490   if (data_size == 0) {
491     logerr (TAG, "Invalid data size\n");
492     return 0;
493   }
494
495   bool need_quantization = false;
496   /**
497    * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
498    * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
499    */
500   if (info->type != DATA_TYPE_SRNPU) {
501     assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
502
503     if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
504         !(zero_point == DEFAULT_ZERO_POINT && scale == DEFAULT_SCALE))
505       need_quantization = true;
506   }
507
508   /** check data manipulation is required */
509   if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
510     uint32_t MPA_L = DATA_GRANULARITY;
511     uint32_t n, h, w, d;
512     uint32_t std_offset;  /* standard offset in NHWC data format */
513     uint32_t npu_offset;  /* npu offset in NPU HW data format*/
514     uint32_t src_offset;
515     uint32_t dst_offset;
516     uint32_t slice_size;
517
518     /* @todo we currently support only NHWC */
519     if (info->layout != DATA_LAYOUT_NHWC) {
520       logerr (TAG, "data manipulation is supported for NHWC only\n");
521       return -EINVAL;
522     }
523
524     for (n = 0; n < batch; n++) {
525       for (h = 0; h < height; h++) {
526         for (w = 0; w < width; w++) {
527           for (d = 0; d < depth; d += MPA_L) {
528             std_offset = d + depth * (w + width * (h + n * height));
529             npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
530             slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
531
532             if (is_input) {
533               src_offset = std_offset * data_size;
534               dst_offset = npu_offset;
535             } else {
536               src_offset = npu_offset;
537               dst_offset = std_offset * data_size;
538             }
539
540             /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
541             if (need_quantization) {
542               memcpy_with_quant (is_input, info->type, scale, zero_point,
543                   static_cast<char*>(dst) + dst_offset,
544                   static_cast<char*>(src) + src_offset,
545                   slice_size);
546             } else {
547               memcpy (
548                   static_cast<char*>(dst) + dst_offset,
549                   static_cast<char*>(src) + src_offset,
550                   slice_size);
551             }
552           }
553         }
554       }
555     }
556   } else if (need_quantization) {
557     /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
558     if (is_input)
559       size = size / data_size;
560
561     memcpy_with_quant (is_input, info->type, scale, zero_point,
562         dst, src, size);
563   } else {
564     memcpy (dst, src, size);
565   }
566
567   return 0;
568 }
569
570 #else
571
572 size_t
573 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
574     void *dst, void *src, size_t size)
575 {
576   memcpy (dst, src, size);
577   return size;
578 }
579
580 #endif
581
582 /**
583  * @brief create device instance depending on device type and id
584  * @param[in] type device type
585  * @param[in] id device id
586  * @return device instance
587  */
588 Device *
589 Device::createInstance (dev_type type, int id)
590 {
591   Device *device = nullptr;
592
593   switch (type & DEVICETYPE_MASK) {
594     case DEVICETYPE_TRIV:
595       device = new TrinityVision (id);
596       break;
597     case DEVICETYPE_TRIV2:
598       device = new TrinityVision2 (id);
599       break;
600     case DEVICETYPE_TRIA:
601       device = new TrinityAsr (id);
602       break;
603     default:
604       break;
605   }
606
607   if (device != nullptr && device->init () != 0) {
608     delete device;
609     device = nullptr;
610   }
611
612   return device;
613 }
614
615 /** @brief host handler constructor */
616 HostHandler::HostHandler (Device *device)
617   : device_(device)
618 {
619 }
620
621 /** @brief host handler destructor */
622 HostHandler::~HostHandler ()
623 {
624 }
625
626 /**
627  * @brief register model from generic buffer
628  * @param[in] model_buf model buffer
629  * @param[out] modelid model id
630  * @return 0 if no error. otherwise a negative errno
631  */
632 int
633 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
634 {
635   Model *model = device_->registerModel (model_buf);
636   if (model == nullptr) {
637     logerr (TAG, "Failed to register model\n");
638     return -EINVAL;
639   }
640
641   int status = models_.insert (model->getID(), model);
642   if (status != 0) {
643     logerr (TAG, "Failed to insert model id\n");
644     delete model;
645     return status;
646   }
647
648   *modelid = model->getID();
649   return 0;
650 }
651
652 /**
653  * @brief remove the registered model
654  * @param[in] modelid model id
655  * @return 0 if no error. otherwise a negative errno
656  */
657 int
658 HostHandler::unregisterModel (uint32_t modelid)
659 {
660   return models_.remove (modelid);
661 }
662
663 /**
664  * @brief remove all registered models
665  * @return 0
666  */
667 int
668 HostHandler::unregisterModels ()
669 {
670   models_.clear ();
671   return 0;
672 }
673
674 /**
675  * @brief Set the data layout for input/output tensors
676  * @param[in] modelid The ID of model whose layouts are set
677  * @param[in] in the layout/type info for input tensors
678  * @param[in] out the layout/type info for output tensors
679  * @return @c 0 if no error. otherwise a negative error value
680  * @note if this function is not called, default layout/type will be used.
681  */
682 int
683 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
684     tensors_data_info *out)
685 {
686   Model *model = models_.find (modelid);
687   if (model == nullptr)
688     return -ENOENT;
689
690   model->setDataInfo (in, out);
691
692   return 0;
693 }
694
695 /**
696  * @brief Set the inference constraint for next NPU inferences
697  * @param[in] modelid The target model id
698  * @param[in] constraint inference constraint (e.g., timeout, priority)
699  * @return @c 0 if no error. otherwise a negative error value
700  * @note If this function is not called, default values are used.
701  */
702 int
703 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
704 {
705   Model *model = models_.find (modelid);
706   if (model == nullptr)
707     return -ENOENT;
708
709   model->setConstraint (constraint);
710
711   return 0;
712 }
713
714 /**
715  * @brief find and return model instance
716  * @param[in] modelid model id
717  * @return model instance if found. otherwise nullptr
718  */
719 Model *
720 HostHandler::getModel (uint32_t modelid)
721 {
722   return models_.find (modelid);
723 }
724
725 /** @brief dummay callback for runSync. */
726 class callbackSync {
727   public:
728     callbackSync (output_buffers *output) : output_(output), done_(false) {}
729
730     static void callback (output_buffers *output, uint64_t sequence, void *data) {
731       callbackSync *sync = static_cast<callbackSync *>(data);
732       sync->callback (output, sequence);
733     }
734
735     void callback (output_buffers *output, uint64_t sequence) {
736       /** just copy internal variables of output buffers */
737       memcpy (output_, output, sizeof (output_buffers));
738       done_ = true;
739       cv_.notify_one ();
740     }
741
742     void wait () {
743       std::unique_lock<std::mutex> lock (m_);
744       cv_.wait (lock, [this]() { return done_; });
745     }
746
747   private:
748     std::mutex m_;
749     std::condition_variable cv_;
750     output_buffers *output_;
751     bool done_;
752 };
753
754 /**
755  * @brief Execute inference. Wait (block) until the output is available.
756  * @param[in] modelid The model to be inferred.
757  * @param[in] input The input data to be inferred.
758  * @param[out] output The output result.
759  * @return @c 0 if no error. otherwise a negative error value
760  */
761 int
762 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
763     output_buffers *output)
764 {
765   callbackSync sync (output);
766   int status = runAsync (modelid, input, callbackSync::callback,
767       static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
768   if (status == 0) {
769     /** sync needs to wait callback */
770     sync.wait ();
771   }
772   return status;
773 }
774
775 /**
776  * @brief Invoke NPU inference. Unblocking call.
777  * @param[in] modelid The model to be inferred.
778  * @param[in] input The input data to be inferred.
779  * @param[in] cb The output buffer handler.
780  * @param[in] cb_data The data given as a parameter to the runNPU_async call.
781  * @param[in] mode Configures how this operation works.
782  * @param[out] sequence The sequence number returned with runNPU_async.
783  * @return @c 0 if no error. otherwise a negative error value
784  */
785 int
786 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
787     npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
788 {
789   Model *model = nullptr;
790
791   if (device_->needModel()) {
792     model = getModel (modelid);
793     if (model == nullptr)
794       return -ENOENT;
795   }
796
797   device_->setAsyncMode (mode);
798   return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
799 }
800
801 /**
802  * @brief get number of available devices
803  * @param[in] type device type
804  * @return number of devices
805  */
806 int
807 HostHandler::getNumDevices (dev_type type)
808 {
809   return DriverAPI::getNumDevices (type);
810 }
811
812 /**
813  * @brief get device instance
814  * @param[out] dev device instance
815  * @param[in] type device type
816  * @param[in] id device id
817  * @return 0 if no error. otherwise a negative errno
818  */
819 int
820 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
821 {
822   int num_devices = getNumDevices (type);
823
824   /** check the validity of device id */
825   if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
826     logerr (TAG, "Invalid arguments provided\n");
827     return -ENODEV;
828   }
829
830   Device *device = Device::createInstance (type, id);
831   if (device == nullptr) {
832     logerr (TAG, "Failed to create a device with the given type\n");
833     return -EINVAL;
834   }
835
836   *dev = device;
837   /** This is just for backward-compatility; we don't guarantee its corresness */
838   latest_dev_ = *dev;
839
840   return 0;
841 }
842
843 /**
844  * @brief allocate generic buffer (just for users)
845  * @param[out] buffer buffer instance
846  * @return 0 if no error. otherwise a negative errno
847  */
848 int
849 HostHandler::allocGenericBuffer (generic_buffer *buffer)
850 {
851   if (buffer == NULL || SIZE_MAX < buffer->size)
852     return -EINVAL;
853
854   if (buffer->type == BUFFER_FILE) {
855     /* nothing to do */
856     if (buffer->filepath == nullptr)
857       return -EINVAL;
858   } else {
859     /* now, npu-engine always provides dmabuf-based allocation */
860     HWmem *hwmem = device_->allocMemory ();
861     if (hwmem == nullptr || hwmem->alloc (buffer->size) < 0)
862       return -ENOMEM;
863
864     buffer->dmabuf = hwmem->getDmabuf();
865     buffer->offset = hwmem->getOffset();
866     buffer->addr = hwmem->getData();
867   }
868   return 0;
869 }
870
871 /**
872  * @brief deallocate generic buffer (just for users)
873  * @param[in] buffer buffer instance
874  * @return 0 if no error. otherwise a negative errno
875  */
876 int
877 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
878 {
879   if (buffer == NULL)
880     return -EINVAL;
881
882   if (buffer->type != BUFFER_FILE)
883     device_->deallocMemory (buffer->dmabuf);
884
885   return 0;
886 }
887
888 /**
889  * @brief allocate multiple generic buffers (just for users)
890  * @param[out] buffers multi-buffer instance
891  * @return 0 if no error. otherwise a negative errno
892  */
893 int
894 HostHandler::allocGenericBuffer (generic_buffers *buffers)
895 {
896   if (buffers == NULL || buffers->num_buffers < 1)
897     return -EINVAL;
898
899   buffer_types type = buffers->bufs[0].type;
900   if (type == BUFFER_FILE)
901     return 0;
902
903   uint64_t total_size = 0;
904   for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
905     total_size += buffers->bufs[idx].size;
906
907   uint64_t first_size = buffers->bufs[0].size;
908   buffers->bufs[0].size = total_size;
909   int status = allocGenericBuffer (&buffers->bufs[0]);
910   if (status != 0)
911     return status;
912
913   uint64_t offset = first_size;
914   for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
915     buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
916     buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
917     buffers->bufs[idx].type = type;
918
919     offset += buffers->bufs[idx].size;
920   }
921
922   return 0;
923 }
924
925 /**
926  * @brief deallocate multiple generic buffers (just for users)
927  * @param[in] buffers multi-buffer instance
928  * @return 0 if no error. otherwise a negative errno
929  */
930 int
931 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
932 {
933   if (buffers == NULL || buffers->num_buffers < 1)
934     return -EINVAL;
935
936   return deallocGenericBuffer (&buffers->bufs[0]);
937 }
938
939 /** just for backward-compatability */
940 npudev_h HostHandler::latest_dev_ = nullptr;
941
942 /** implementation of libnpuhost APIs */
943
944 /**
945  * @brief Returns the number of available NPU devices.
946  * @return @c The number of NPU devices.
947  * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
948 */
949 int getnumNPUdeviceByType (dev_type type)
950 {
951   return HostHandler::getNumDevices (type);
952 }
953
954 /**
955  * @brief Returns the number of NPU devices (TRIV).
956  */
957 int getnumNPUdevice (void)
958 {
959   return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
960 }
961
962 /**
963  * @brief Returns the list of ASR devices (TRIA)
964  */
965 int getnumASRdevice (void)
966 {
967   return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
968 }
969
970 /**
971  * @brief Returns the handle of the chosen NPU devices.
972  * @param[out] dev The NPU device handle
973  * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
974  * @return @c 0 if no error. otherwise a negative error value
975  */
976 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
977 {
978   return HostHandler::getDevice (dev, type, id);
979 }
980
981 /**
982  * @brief Returns the handle of the chosen TRIV device.
983  */
984 int getNPUdevice (npudev_h *dev, uint32_t id)
985 {
986   return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
987 }
988
989 /**
990  * @brief Returns the handle of the chosen TRIA device.
991  */
992 int getASRdevice (npudev_h *dev, uint32_t id)
993 {
994   return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
995 }
996
997 /**
998  * @brief Send the NN model to NPU.
999  * @param[in] dev The NPU device handle
1000  * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
1001  * @param[out] modelid The modelid allocated for this instance of NN model.
1002  * @return @c 0 if no error. otherwise a negative error value
1003  *
1004  * @detail For ASR devices, which do not accept models, but have models
1005  *         embedded in devices, you do not need to call register and
1006  *         register calls for ASR are ignored.
1007  *
1008  * @todo Add a variation: in-memory model register.
1009  */
1010 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
1011 {
1012   INIT_HOST_HANDLER (host_handler, dev);
1013
1014   return host_handler->registerModel (modelfile, modelid);
1015 }
1016
1017 /**
1018  * @brief Remove the NN model from NPU
1019  * @param[in] dev The NPU device handle
1020  * @param[in] modelid The model to be removed from the NPU.
1021  * @return @c 0 if no error. otherwise a negative error value
1022  * @detail This may incur some latency with memory compatcion.
1023  */
1024 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
1025 {
1026   INIT_HOST_HANDLER (host_handler, dev);
1027
1028   return host_handler->unregisterModel (modelid);
1029 }
1030
1031 /**
1032  * @brief Remove all NN models from NPU
1033  * @param[in] dev The NPU device handle
1034  * @return @c 0 if no error. otherwise a negative error value
1035  */
1036 int unregisterNPUmodel_all(npudev_h dev)
1037 {
1038   INIT_HOST_HANDLER (host_handler, dev);
1039
1040   return host_handler->unregisterModels ();
1041 }
1042
1043 /**
1044  * @brief [OPTIONAL] Set the data layout for input/output tensors
1045  * @param[in] dev The NPU device handle
1046  * @param[in] modelid The ID of model whose layouts are set
1047  * @param[in] info_in the layout/type info for input tensors
1048  * @param[in] info_out the layout/type info for output tensors
1049  * @return @c 0 if no error. otherwise a negative error value
1050  * @note if this function is not called, default layout/type will be used.
1051  */
1052 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
1053     tensors_data_info *info_in, tensors_data_info *info_out)
1054 {
1055   INIT_HOST_HANDLER (host_handler, dev);
1056
1057   return host_handler->setDataInfo (modelid, info_in, info_out);
1058 }
1059
1060 /**
1061  * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
1062  * @param[in] dev The NPU device handle
1063  * @param[in] modelid The target model id
1064  * @param[in] constraint inference constraint (e.g., timeout, priority)
1065  * @return @c 0 if no error. otherwise a negative error value
1066  * @note If this function is not called, default values are used.
1067  */
1068 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
1069 {
1070   INIT_HOST_HANDLER (host_handler, dev);
1071
1072   return host_handler->setConstraint (modelid, constraint);
1073 }
1074
1075 /**
1076  * @brief Execute inference. Wait (block) until the output is available.
1077  * @param[in] dev The NPU device handle
1078  * @param[in] modelid The model to be inferred.
1079  * @param[in] input The input data to be inferred.
1080  * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
1081  * @return @c 0 if no error. otherwise a negative error value
1082  *
1083  * @detail This is a syntactic sugar of runNPU_async().
1084  *         CAUTION: There is a memcpy for the output buffer.
1085  */
1086 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
1087     output_buffers *output)
1088 {
1089   INIT_HOST_HANDLER (host_handler, dev);
1090
1091   return host_handler->runSync (modelid, input, output);
1092 }
1093
1094 /**
1095  * @brief Invoke NPU inference. Unblocking call.
1096  * @param[in] dev The NPU device handle
1097  * @param[in] modelid The model to be inferred.
1098  * @param[in] input The input data to be inferred.
1099  * @param[in] cb The output buffer handler.
1100  * @param[out] sequence The sequence number returned with runNPU_async.
1101  * @param[in] data The data given as a parameter to the runNPU_async call.
1102  * @param[in] mode Configures how this operation works.
1103  * @return @c 0 if no error. otherwise a negative error value
1104  */
1105 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
1106     npuOutputNotify cb, uint64_t *sequence, void *data,
1107     npu_async_mode mode)
1108 {
1109   INIT_HOST_HANDLER (host_handler, dev);
1110
1111   return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
1112 }
1113
1114 /**
1115  * @brief Allocate a buffer for NPU model with the requested buffer type.
1116  * @param[in] dev The NPU device handle
1117  * @param[in/out] Buffer the buffer pointer where memory is allocated.
1118  * @return 0 if no error, otherwise a negative errno.
1119  */
1120 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1121 {
1122   INIT_HOST_HANDLER (host_handler, dev);
1123
1124   return host_handler->allocGenericBuffer (buffer);
1125 }
1126
1127 /**
1128  * @brief Free the buffer and remove the address mapping.
1129  * @param[in] dev The NPU device handle
1130  * @param[in] buffer the model buffer
1131  * @return 0 if no error, otherwise a negative errno.
1132  */
1133 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1134 {
1135   INIT_HOST_HANDLER (host_handler, dev);
1136
1137   return host_handler->deallocGenericBuffer (buffer);
1138 }
1139
1140 /**
1141  * @brief Allocate a buffer for NPU input with the requested buffer type.
1142  * @param[in] dev The NPU device handle
1143  * @param[in/out] Buffer the buffer pointer where memory is allocated.
1144  * @return 0 if no error, otherwise a negative errno.
1145  * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
1146  *       calls of allocInputBuffer() don't gurantee contiguous allocations between them.
1147  */
1148 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1149 {
1150   INIT_HOST_HANDLER (host_handler, dev);
1151
1152   return host_handler->allocGenericBuffer (buffer);
1153 }
1154
1155 /**
1156  * @brief Free the buffer and remove the address mapping.
1157  * @param[in] dev The NPU device handle
1158  * @param[in] buffer the input buffer
1159  * @return 0 if no error, otherwise a negative errno.
1160  */
1161 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1162 {
1163   INIT_HOST_HANDLER (host_handler, dev);
1164
1165   return host_handler->deallocGenericBuffer (buffer);
1166 }
1167
1168 /**
1169  * @brief Allocate input buffers, which have multiple instances of generic_buffer
1170  * @param[in] dev The NPU device handle
1171  * @param[in/out] input input buffers.
1172  * @return 0 if no error, otherwise a negative errno.
1173  * @note it reuses allocInputBuffer().
1174  * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
1175  *          memory mapping for multiple tensors (in a single inference, not batch size).
1176  */
1177 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
1178 {
1179   INIT_HOST_HANDLER (host_handler, dev);
1180
1181   return host_handler->allocGenericBuffer (input);
1182 }
1183
1184 /**
1185  * @brief Free input buffers allocated by allocInputBuffers().
1186  * @param[in] dev The NPU device handle
1187  * @param[in/out] input input buffers.
1188  * @note it reuses cleanInputbuffer().
1189  * @return 0 if no error, otherwise a negative errno.
1190  */
1191 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
1192 {
1193   INIT_HOST_HANDLER (host_handler, dev);
1194
1195   return host_handler->deallocGenericBuffer (input);
1196 }
1197
1198 /**
1199  * @brief Get metadata for NPU model
1200  * @param[in] model The path of model binary file
1201  * @param[in] need_extra whether you want to extract the extra data in metadata
1202  * @return the metadata structure to be filled if no error, otherwise nullptr
1203  *
1204  * @note For most npu-engine users, the extra data is not useful because it will be
1205  *       used for second-party users (e.g., compiler, simulator).
1206  *       Also, the caller needs to free the metadata.
1207  *
1208  * @note the caller needs to free the metadata
1209  */
1210 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
1211 {
1212   npubin_meta *meta;
1213   FILE *fp;
1214   size_t ret;
1215
1216   if (!model)
1217     return nullptr;
1218
1219   fp = fopen (model, "rb");
1220   if (!fp) {
1221     logerr (TAG, "Failed to open the model binary: %d\n", -errno);
1222     return nullptr;
1223   }
1224
1225   meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
1226   if (!meta) {
1227     logerr (TAG, "Failed to allocate metadata\n");
1228     goto exit_err;
1229   }
1230
1231   ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
1232   if (ret != NPUBIN_META_SIZE) {
1233     logerr (TAG, "Failed to read the metadata\n");
1234     goto exit_free;
1235   }
1236
1237   if (!CHECK_NPUBIN (meta->magiccode)) {
1238     logerr (TAG, "Invalid metadata provided\n");
1239     goto exit_free;
1240   }
1241
1242   if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
1243     npubin_meta *new_meta;
1244
1245     new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
1246     if (!new_meta) {
1247       logerr (TAG, "Failed to allocate extra metadata\n");
1248       goto exit_free;
1249     }
1250
1251     ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
1252     if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
1253       logerr (TAG, "Invalid extra metadata provided\n");
1254       free (new_meta);
1255       goto exit_err;
1256     }
1257
1258     meta = new_meta;
1259   }
1260
1261   fclose (fp);
1262
1263   return meta;
1264
1265 exit_free:
1266   free (meta);
1267 exit_err:
1268   fclose (fp);
1269
1270   return nullptr;
1271 }
1272
1273 /** deprecated buffer APIs; please use the above APIs */
1274
1275 /** @brief deprecated */
1276 int allocModelBuffer (generic_buffer *buffer)
1277 {
1278   logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
1279   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1280 }
1281
1282 /** @brief deprecated */
1283 int cleanModelBuffer (generic_buffer *buffer)
1284 {
1285   logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
1286   return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1287 }
1288
1289 /** @brief deprecated */
1290 int allocInputBuffer (generic_buffer *buffer)
1291 {
1292   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
1293   return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1294 }
1295
1296 /** @brief deprecated */
1297 int cleanInputBuffer (generic_buffer *buffer)
1298 {
1299   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
1300   return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1301 }
1302
1303 /** @brief deprecated */
1304 int allocInputBuffers (input_buffers * input)
1305 {
1306   logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
1307   return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1308 }
1309
1310 /** @brief deprecated */
1311 int cleanInputBuffers (input_buffers * input)
1312 {
1313   logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
1314   return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1315 }
1316
1317 /** @brief deprecated */
1318 int allocNPUBuffer (uint64_t size, buffer_types type,
1319     const char * filepath, generic_buffer *buffer)
1320 {
1321   if (buffer) {
1322     buffer->size = size;
1323     buffer->type = type;
1324     buffer->filepath = filepath;
1325   }
1326
1327   logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
1328   return allocModelBuffer (buffer);
1329 }
1330
1331 /** @brief deprecated */
1332 int cleanNPUBuffer (generic_buffer * buffer)
1333 {
1334   logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
1335   return cleanModelBuffer (buffer);
1336 }