rogue
Loading...
Searching...
No Matches
Prbs.cpp
Go to the documentation of this file.
1
17#include "rogue/Directives.h"
18
20
21#include <inttypes.h>
22#include <stdarg.h>
23#include <sys/time.h>
24#include <unistd.h>
25
26#include <cstdio>
27#include <cstring>
28#include <memory>
29
30#include "rogue/GeneralError.h"
31#include "rogue/GilRelease.h"
32#include "rogue/Logging.h"
39
41namespace ru = rogue::utilities;
42
43#ifndef NO_PYTHON
44 #include <boost/python.hpp>
45namespace bp = boost::python;
46#endif
47
49ru::PrbsPtr ru::Prbs::create() {
50 ru::PrbsPtr p = std::make_shared<ru::Prbs>();
51 return (p);
52}
53
55ru::Prbs::Prbs() {
56 txThread_ = NULL;
57 rxSeq_ = 0;
58 rxErrCount_ = 0;
59 rxCount_ = 0;
60 rxBytes_ = 0;
61 rxEnable_ = true;
62 txSeq_ = 0;
63 txSize_ = 0;
64 txErrCount_ = 0;
65 txCount_ = 0;
66 txBytes_ = 0;
67 checkPl_ = true;
68 genPl_ = true;
69 rxLog_ = rogue::Logging::create("prbs.rx");
70 txLog_ = rogue::Logging::create("prbs.tx");
71 txPeriod_ = 0;
72
73 // Init width = 32
74 width_ = 32;
75 byteWidth_ = 4;
76 minSize_ = 12;
77 sendCount_ = false;
78
79 // Init 4 taps
80 tapCnt_ = 4;
81 taps_ = reinterpret_cast<uint8_t*>(malloc(sizeof(uint8_t) * tapCnt_));
82 taps_[0] = 1;
83 taps_[1] = 2;
84 taps_[2] = 6;
85 taps_[3] = 31;
86
87 gettimeofday(&lastRxTime_, NULL);
88 gettimeofday(&lastTxTime_, NULL);
89
90 lastRxCount_ = 0;
91 lastRxBytes_ = 0;
92 rxRate_ = 0.0;
93 rxBw_ = 0.0;
94
95 lastTxCount_ = 0;
96 lastTxBytes_ = 0;
97 txRate_ = 0.0;
98 txBw_ = 0.0;
99}
100
102ru::Prbs::~Prbs() {
103 // disable() joins the TX thread; otherwise it would outlive taps_/threadEn_.
104 disable();
105 free(taps_);
106}
107
109double ru::Prbs::updateTime(struct timeval* last) {
110 struct timeval cmp;
111 struct timeval now;
112 struct timeval per;
113 double ret;
114
115 cmp.tv_sec = 1;
116 cmp.tv_usec = 0;
117
118 gettimeofday(&now, NULL);
119
120 timersub(&now, last, &per);
121
122 if (timercmp(&per, &cmp, >)) {
123 ret = static_cast<float>(per.tv_sec) + static_cast<float>(per.tv_usec) / 1e6;
124 gettimeofday(last, NULL);
125 } else {
126 ret = 0.0;
127 }
128 return ret;
129}
130
132void ru::Prbs::setWidth(uint32_t width) {
133 if ((width > (MaxBytes * 8)) || (width % 32) != 0) throw(rogue::GeneralError("Prbs::setWidth", "Invalid width."));
134
135 rogue::GilRelease noGil;
136 std::lock_guard<std::mutex> lockT(pMtx_);
137
138 width_ = width;
139 byteWidth_ = width / 8;
140 minSize_ = byteWidth_ * 3;
141}
142
144void ru::Prbs::setTaps(uint32_t tapCnt, uint8_t* taps) {
145 uint32_t i;
146
147 rogue::GilRelease noGil;
148 std::lock_guard<std::mutex> lockT(pMtx_);
149
150 free(taps_);
151 tapCnt_ = tapCnt;
152 taps_ = reinterpret_cast<uint8_t*>(malloc(sizeof(uint8_t) * tapCnt));
153
154 for (i = 0; i < tapCnt_; i++) taps_[i] = taps[i];
155}
156
157#ifndef NO_PYTHON
158
160void ru::Prbs::setTapsPy(boost::python::object p) {
161 Py_buffer pyBuf;
162
163 if (PyObject_GetBuffer(p.ptr(), &pyBuf, PyBUF_SIMPLE) < 0)
164 throw(rogue::GeneralError("Prbs::setTapsPy", "Python Buffer Error"));
165
166 setTaps(pyBuf.len, reinterpret_cast<uint8_t*>(pyBuf.buf));
167 PyBuffer_Release(&pyBuf);
168}
169
170#endif
171
173void ru::Prbs::sendCount(bool state) {
174 rogue::GilRelease noGil;
175 std::lock_guard<std::mutex> lockT(pMtx_);
176
177 sendCount_ = state;
178}
179
180void ru::Prbs::flfsr(uint8_t* data) {
181 uint32_t iByte;
182 uint32_t iBit;
183 uint32_t x;
184 bool msbOut;
185 bool lsbIn = false;
186
187 for (x = 0; x < tapCnt_; x++) {
188 iByte = taps_[x] / 8;
189 iBit = taps_[x] % 8;
190 lsbIn ^= ((data[iByte] >> iBit) & 0x1);
191 }
192
193 for (x = 0; x < byteWidth_; x++) {
194 msbOut = data[x] & 0x80;
195 data[x] <<= 1;
196 data[x] |= lsbIn;
197 lsbIn = msbOut;
198 }
199}
200
202void ru::Prbs::runThread() {
203 txLog_->logThreadId();
204
205 while (threadEn_) {
206 // enable() validated txSize_ against byteWidth_/minSize_ once, but
207 // setWidth() may change them while this thread runs. genFrame()
208 // re-validates and throws; an uncaught throw here calls
209 // std::terminate(), so stop the generator instead.
210 try {
211 genFrame(txSize_);
212 } catch (rogue::GeneralError& e) {
213 txLog_->error("Frame generation failed, stopping: %s", e.what());
214 threadEn_ = false;
215 break;
216 }
217 if ( txPeriod_ > 0 ) usleep(txPeriod_);
218 }
219}
220
222void ru::Prbs::enable(uint32_t size) {
223 // Verify size first
224 if (((size % byteWidth_) != 0) || size < minSize_) throw rogue::GeneralError("Prbs::enable", "Invalid frame size");
225
226 if (txThread_ == NULL) {
227 txSize_ = size;
228 threadEn_ = true;
229 txThread_ = new std::thread(&Prbs::runThread, this);
230
231 // Set a thread name
232#ifndef __MACH__
233 pthread_setname_np(txThread_->native_handle(), "PrbsTx");
234#endif
235 }
236}
237
239void ru::Prbs::disable() {
240 if (txThread_ != NULL) {
241 rogue::GilRelease noGil;
242 threadEn_ = false;
243 txThread_->join();
244 delete txThread_;
245 txThread_ = NULL;
246 }
247}
248
250bool ru::Prbs::getRxEnable() {
251 return rxEnable_;
252}
253
255void ru::Prbs::setRxEnable(bool en) {
256 rogue::GilRelease noGil;
257 pMtx_.lock();
258 rxEnable_ = en;
259 pMtx_.unlock();
260}
261
263uint32_t ru::Prbs::getRxErrors() {
264 return (rxErrCount_);
265}
266
268uint32_t ru::Prbs::getRxCount() {
269 return (rxCount_);
270}
271
273uint64_t ru::Prbs::getRxBytes() {
274 return (rxBytes_);
275}
276
278uint32_t ru::Prbs::getTxErrors() {
279 return (txErrCount_);
280}
281
283uint32_t ru::Prbs::getTxCount() {
284 return (txCount_);
285}
286
288double ru::Prbs::getRxRate() {
289 return rxRate_;
290}
291
293double ru::Prbs::getRxBw() {
294 return rxBw_;
295}
296
298double ru::Prbs::getTxRate() {
299 return txRate_;
300}
301
303uint32_t ru::Prbs::getTxPeriod() {
304 return txPeriod_;
305}
306
308void ru::Prbs::setTxPeriod(uint32_t value) {
309 txPeriod_ = value;
310}
311
313double ru::Prbs::getTxBw() {
314 return txBw_;
315}
316
318uint64_t ru::Prbs::getTxBytes() {
319 return (txBytes_);
320}
321
323void ru::Prbs::checkPayload(bool state) {
324 checkPl_ = state;
325}
326
328void ru::Prbs::genPayload(bool state) {
329 genPl_ = state;
330}
331
333// Counters should really be locked!
334void ru::Prbs::resetCount() {
335 rogue::GilRelease noGil;
336 pMtx_.lock();
337 txErrCount_ = 0;
338 txCount_ = 0;
339 txBytes_ = 0;
340 rxErrCount_ = 0;
341 rxCount_ = 0;
342 rxBytes_ = 0;
343 pMtx_.unlock();
344}
345
347void ru::Prbs::genFrame(uint32_t size) {
348 ris::FrameIterator frIter;
349 ris::FrameIterator frEnd;
350 uint32_t frSeq[MaxBytes / 4];
351 uint32_t frSize[MaxBytes / 4];
352 uint32_t wCount[MaxBytes / 4];
353 uint8_t data[MaxBytes];
354 double per;
355 ris::FramePtr fr;
356
357 rogue::GilRelease noGil;
358 std::lock_guard<std::mutex> lock(pMtx_);
359
360 // Verify size first
361 if (((size % byteWidth_) != 0) || size < minSize_)
362 throw rogue::GeneralError("Prbs::genFrame", "Invalid frame size");
363
364 // Setup size
365 memset(frSize, 0, MaxBytes);
366 frSize[0] = (size / byteWidth_) - 1;
367
368 // Setup sequence
369 memset(frSeq, 0, MaxBytes);
370 frSeq[0] = txSeq_;
371
372 // Setup counter
373 memset(wCount, 0, MaxBytes);
374
375 // Get frame
376 fr = reqFrame(size, true);
377 fr->setPayload(size);
378
379 frIter = fr->begin();
380 frEnd = frIter + size;
381
382 // First word is sequence
383 ris::toFrame(frIter, byteWidth_, frSeq);
384 ++wCount[0];
385
386 // Second word is size
387 ris::toFrame(frIter, byteWidth_, frSize);
388 ++wCount[0];
389
390 if (genPl_) {
391 // Init data
392 std::memcpy(data, frSeq, byteWidth_);
393
394 // Generate payload
395 while (frIter != frEnd) {
396 if (sendCount_) {
397 ris::toFrame(frIter, byteWidth_, wCount);
398 } else {
399 flfsr(data);
400 ris::toFrame(frIter, byteWidth_, data);
401 }
402 ++wCount[0];
403 }
404 }
405
406 sendFrame(fr);
407
408 // Update counters
409 txSeq_++;
410 txCount_++;
411 txBytes_ += size;
412
413 if ((per = updateTime(&lastTxTime_)) > 0.0) {
414 txRate_ = static_cast<double>(txCount_ - lastTxCount_) / per;
415 txBw_ = static_cast<double>(txBytes_ - lastTxBytes_) / per;
416 lastTxCount_ = txCount_;
417 lastTxBytes_ = txBytes_;
418 }
419}
420
422void ru::Prbs::acceptFrame(ris::FramePtr frame) {
423 ris::FrameIterator frIter;
424 ris::FrameIterator frEnd;
425 uint32_t frSeq[MaxBytes / 4];
426 uint32_t frSize[MaxBytes / 4];
427 uint32_t expSeq;
428 uint32_t expSize;
429 uint32_t size;
430 uint32_t pos;
431 uint32_t x;
432 uint8_t expData[MaxBytes];
433 double per;
434 char debugA[10000];
435 char debugB[1000];
436
437 rogue::GilRelease noGil;
438
439 while (!rxEnable_) usleep(10000);
440
441 ris::FrameLockPtr fLock = frame->lock();
442 std::lock_guard<std::mutex> lock(pMtx_);
443
444 size = frame->getPayload();
445 frIter = frame->begin();
446 frEnd = frame->end();
447
448 // Check for frame errors
449 if (frame->getError()) {
450 rxLog_->warning("Frame error field is set: 0x%" PRIx8, frame->getError());
451 rxErrCount_++;
452 return;
453 }
454
455 // Verify size
456 if (((size % byteWidth_) != 0) || size < minSize_) {
457 rxLog_->warning("Size violation size=%" PRIu32 ", count=%" PRIu32, size, rxCount_);
458 rxErrCount_++;
459 return;
460 }
461
462 // First word is sequence
463 ris::fromFrame(frIter, byteWidth_, frSeq);
464 expSeq = rxSeq_;
465 rxSeq_ = frSeq[0] + 1;
466
467 // Second word is size
468 ris::fromFrame(frIter, byteWidth_, frSize);
469 expSize = (frSize[0] + 1) * byteWidth_;
470
471 // Check size and sequence
472 // Accept any sequence if our local count is zero
473 // incoming frames with seq = 0 never cause errors and treated as a restart
474 if ((expSize != size) || (frSeq[0] != 0 && expSeq != 0 && frSeq[0] != expSeq)) {
475 rxLog_->warning("Bad header. expSize=%" PRIu32 " gotSize=%" PRIu32 " expSeq=%" PRIu32 " gotSeq=%" PRIu32
476 " nxtSeq=%" PRIu32 " count=%" PRIu32,
477 expSize,
478 size,
479 expSeq,
480 frSeq[0],
481 rxSeq_,
482 rxCount_);
483 rxErrCount_++;
484 return;
485 }
486
487 // Is payload checking enabled
488 if (checkPl_) {
489 // Init data
490 std::memcpy(expData, frSeq, byteWidth_);
491 pos = 0;
492
493 // Read payload
494 while (frIter != frEnd) {
495 flfsr(expData);
496
497 if (!std::equal(frIter, frIter + byteWidth_, expData)) {
498 snprintf(debugA,
499 sizeof(debugA),
500 "Bad value at index %" PRIu32 ". count=%" PRIu32 ", size=%" PRIu32,
501 pos,
502 rxCount_,
503 (size / byteWidth_) - 1);
504
505 for (x = 0; x < byteWidth_; x++) {
506 snprintf(debugB,
507 sizeof(debugB),
508 "\n %" PRIu32 ":%" PRIu32 " Got=0x%" PRIx8 " Exp=0x%" PRIx8,
509 pos,
510 x,
511 *(frIter + x),
512 *(expData + x));
513 snprintf(debugA + strlen(debugA), sizeof(debugA) - strlen(debugA), "%s", debugB);
514 }
515 rxLog_->warning(debugA);
516 rxErrCount_++;
517 return;
518 }
519 frIter += byteWidth_;
520 ++pos;
521 }
522 }
523
524 rxCount_++;
525 rxBytes_ += size;
526
527 if ((per = updateTime(&lastRxTime_)) > 0.0) {
528 rxRate_ = static_cast<double>(rxCount_ - lastRxCount_) / per;
529 rxBw_ = static_cast<double>(rxBytes_ - lastRxBytes_) / per;
530 lastRxCount_ = rxCount_;
531 lastRxBytes_ = rxBytes_;
532 }
533}
534
535void ru::Prbs::setup_python() {
536#ifndef NO_PYTHON
537 // Keep the manual method docstrings, but suppress Boost.Python's generated
538 // Python/C++ signatures. The autogenerated forms are not very readable in
539 // the Sphinx Python API pages for exported C++ classes.
540 bp::docstring_options doc_options(true, false, false);
541
542 bp::class_<ru::Prbs, ru::PrbsPtr, bp::bases<ris::Master, ris::Slave>, boost::noncopyable>(
543 "Prbs",
544 "PRBS generator/checker that can act as both stream master and slave.\n\n"
545 "The engine can generate deterministic pseudo-random frames and verify\n"
546 "received frames for bit-error testing. It supports both one-shot frame\n"
547 "generation and optional background transmit mode.",
548 bp::init<>("Construct a PRBS generator/checker with default taps and width."))
549 .def("genFrame", &ru::Prbs::genFrame, bp::args("size"), "Generate and transmit one PRBS frame.")
550 .def("enable",
551 &ru::Prbs::enable,
552 bp::args("size"),
553 "Enable periodic background PRBS frame generation using the configured TX period.")
554 .def("disable", &ru::Prbs::disable, "Disable periodic background PRBS frame generation.")
555 .def("setWidth", &ru::Prbs::setWidth, bp::args("width"), "Set the PRBS generator/checker width in bits.")
556 .def("setTaps",
557 &ru::Prbs::setTapsPy,
558 bp::args("taps"),
559 "Configure the PRBS LFSR tap positions from a bytes-like object.")
560 .def("getRxEnable", &ru::Prbs::getRxEnable, "Return whether receive-side checking is enabled.")
561 .def("setRxEnable", &ru::Prbs::setRxEnable, bp::args("state"), "Enable or disable receive-side checking.")
562 .def("getRxErrors", &ru::Prbs::getRxErrors, "Return the receive-side error count.")
563 .def("getRxCount", &ru::Prbs::getRxCount, "Return the total received frame count.")
564 .def("getRxRate", &ru::Prbs::getRxRate, "Return the computed receive frame rate in frames/second.")
565 .def("getRxBw", &ru::Prbs::getRxBw, "Return the computed receive bandwidth in bytes/second.")
566 .def("getRxBytes", &ru::Prbs::getRxBytes, "Return the total received payload byte count.")
567 .def("getTxErrors", &ru::Prbs::getTxErrors, "Return the transmit-side error count.")
568 .def("getTxCount", &ru::Prbs::getTxCount, "Return the total transmitted frame count.")
569 .def("getTxBytes", &ru::Prbs::getTxBytes, "Return the total transmitted payload byte count.")
570 .def("getTxPeriod", &ru::Prbs::getTxPeriod, "Return the periodic transmit interval in microseconds.")
571 .def("setTxPeriod",
572 &ru::Prbs::setTxPeriod,
573 bp::args("period"),
574 "Set the periodic transmit interval in microseconds.")
575 .def("getTxRate", &ru::Prbs::getTxRate, "Return the computed transmit frame rate in frames/second.")
576 .def("getTxBw", &ru::Prbs::getTxBw, "Return the computed transmit bandwidth in bytes/second.")
577 .def("checkPayload",
578 &ru::Prbs::checkPayload,
579 bp::args("state"),
580 "Enable or disable PRBS payload checking on received frames.")
581 .def("genPayload",
582 &ru::Prbs::genPayload,
583 bp::args("state"),
584 "Enable or disable PRBS payload generation on transmitted frames.")
585 .def("resetCount", &ru::Prbs::resetCount, "Reset transmit and receive counters.")
586 .def("sendCount",
587 &ru::Prbs::sendCount,
588 bp::args("state"),
589 "Enable or disable insertion of frame counters into generated payloads.");
590
591 bp::implicitly_convertible<ru::PrbsPtr, ris::SlavePtr>();
592 bp::implicitly_convertible<ru::PrbsPtr, ris::MasterPtr>();
593#endif
594}
Generic Rogue exception type.
char const * what() const
Returns exception text for standard exception handling.
RAII helper that releases the Python GIL for a scope.
Definition GilRelease.h:36
static std::shared_ptr< rogue::Logging > create(const std::string &name, bool quiet=false)
Creates a logger instance.
Definition Logging.cpp:95
Random-access byte iterator across a Frame payload.
static void fromFrame(rogue::interfaces::stream::FrameIterator &iter, uint32_t size, void *dst)
Copies bytes from a frame iterator to a destination pointer.
std::shared_ptr< rogue::interfaces::stream::Frame > FramePtr
Shared pointer alias for Frame.
Definition Frame.h:549
static void toFrame(rogue::interfaces::stream::FrameIterator &iter, uint32_t size, void *src)
Copies bytes from a source pointer into a frame iterator.
std::shared_ptr< rogue::interfaces::stream::FrameLock > FrameLockPtr
Shared pointer alias for FrameLock.
Definition FrameLock.h:110
std::shared_ptr< rogue::utilities::Prbs > PrbsPtr
Definition Prbs.h:332