forked from PX4/DriverFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDriverFramework.cpp
More file actions
502 lines (381 loc) · 11.1 KB
/
DriverFramework.cpp
File metadata and controls
502 lines (381 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/**********************************************************************
* Copyright (c) 2015 Mark Charlebois
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the
* disclaimer below) provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Dronecode Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
* GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include "DriverFramework.hpp"
#include "DevObj.hpp"
#include "DevMgr.hpp"
#include "SyncObj.hpp"
#include "WorkItems.hpp"
#ifdef __DF_LINUX
#include <sys/prctl.h>
#endif
// Used for backtrace
#ifdef DF_ENABLE_BACKTRACE
#include <stdlib.h>
#include <execinfo.h>
#endif
#define SHOW_STATS 0
namespace DriverFramework
{
//-----------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------
class HRTWorkQueue : public DisableCopy
{
public:
static HRTWorkQueue &instance();
int initialize();
void finalize();
void scheduleWorkItem(WorkHandle &wh);
void shutdown();
void enableStats(bool enable);
static void *process_trampoline(void * /*arg*/);
private:
HRTWorkQueue() = default;
~HRTWorkQueue() = default;
void process();
bool m_enable_stats = false;
SyncObj m_reschedule;
};
};
using namespace DriverFramework;
//-----------------------------------------------------------------------
// Global Variables
//-----------------------------------------------------------------------
namespace DriverFramework
{
RunStatus *g_run_status = nullptr;
};
//-----------------------------------------------------------------------
// Static Variables
//-----------------------------------------------------------------------
static pthread_t g_tid;
// QuRT C++ compiler does not support static initialization of classes
static SyncObj *g_framework;
//-----------------------------------------------------------------------
// Static Functions
//-----------------------------------------------------------------------
static uint64_t TsToAbstime(struct timespec *ts)
{
uint64_t result = (uint64_t)(ts->tv_sec) * 1000000UL;
result += ts->tv_nsec / 1000;
return result;
}
static uint64_t starttime = 0;
static void initStartTime()
{
struct timespec ts = {};
int ret = absoluteTime(ts);
if (ret != 0) {
printf("ERROR: absoluteTime returned (%d)\n", ret);
return;
}
starttime = TsToAbstime(&ts);
}
static inline uint64_t getStartTime()
{
return starttime;
}
//-----------------------------------------------------------------------
// Global Functions
//-----------------------------------------------------------------------
// NOTE: DO NOT USE DF_LOG_XXX here as it will cause a recursive loop
uint64_t DriverFramework::offsetTime()
{
struct timespec ts = {};
int ret = absoluteTime(ts);
if (ret != 0) {
printf("ERROR: absoluteTime returned (%d)", ret);
return 0;
}
// Time is in microseconds
uint64_t result = TsToAbstime(&ts) - getStartTime();
return result;
}
timespec DriverFramework::offsetTimeToAbsoluteTime(uint64_t offset_time)
{
struct timespec ts = {};
uint64_t abs_time = offset_time + getStartTime();
ts.tv_sec = abs_time / 1000000;
ts.tv_nsec = (abs_time % 1000000) * 1000;
return ts;
}
#if DF_ENABLE_BACKTRACE
void DriverFramework::backtrace()
{
void *buffer[10];
char **callstack;
int bt_size;
int idx;
bt_size = ::backtrace(buffer, 10);
callstack = ::backtrace_symbols(buffer, bt_size);
DF_LOG_INFO("Backtrace: %d", bt_size);
for (idx = 0; idx < bt_size; idx++) {
DF_LOG_INFO("%s", callstack[idx]);
}
free(callstack);
}
#endif
//-----------------------------------------------------------------------
// Class Methods
//-----------------------------------------------------------------------
/*************************************************************************
RunStatus
*************************************************************************/
bool RunStatus::check()
{
m_lock.lock();
bool ret = m_run;
m_lock.unlock();
return ret;
}
void RunStatus::terminate()
{
m_lock.lock();
m_run = false;
m_lock.unlock();
}
/*************************************************************************
Framework
*************************************************************************/
void Framework::shutdown()
{
// Free the HRTWorkQueue resources
HRTWorkQueue::instance().finalize();
// Free the WorkMgr resources
WorkMgr::finalize();
// Free the DevMgr resources
DevMgr::finalize();
// allow Framework to exit
g_framework->lock();
g_framework->signal();
g_framework->unlock();
}
int Framework::initialize()
{
initStartTime(); // must be initialized before any other timing methods are called
DF_LOG_DEBUG("Framework::initialize");
g_framework = new SyncObj;
if (!g_framework) {
DF_LOG_ERR("ERROR: falled to allocate g_framework");
return -1;
}
g_run_status = new RunStatus;
if (!g_run_status) {
DF_LOG_ERR("g_run_status allocation failed");
return -2;
}
struct timespec ts = {};
int ret = absoluteTime(ts);
if (ret != 0) {
DF_LOG_ERR("ERROR: absoluteTime returned (%d)", ret);
return -4;
}
ret = HRTWorkQueue::instance().initialize();
if (ret < 0) {
return ret - 10;
}
DF_LOG_DEBUG("Calling DevMgr::initialize");
ret = DevMgr::initialize();
if (ret < 0) {
return ret - 20;
}
DF_LOG_DEBUG("Calling WorkMgr::initialize");
ret = WorkMgr::initialize();
if (ret < 0) {
return ret - 30;
}
return 0;
}
void Framework::waitForShutdown()
{
// Block until shutdown requested
g_framework->lock();
g_framework->waitOnSignal(nullptr);
g_framework->unlock();
delete g_framework;
g_framework = nullptr;
}
/*************************************************************************
HRTWorkQueue
*************************************************************************/
#ifndef __DF_QURT
// pthread_setschedparam does not seem to work on QURT.
static void show_sched_settings()
{
int policy;
struct sched_param param {};
int ret = pthread_getschedparam(pthread_self(), &policy, ¶m);
if (ret != 0) {
DF_LOG_ERR("pthread_getschedparam failed (%d)", ret);
}
DF_LOG_DEBUG("pthread info: policy=%s priority=%d",
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
(policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
"UNKNOWN",
param.sched_priority);
}
static int setRealtimeSched()
{
int policy = SCHED_FIFO;
sched_param param {};
param.sched_priority = sched_get_priority_max(SCHED_FIFO);
int ret = pthread_setschedparam(pthread_self(), policy, ¶m);
show_sched_settings();
return ret;
}
#endif
void *HRTWorkQueue::process_trampoline(void *arg)
{
DF_LOG_DEBUG("HRTWorkQueue::process_trampoline");
#ifndef __DF_QURT
int ret = setRealtimeSched();
if (ret != 0) {
DF_LOG_ERR("WARNING: setRealtimeSched failed (not run as root?)");
}
#endif
#ifdef __DF_LINUX
prctl(PR_SET_NAME, "DFWorker"); //set the thread name
#endif
DF_LOG_DEBUG("process_trampoline %d", ret);
instance().process();
return nullptr;
}
HRTWorkQueue &HRTWorkQueue::instance()
{
static HRTWorkQueue *instance = nullptr;
if (!instance) {
instance = new HRTWorkQueue();
}
return *instance;
}
int HRTWorkQueue::initialize()
{
DF_LOG_DEBUG("HRTWorkQueue::initialize");
pthread_attr_t attr {};
int ret = pthread_attr_init(&attr);
if (ret != 0) {
DF_LOG_ERR("pthread_attr_init failed");
return -1;
}
#ifdef __DF_QURT
// Try to set a stack size. This stack size is later used in _measure() calls
// in the sensor drivers, at least on QURT.
const size_t stacksize = 3072;
if (pthread_attr_setstacksize(&attr, stacksize) != 0) {
DF_LOG_ERR("failed to set stack size of %lu bytes", stacksize);
return -2;
}
#endif
// Create high priority worker thread
if (pthread_create(&g_tid, &attr, process_trampoline, nullptr)) {
return -3;
}
DF_LOG_DEBUG("pthread_create success");
return 0;
}
void HRTWorkQueue::finalize()
{
DF_LOG_DEBUG("HRTWorkQueue::finalize");
shutdown();
// Wait for work queue thread to exit
pthread_join(g_tid, nullptr);
}
void HRTWorkQueue::scheduleWorkItem(WorkHandle &wh)
{
DF_LOG_DEBUG("HRTWorkQueue::scheduleWorkItem (%p)", &wh);
// Handle is known to be valid
int ret = WorkItems::schedule(wh.m_handle);
DF_LOG_DEBUG("WorkItems::schedule %d", ret);
if (ret == 0) {
wh.m_errno = 0;
m_reschedule.lock();
m_reschedule.signal();
m_reschedule.unlock();
} else if (ret == EBADF) {
wh.m_errno = EBADF;
wh.m_handle = -1;
} else {
wh.m_errno = ret;
}
}
void HRTWorkQueue::shutdown()
{
DF_LOG_DEBUG("HRTWorkQueue::shutdown");
if (g_run_status) {
g_run_status->terminate();
}
m_reschedule.lock();
m_reschedule.signal();
m_reschedule.unlock();
}
void HRTWorkQueue::process()
{
DF_LOG_DEBUG("HRTWorkQueue::process");
uint64_t next;
uint64_t now;
while (g_run_status && g_run_status->check()) {
now = offsetTime();
// Wake up every 10 sec if nothing scheduled
next = now + 10000000;
WorkItems::processExpiredWorkItems(next);
struct timespec next_ts = offsetTimeToAbsoluteTime(next);
#ifdef __DF_QURT
// to accomodate sleep inaccuracy in the platform
if (next > now + 200) {
#else
if (next > now) {
#endif
DF_LOG_DEBUG("HRTWorkQueue::process waiting until (%" PRIi64 "usec)", next);
// Wait until next expiry or until a new item is rescheduled
m_reschedule.lock();
m_reschedule.waitOnSignal(&next_ts);
m_reschedule.unlock();
DF_LOG_DEBUG("HRTWorkQueue::process done wait");
}
DF_LOG_DEBUG("HRTWorkQueue::process not waiting for work");
}
};
// This has to be in ths file to access HRTWorkQueue::scheduleWorkItem
int WorkMgr::schedule(DriverFramework::WorkHandle &wh)
{
DF_LOG_DEBUG("WorkMgr::schedule");
HRTWorkQueue::instance().scheduleWorkItem(wh);
return (wh.m_errno == 0) ? 0 : -1;
}