Dawn Framework 1.0
Universal data acquisition framework for embedded systems
bitmerge.cxx
1// dawn/src/prog/bitmerge.cxx
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5
6#include "dawn/prog/bitmerge.hxx"
7
8#include <algorithm>
9#include <climits>
10#include <cstring>
11#include <new>
12
13#include "dawn/debug.hxx"
14#include "dawn/io/common.hxx"
15#include "dawn/io/ddata.hxx"
16
17using namespace dawn;
18
19static const size_t INPUT_WORDS = 3;
20static const uint32_t FIELD_BITS = sizeof(uint32_t) * CHAR_BIT;
21
22// Element widths with at least one enabled data type
23
24#if defined(CONFIG_DAWN_DTYPE_BOOL) || defined(CONFIG_DAWN_DTYPE_INT8) || \
25 defined(CONFIG_DAWN_DTYPE_UINT8)
26# define BITMERGE_HAVE_8BIT
27#endif
28
29#if defined(CONFIG_DAWN_DTYPE_INT16) || defined(CONFIG_DAWN_DTYPE_UINT16)
30# define BITMERGE_HAVE_16BIT
31#endif
32
33#if defined(CONFIG_DAWN_DTYPE_INT32) || defined(CONFIG_DAWN_DTYPE_UINT32)
34# define BITMERGE_HAVE_32BIT
35#endif
36
37// Integer or bool up to 32 bits: fields are merged as plain words
38
39static bool isMergeDtype(uint8_t dtype)
40{
41 switch (dtype)
42 {
43#ifdef CONFIG_DAWN_DTYPE_BOOL
45#endif
46#ifdef CONFIG_DAWN_DTYPE_INT8
48#endif
49#ifdef CONFIG_DAWN_DTYPE_UINT8
51#endif
52#ifdef CONFIG_DAWN_DTYPE_INT16
54#endif
55#ifdef CONFIG_DAWN_DTYPE_UINT16
57#endif
58#ifdef CONFIG_DAWN_DTYPE_INT32
60#endif
61#ifdef CONFIG_DAWN_DTYPE_UINT32
63#endif
64 return true;
65
66 default:
67 return false;
68 }
69}
70
71// Read element zero of a buffer as a plain word; init() rejected other widths
72
73static uint32_t readElem(io_ddata_t *data)
74{
75 switch (data->getSize())
76 {
77#ifdef BITMERGE_HAVE_8BIT
78 case 1:
79 {
80 return *static_cast<uint8_t *>(data->getDataPtr());
81 }
82#endif
83
84#ifdef BITMERGE_HAVE_16BIT
85 case 2:
86 {
87 return *static_cast<uint16_t *>(data->getDataPtr());
88 }
89#endif
90
91#ifdef BITMERGE_HAVE_32BIT
92 case 4:
93 {
94 return *static_cast<uint32_t *>(data->getDataPtr());
95 }
96#endif
97
98 default:
99 {
100 return 0;
101 }
102 }
103}
104
105// Store a merged word into element zero of a buffer
106
107static void writeElem(io_ddata_t *data, uint32_t word)
108{
109 switch (data->getSize())
110 {
111#ifdef BITMERGE_HAVE_8BIT
112 case 1:
113 {
114 *static_cast<uint8_t *>(data->getDataPtr()) = static_cast<uint8_t>(word);
115 break;
116 }
117#endif
118
119#ifdef BITMERGE_HAVE_16BIT
120 case 2:
121 {
122 *static_cast<uint16_t *>(data->getDataPtr()) = static_cast<uint16_t>(word);
123 break;
124 }
125#endif
126
127#ifdef BITMERGE_HAVE_32BIT
128 case 4:
129 {
130 *static_cast<uint32_t *>(data->getDataPtr()) = word;
131 break;
132 }
133#endif
134
135 default:
136 {
137 break;
138 }
139 }
140}
141
142// Merge a run of samples of one width: dst = ((src & mask) << shift) | orval
143
144template<typename T>
145static void mergeSamplesT(const void *in,
146 void *out,
147 size_t items,
148 uint32_t mask,
149 uint32_t shift,
150 uint32_t orval)
151{
152 const T *src = static_cast<const T *>(in);
153 T *dst = static_cast<T *>(out);
154 size_t i;
155
156 for (i = 0; i < items; i++)
157 {
158 dst[i] = static_cast<T>(((static_cast<uint32_t>(src[i]) & mask) << shift) | orval);
159 }
160}
161
162CProgBitMerge::CProgBitMerge(CDescObject &desc)
163 : CProgCommon(desc)
164 , output(nullptr)
165 , outputId(0)
166 , outputData(nullptr)
167 , streamIdx(NO_STREAM)
168 , batch(1)
169 , active(false)
170 , registered(false)
171{
172}
173
174CProgBitMerge::~CProgBitMerge()
175{
176 deinit();
177}
178
179int CProgBitMerge::allocInput(SObjectId::ObjectId ioId, uint32_t shift, uint32_t mask)
180{
181 SMergeInput inp;
182
183 inp.owner = this;
184 inp.io = nullptr;
185 inp.ioId = ioId;
186 inp.shift = shift;
187 inp.mask = mask;
188 inp.currentData = nullptr;
189
190 inputs.push_back(inp);
191 setObjectMapItem(ioId, nullptr);
192 return OK;
193}
194
195int CProgBitMerge::configureDesc(const CDescObject &desc)
196{
197 const SObjectCfg::SObjectCfgItem *item;
198 const SObjectId::UObjectId *ids;
199 const uint32_t *vals;
200 size_t offset;
201 size_t ii;
202 size_t n;
203
204 offset = 0;
205 for (ii = 0; ii < desc.getSize(); ii++)
206 {
207 item = desc.objectCfgItemNext(offset);
208
209 if (item->cfgid.s.cls != CProgCommon::PROG_CLASS_BITMERGE)
210 {
211 DAWNERR("bitmerge: unsupported cfg class 0x%" PRIx32 "\n", item->cfgid.v);
212 return -EINVAL;
213 }
214
215 switch (item->cfgid.s.id)
216 {
217 case PROG_BITMERGE_CFG_INPUTS:
218 {
219 n = static_cast<size_t>(item->cfgid.s.size);
220 if (n == 0 || n % INPUT_WORDS != 0)
221 {
222 DAWNERR("bitmerge: invalid INPUTS size %zu\n", n);
223 return -EINVAL;
224 }
225
226 vals = reinterpret_cast<const uint32_t *>(item->data);
227 for (size_t j = 0; j < n; j += INPUT_WORDS)
228 {
229 ids = reinterpret_cast<const SObjectId::UObjectId *>(&vals[j]);
230 int ret = allocInput(ids[0].v, vals[j + 1], vals[j + 2]);
231 if (ret != OK)
232 {
233 return ret;
234 }
235 }
236 break;
237 }
238
239 case PROG_BITMERGE_CFG_OUTPUT:
240 {
241 if (item->cfgid.s.size != 1)
242 {
243 DAWNERR("bitmerge: OUTPUT must have 1 entry\n");
244 return -EINVAL;
245 }
246
247 ids = reinterpret_cast<const SObjectId::UObjectId *>(item->data);
248 outputId = ids[0].v;
249 setObjectMapItem(outputId, nullptr);
250 break;
251 }
252
253 default:
254 {
255 DAWNERR("bitmerge: unsupported cfg id %u\n", item->cfgid.s.id);
256 return -EINVAL;
257 }
258 }
259 }
260
261 if (inputs.empty())
262 {
263 DAWNERR("bitmerge: at least one input required\n");
264 return -EINVAL;
265 }
266
267 if (outputId == 0)
268 {
269 DAWNERR("bitmerge: output IO not configured\n");
270 return -EINVAL;
271 }
272
273 return OK;
274}
275
277{
278 return configureDesc(getDesc());
279}
280
281int CProgBitMerge::checkFieldLayout(uint32_t width) const
282{
283 uint32_t used = 0;
284 size_t i;
285
286 for (i = 0; i < inputs.size(); i++)
287 {
288 uint32_t field;
289
290 if (inputs[i].mask == 0)
291 {
292 DAWNERR("bitmerge: input %zu has an empty mask\n", i);
293 return -EINVAL;
294 }
295
296 if (inputs[i].shift >= width)
297 {
298 DAWNERR("bitmerge: input %zu shift %" PRIu32 " out of range\n", i, inputs[i].shift);
299 return -EINVAL;
300 }
301
302 // Reject a mask shifted (even partly) out of the output word
303
304 field = inputs[i].mask << inputs[i].shift;
305 if ((field >> inputs[i].shift) != inputs[i].mask ||
306 (width < FIELD_BITS && (field >> width) != 0))
307 {
308 DAWNERR("bitmerge: input %zu field does not fit the word\n", i);
309 return -EINVAL;
310 }
311
312 if ((used & field) != 0)
313 {
314 DAWNERR("bitmerge: input %zu field overlaps an earlier one\n", i);
315 return -EINVAL;
316 }
317
318 used |= field;
319 }
320
321 return OK;
322}
323
325{
326 CIOCommon *io;
327 size_t outDim = 1;
328 size_t i;
329 int ret;
330
331 for (i = 0; i < inputs.size(); i++)
332 {
333 io = getIO(inputs[i].ioId);
334 if (!io)
335 {
336 DAWNERR("bitmerge: input IO 0x%" PRIx32 " not found\n", inputs[i].ioId);
337 return -EIO;
338 }
339
340 if (!io->isRead())
341 {
342 DAWNERR("bitmerge: input 0x%" PRIx32 " is not readable\n", inputs[i].ioId);
343 return -EINVAL;
344 }
345
346 if (!isMergeDtype(io->getDtype()))
347 {
348 DAWNERR(
349 "bitmerge: input 0x%" PRIx32 " unsupported dtype %u\n", inputs[i].ioId, io->getDtype());
350 return -EINVAL;
351 }
352
353 inputs[i].io = io;
354
355 // Batching is a property of the input. The batched one drives the
356 // output rate and shape; the rest are slow operands.
357
358 if (io->isBatch())
359 {
360 if (streamIdx != NO_STREAM)
361 {
362 DAWNERR("bitmerge: only one batched input is supported\n");
363 return -EINVAL;
364 }
365
366 // Batches only arrive through notifications
367
368 if (!io->isNotify())
369 {
370 DAWNERR("bitmerge: batched input 0x%" PRIx32 " is not notify-capable\n",
371 inputs[i].ioId);
372 return -EINVAL;
373 }
374
375 streamIdx = i;
376 batch = io->getNotifyBatch();
377 outDim = io->getDataDim();
378 }
379 else if (io->getDataDim() > 1)
380 {
381 // Only element zero of a slow input enters the merge
382
383 DAWNWARN("bitmerge: input 0x%" PRIx32 " dim %zu, using element 0\n",
384 inputs[i].ioId,
385 io->getDataDim());
386 }
387 }
388
389 io = getIO(outputId);
390 if (!io)
391 {
392 DAWNERR("bitmerge: output IO 0x%" PRIx32 " not found\n", outputId);
393 return -EIO;
394 }
395 output = io;
396
397 if (!isMergeDtype(output->getDtype()))
398 {
399 DAWNERR("bitmerge: output unsupported dtype %u\n", output->getDtype());
400 return -EINVAL;
401 }
402
403 if (streamIdx != NO_STREAM)
404 {
405 CIOCommon *src = inputs[streamIdx].io;
406
407 if (output->getDtypeSize() != src->getDtypeSize())
408 {
409 DAWNERR("bitmerge: output element size must match the batched input\n");
410 return -EINVAL;
411 }
412 }
413
414 // Fields must fit the real output width, not just a 32-bit word
415
416 ret = checkFieldLayout(output->getDtypeSize() * CHAR_BIT);
417 if (ret != OK)
418 {
419 return ret;
420 }
421
422 // Only a virt output can carry the batch, real IO writes batch 0 only
423
424 if (output->getCls() != CIOCommon::IO_CLASS_VIRT)
425 {
426 batch = 1;
427 }
428
429 ret = prepareWritableTarget(output, outDim, true, batch);
430 if (ret != OK)
431 {
432 DAWNERR("bitmerge: output target prepare failed %d\n", ret);
433 return ret;
434 }
435
436 for (i = 0; i < inputs.size(); i++)
437 {
438 inputs[i].currentData = inputs[i].io->ddata_alloc(1);
439 if (inputs[i].currentData == nullptr)
440 {
441 DAWNERR("bitmerge: currentData allocation failed for input %zu\n", i);
442 return -ENOMEM;
443 }
444 }
445
446 outputData = output->ddata_alloc(batch);
447 if (outputData == nullptr)
448 {
449 DAWNERR("bitmerge: outputData allocation failed\n");
450 return -ENOMEM;
451 }
452
453 return OK;
454}
455
457{
458 doStop();
459
460 for (size_t i = 0; i < inputs.size(); i++)
461 {
462 delete inputs[i].currentData;
463 inputs[i].currentData = nullptr;
464 }
465
466 inputs.clear();
467
468 delete outputData;
469 outputData = nullptr;
470 output = nullptr;
471 outputId = 0;
472 streamIdx = NO_STREAM;
473 batch = 1;
474 return OK;
475}
476
477int CProgBitMerge::ioNotifierCb(void *priv, io_ddata_t *data)
478{
479 SMergeInput *inp = static_cast<SMergeInput *>(priv);
480
481 if (inp == nullptr || inp->owner == nullptr || !inp->owner->active)
482 {
483 return OK;
484 }
485
486 if (inp->owner->streamIdx != NO_STREAM && inp == &inp->owner->inputs[inp->owner->streamIdx])
487 {
488 inp->owner->updateStream(data);
489 return OK;
490 }
491
492 // Slow inputs are re-read per merge; the next batch picks up a change
493
494 if (inp->owner->streamIdx == NO_STREAM)
495 {
496 inp->owner->updateScalar();
497 }
498
499 return OK;
500}
501
503{
504 size_t i;
505 int ret;
506
507 active = true;
508
509 if (!registered)
510 {
511 for (i = 0; i < inputs.size(); i++)
512 {
513 if (!inputs[i].io->isNotify())
514 {
515 continue;
516 }
517
518 ret = inputs[i].io->setNotifier(ioNotifierCb, 0, &inputs[i]);
519 if (ret != OK)
520 {
521 DAWNERR("bitmerge: setNotifier failed on input %zu: %d\n", i, ret);
522
523 // Undo the notifiers already set
524
525 while (i-- > 0)
526 {
527 if (inputs[i].io->isNotify())
528 {
529 inputs[i].io->setNotifier(nullptr, 0, nullptr);
530 }
531 }
532
533 active = false;
534 return ret;
535 }
536 }
537
538 registered = true;
539 }
540
541 if (streamIdx == NO_STREAM)
542 {
543 updateScalar();
544 }
545
546 return OK;
547}
548
550{
551 if (registered)
552 {
553 for (size_t i = 0; i < inputs.size(); i++)
554 {
555 if (inputs[i].io && inputs[i].io->isNotify())
556 {
557 inputs[i].io->setNotifier(nullptr, 0, nullptr);
558 }
559 }
560
561 registered = false;
562 }
563
564 active = false;
565 return OK;
566}
567
569{
570 return false;
571}
572
573int CProgBitMerge::mergeConstant(size_t skip, uint32_t &acc)
574{
575 size_t i;
576 int ret;
577
578 acc = 0;
579
580 for (i = 0; i < inputs.size(); i++)
581 {
582 if (i == skip || inputs[i].currentData == nullptr)
583 {
584 continue;
585 }
586
587 ret = inputs[i].io->getData(*inputs[i].currentData, 1);
588 if (ret != OK)
589 {
590 DAWNERR("bitmerge: getData failed for input 0x%" PRIx32 ": %d\n", inputs[i].ioId, ret);
591 return ret;
592 }
593
594 acc |= (readElem(inputs[i].currentData) & inputs[i].mask) << inputs[i].shift;
595 }
596
597 return OK;
598}
599
600void CProgBitMerge::updateScalar()
601{
602 uint32_t word;
603 int ret;
604
605 if (output == nullptr || outputData == nullptr)
606 {
607 return;
608 }
609
610 // Notifiers may fire from different threads; one lock per update
611
612 std::lock_guard<std::mutex> lock(mergeLock);
613
614 if (mergeConstant(NO_STREAM, word) != OK)
615 {
616 return;
617 }
618
619 writeElem(outputData, word);
620
621 ret = output->setData(*outputData);
622 if (ret != OK)
623 {
624 DAWNERR("bitmerge: setData on output failed %d\n", ret);
625 }
626}
627
628void CProgBitMerge::mergeBatch(const void *in,
629 void *out,
630 size_t items,
631 const SMergeInput *src,
632 uint32_t orval)
633{
634 switch (outputData->getSize())
635 {
636#ifdef BITMERGE_HAVE_8BIT
637 case 1:
638 {
639 mergeSamplesT<uint8_t>(in, out, items, src->mask, src->shift, orval);
640 break;
641 }
642#endif
643
644#ifdef BITMERGE_HAVE_16BIT
645 case 2:
646 {
647 mergeSamplesT<uint16_t>(in, out, items, src->mask, src->shift, orval);
648 break;
649 }
650#endif
651
652#ifdef BITMERGE_HAVE_32BIT
653 case 4:
654 {
655 mergeSamplesT<uint32_t>(in, out, items, src->mask, src->shift, orval);
656 break;
657 }
658#endif
659
660 default:
661 {
662 break;
663 }
664 }
665}
666
667void CProgBitMerge::updateStream(io_ddata_t *data)
668{
669 const SMergeInput *src;
670 uint32_t orval;
671 size_t nbatch;
672 size_t nitems;
673 size_t first;
674 size_t flat;
675 size_t b;
676 int ret;
677
678 if (data == nullptr || output == nullptr || outputData == nullptr)
679 {
680 return;
681 }
682
683 src = &inputs[streamIdx];
684
685 // One lock per batch, not per sample
686
687 std::lock_guard<std::mutex> lock(mergeLock);
688
689 // Slow inputs are read once per batch and folded into one constant
690
691 if (mergeConstant(streamIdx, orval) != OK)
692 {
693 return;
694 }
695
696 // An output holding fewer batches gets the latest samples
697
698 nbatch = std::min(data->getBatch(), outputData->getBatch());
699 first = data->getBatch() - nbatch;
700 nitems = std::min(data->getItems(), outputData->getItems());
701
702 // One flat pass when both sides are contiguous
703
704 flat = first == 0 ? contiguousCount(data, nbatch, nitems) : 0;
705 if (flat != 0 && contiguousCount(outputData, nbatch, nitems) == flat)
706 {
707 mergeBatch(data->getDataPtr(0), outputData->getDataPtr(0), flat, src, orval);
708 }
709 else
710 {
711 // Padded or timestamped batches are walked one by one
712
713 for (b = 0; b < nbatch; b++)
714 {
715 mergeBatch(data->getDataPtr(first + b), outputData->getDataPtr(b), nitems, src, orval);
716 }
717 }
718
719 if (outputData->hasTimestamp() && data->hasTimestamp())
720 {
721 for (b = 0; b < nbatch; b++)
722 {
723 outputData->getTs(b) = data->getTs(first + b);
724 }
725 }
726
727 ret = output->setData(*outputData);
728 if (ret != OK)
729 {
730 DAWNERR("bitmerge: setData on output failed %d\n", ret);
731 }
732}
CIOCommon * getIO(SObjectId::ObjectId id)
Get an I/O object by ID.
Definition bindable.cxx:41
void setObjectMapItem(SObjectId::ObjectId id, CObject *obj)
Set an item in the object map.
Definition bindable.cxx:23
Descriptor wrapper for individual object configuration.
size_t getSize() const
Get number of configuration items for this object.
SObjectCfg::SObjectCfgItem * objectCfgItemNext(size_t &offset) const
Get config item at current offset and advance past it.
Base class for all I/O objects.
Definition common.hxx:30
virtual bool isBatch() const =0
Check if IO supports batch operations.
virtual bool isNotify() const =0
Check if IO supports notifications.
virtual size_t getDataDim() const =0
Get data vector dimension.
virtual bool isRead() const =0
Check if IO supports read operations.
@ IO_CLASS_VIRT
Virtual I/O.
Definition common.hxx:217
CDescObject & getDesc()
Get descriptor object for this object.
Definition object.cxx:190
size_t getDtypeSize() const
Get size of this object's data type.
Definition object.cxx:195
uint8_t getDtype() const
Get data type field.
Definition object.cxx:175
int init()
One-time initialize object after bindings are resolved.
Definition bitmerge.cxx:324
bool hasThread() const
Check if a background thread is active.
Definition bitmerge.cxx:568
int doStart()
Start implementation hook.
Definition bitmerge.cxx:502
int configure()
Configure object from descriptor data.
Definition bitmerge.cxx:276
int deinit()
De-initialize object.
Definition bitmerge.cxx:456
int doStop()
Stop implementation hook.
Definition bitmerge.cxx:549
Base class for all PROG (processing) objects.
Definition common.hxx:28
int prepareWritableTarget(CIOCommon *io, size_t dim, bool notify, size_t batch=1)
Check a writable output; shape a deferred virt output or check an already shaped one.
Definition common.cxx:45
static size_t contiguousCount(io_ddata_t *d, size_t nbatch, size_t nitems)
Count elements of the first nbatch batches stored back to back.
Definition common.cxx:25
Out-of-tree user-extension hooks for Dawn.
Definition bindable.hxx:13
ObjectCfgData_t data[]
Configuration data array (flexible, size from cfgid.s.size).
UObjectCfgId cfgid
Configuration ID header (type, class, id, size, rw, dtype).
@ DTYPE_INT32
Signed 32-bit integer (-2147483648 to 2147483647).
Definition objectid.hxx:92
@ DTYPE_UINT8
Unsigned 8-bit integer (0 to 255).
Definition objectid.hxx:80
@ DTYPE_INT16
Signed 16-bit integer (-32768 to 32767).
Definition objectid.hxx:84
@ DTYPE_INT8
Signed 8-bit integer (-128 to 127).
Definition objectid.hxx:76
@ DTYPE_UINT16
Unsigned 16-bit integer (0 to 65535).
Definition objectid.hxx:88
@ DTYPE_UINT32
Unsigned 32-bit integer (0 to 4294967295).
Definition objectid.hxx:96
@ DTYPE_BOOL
Boolean data type (stored in 32-bit container).
Definition objectid.hxx:72
uint32_t ObjectId
ObjectID type - single 32-bit value.
Definition objectid.hxx:44
Heap-allocated dynamic I/O data buffer.
Definition ddata.hxx:21
void * getDataPtr(size_t batch=0)
Get pointer to data only (skips timestamp if present).
Definition ddata.hxx:180
bool hasTimestamp()
Check if this buffer has per-batch timestamp storage.
Definition ddata.hxx:188
size_t getSize() const
Get element size in bytes.
Definition ddata.hxx:121
size_t getItems()
Get number of items per batch.
Definition ddata.hxx:128
size_t getBatch()
Get number of batches.
Definition ddata.hxx:135
io_ts_t & getTs(size_t batch=0)
Get timestamp reference for batch.
Definition ddata.hxx:203
ObjectCfgId v
Raw 32-bit ConfigID value (for storage, comparison).
Definition objectcfg.hxx:82
uint32_t cls
Object class (bits 21-29, max 511).
uint32_t id
Configuration identifier (bits 0-4, max 31).
Definition objectcfg.hxx:94
struct dawn::SObjectCfg::UObjectCfgId::@334307326077356333363326153167141302007100111136 s
Bit-field structure for named member access.
uint32_t size
Configuration data size in 32-bit words (bits 5-14, max 1023).
ObjectId v
Raw 32-bit ObjectID value (for comparison, hashing, storage).
Definition objectid.hxx:221