F´ Flight Software - C/C++ Documentation
A framework for building embedded system applications to NASA flight quality standards.
Task.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // \title Os/Posix/Task.cpp
3 // \brief implementation of Posix implementation of Os::Task
4 // ======================================================================
5 #include <pthread.h>
6 #include <unistd.h>
7 #include <cerrno>
8 #include <climits>
9 #include <cstring>
10 
11 #include "Fw/Logger/Logger.hpp"
12 #include "Fw/Types/Assert.hpp"
13 #include "Os/Posix/Task.hpp"
14 #include "Os/Posix/error.hpp"
15 #include "Os/Task.hpp"
16 
17 namespace Os {
18 namespace Posix {
19 namespace Task {
20 std::atomic<bool> PosixTask::s_permissions_reported(false);
21 static const int SCHED_POLICY = SCHED_RR;
22 
23 typedef void* (*pthread_func_ptr)(void*);
24 
25 void* pthread_entry_wrapper(void* wrapper_pointer) {
26  FW_ASSERT(wrapper_pointer != nullptr);
27  Os::Task::TaskRoutineWrapper& wrapper = *reinterpret_cast<Os::Task::TaskRoutineWrapper*>(wrapper_pointer);
28  wrapper.run(&wrapper);
29  return nullptr;
30 }
31 
32 int set_stack_size(pthread_attr_t& attributes, const Os::Task::Arguments& arguments) {
33  int status = PosixTaskHandle::SUCCESS;
34  FwSizeType stack = arguments.m_stackSize;
35 // Check for stack size multiple of page size or skip when the function
36 // is unavailable.
37 #ifdef _SC_PAGESIZE
38  long page_size = sysconf(_SC_PAGESIZE);
39 #else
40  long page_size = -1; // Force skip and warning
41 #endif
42  if (page_size <= 0) {
43  Fw::Logger::log("[WARNING] %s could not determine page size %s. Skipping stack-size check.\n",
44  const_cast<CHAR*>(arguments.m_name.toChar()), strerror(errno));
45  } else if ((stack % static_cast<FwSizeType>(page_size)) != 0) {
46  // Round-down to nearest page size multiple
47  FwSizeType rounded = (stack / static_cast<FwSizeType>(page_size)) * static_cast<FwSizeType>(page_size);
48  Fw::Logger::log("[WARNING] %s stack size of %" PRI_FwSizeType
49  " is not multiple of page size %ld, rounding to %" PRI_FwSizeType "\n",
50  const_cast<CHAR*>(arguments.m_name.toChar()), stack, page_size, rounded);
51  stack = rounded;
52  }
53 
54  // Clamp invalid stack sizes
55  if (stack <= static_cast<FwSizeType>(PTHREAD_STACK_MIN)) {
57  "[WARNING] %s stack size of %" PRI_FwSizeType " is too small, clamping to %" PRI_FwSizeType "\n",
58  const_cast<CHAR*>(arguments.m_name.toChar()), stack, static_cast<FwSizeType>(PTHREAD_STACK_MIN));
59  stack = static_cast<FwSizeType>(PTHREAD_STACK_MIN);
60  }
61  status = pthread_attr_setstacksize(&attributes, static_cast<size_t>(stack));
62  return status;
63 }
64 
65 int set_priority_params(pthread_attr_t& attributes, const Os::Task::Arguments& arguments) {
66  const FwSizeType min_priority = static_cast<FwSizeType>(sched_get_priority_min(SCHED_POLICY));
67  const FwSizeType max_priority = static_cast<FwSizeType>(sched_get_priority_max(SCHED_POLICY));
68  int status = PosixTaskHandle::SUCCESS;
69  FwSizeType priority = arguments.m_priority;
70  // Clamp to minimum priority
71  if (priority < min_priority) {
72  Fw::Logger::log("[WARNING] %s low task priority of %" PRI_FwSizeType " clamped to %" PRI_FwSizeType "\n",
73  const_cast<CHAR*>(arguments.m_name.toChar()), priority, min_priority);
74  priority = min_priority;
75  }
76  // Clamp to maximum priority
77  else if (priority > max_priority) {
78  Fw::Logger::log("[WARNING] %s high task priority of %" PRI_FwSizeType " clamped to %" PRI_FwSizeType "\n",
79  const_cast<CHAR*>(arguments.m_name.toChar()), priority, max_priority);
80  priority = max_priority;
81  }
82 
83  // Set attributes required for priority
84  status = pthread_attr_setschedpolicy(&attributes, SCHED_POLICY);
85  if (status == PosixTaskHandle::SUCCESS) {
86  status = pthread_attr_setinheritsched(&attributes, PTHREAD_EXPLICIT_SCHED);
87  }
88  if (status == PosixTaskHandle::SUCCESS) {
89  sched_param schedParam;
90  memset(&schedParam, 0, sizeof(sched_param));
91  schedParam.sched_priority = static_cast<int>(priority);
92  status = pthread_attr_setschedparam(&attributes, &schedParam);
93  }
94  return status;
95 }
96 
97 int set_cpu_affinity(pthread_attr_t& attributes, const Os::Task::Arguments& arguments) {
98  int status = 0;
99 // pthread_attr_setaffinity_np is a non-POSIX function. Notably, it is not available on musl.
100 // Limit its use to builds that involve glibc, on Linux, with _GNU_SOURCE defined.
101 // That's the circumstance in which we expect this feature to work.
102 #if defined(TGT_OS_TYPE_LINUX) && defined(__GLIBC__) && defined(_GNU_SOURCE)
103  const FwSizeType affinity = arguments.m_cpuAffinity;
104  cpu_set_t cpu_set;
105  CPU_ZERO(&cpu_set);
106  CPU_SET(static_cast<int>(affinity), &cpu_set);
107 
108  // According to the man-page this function sets errno rather than returning an error status like other functions
109  status = pthread_attr_setaffinity_np(&attributes, sizeof(cpu_set_t), &cpu_set);
110  status = (status == PosixTaskHandle::SUCCESS) ? status : errno;
111 #else
112  Fw::Logger::log("[WARNING] %s setting CPU affinity is only available with GNU pthreads\n",
113  const_cast<CHAR*>(arguments.m_name.toChar()));
114 #endif
115  return status;
116 }
117 
118 Os::Task::Status PosixTask::create(const Os::Task::Arguments& arguments,
119  const PosixTask::PermissionExpectation permissions) {
120  int pthread_status = PosixTaskHandle::SUCCESS;
121  PosixTaskHandle& handle = this->m_handle;
122  const bool expect_permission = (permissions == EXPECT_PERMISSION);
123  // Initialize and clear pthread attributes
124  pthread_attr_t attributes;
125  memset(&attributes, 0, sizeof(attributes));
126  pthread_status = pthread_attr_init(&attributes);
127  if ((arguments.m_stackSize != Os::Task::TASK_DEFAULT) && (expect_permission) &&
128  (pthread_status == PosixTaskHandle::SUCCESS)) {
129  pthread_status = set_stack_size(attributes, arguments);
130  }
131  if ((arguments.m_priority != Os::Task::TASK_PRIORITY_DEFAULT) && (expect_permission) &&
132  (pthread_status == PosixTaskHandle::SUCCESS)) {
133  pthread_status = set_priority_params(attributes, arguments);
134  }
135  if ((arguments.m_cpuAffinity != Os::Task::TASK_DEFAULT) && (expect_permission) &&
136  (pthread_status == PosixTaskHandle::SUCCESS)) {
137  pthread_status = set_cpu_affinity(attributes, arguments);
138  }
139  if (pthread_status == PosixTaskHandle::SUCCESS) {
140  pthread_status =
141  pthread_create(&handle.m_task_descriptor, &attributes, pthread_entry_wrapper, arguments.m_routine_argument);
142  }
143  // Successful execution of all precious steps will result in a valid task handle
144  if (pthread_status == PosixTaskHandle::SUCCESS) {
145  handle.m_is_valid = true;
146  }
147 
148  (void)pthread_attr_destroy(&attributes);
149  return Posix::posix_status_to_task_status(pthread_status);
150 }
151 
153 
155  FW_ASSERT(arguments.m_routine != nullptr);
156 
157  // Try to create thread with assuming permissions
158  Os::Task::Status status = this->create(arguments, PermissionExpectation::EXPECT_PERMISSION);
159  // Failure due to permission automatically retried
160  if (status == Os::Task::Status::ERROR_PERMISSION) {
161  if (not PosixTask::s_permissions_reported) {
162  Fw::Logger::log("\n");
163  Fw::Logger::log("[NOTE] Task Permissions:\n");
164  Fw::Logger::log("[NOTE]\n");
166  "[NOTE] You have insufficient permissions to create a task with priority and/or cpu affinity.\n");
167  Fw::Logger::log("[NOTE] A task without priority and affinity will be created.\n");
168  Fw::Logger::log("[NOTE]\n");
169  Fw::Logger::log("[NOTE] There are three possible resolutions:\n");
170  Fw::Logger::log("[NOTE] 1. Use tasks without priority and affinity using parameterless start()\n");
171  Fw::Logger::log("[NOTE] 2. Run this executable as a user with task priority permission\n");
172  Fw::Logger::log("[NOTE] 3. Grant capability with \"setcap 'cap_sys_nice=eip'\" or equivalent\n");
173  Fw::Logger::log("\n");
174  PosixTask::s_permissions_reported = true;
175  }
176  // Fallback with no permission
177  status = this->create(arguments, PermissionExpectation::EXPECT_NO_PERMISSION);
178  } else if (status != Os::Task::Status::OP_OK) {
179  Fw::Logger::log("[ERROR] Failed to create task with status: %d", static_cast<int>(status));
180  }
181  return status;
182 }
183 
185  Os::Task::Status status = Os::Task::Status::JOIN_ERROR;
186  if (not this->m_handle.m_is_valid) {
187  status = Os::Task::Status::INVALID_HANDLE;
188  } else {
189  int stat = ::pthread_join(this->m_handle.m_task_descriptor, nullptr);
190  status = (stat == PosixTaskHandle::SUCCESS) ? Os::Task::Status::OP_OK : Os::Task::Status::JOIN_ERROR;
191  }
192  return status;
193 }
194 
196  return &this->m_handle;
197 }
198 
199 // Note: not implemented for Posix threads. Must be manually done using a mutex or other blocking construct as there
200 // is no top-level pthreads support for suspend and resume.
202  FW_ASSERT(0);
203 }
204 
206  FW_ASSERT(0);
207 }
208 
210  Os::Task::Status task_status = Os::Task::OP_OK;
211  timespec sleep_interval;
212  sleep_interval.tv_sec = interval.getSeconds();
213  sleep_interval.tv_nsec = interval.getUSeconds() * 1000;
214 
215  timespec remaining_interval;
216  remaining_interval.tv_sec = 0;
217  remaining_interval.tv_nsec = 0;
218 
219  while (true) {
220  int status = nanosleep(&sleep_interval, &remaining_interval);
221  // Success, return ok
222  if (0 == status) {
223  break;
224  }
225  // Interrupted, reset sleep and iterate
226  else if (EINTR == errno) {
227  sleep_interval = remaining_interval;
228  continue;
229  }
230  // Anything else is an error
231  else {
232  task_status = Os::Task::Status::DELAY_ERROR;
233  break;
234  }
235  }
236  return task_status;
237 }
238 
239 } // end namespace Task
240 } // end namespace Posix
241 } // end namespace Os
static constexpr FwSizeType TASK_DEFAULT
Definition: Task.hpp:37
Task handle representation.
Definition: Task.hpp:33
Operation succeeded.
Definition: Os.hpp:26
PlatformSizeType FwSizeType
const char * toChar() const
Definition: TaskString.hpp:45
#define PRI_FwSizeType
int set_priority_params(pthread_attr_t &attributes, const Os::Task::Arguments &arguments)
Definition: Task.cpp:65
void suspend(SuspensionType suspensionType) override
suspend the task given the suspension type
Definition: Task.cpp:201
static void log(const char *format,...)
log a formated string with supplied arguments
Definition: Logger.cpp:21
static constexpr int SUCCESS
Definition: Task.hpp:25
Status _delay(Fw::TimeInterval interval) override
delay the current task
Definition: Task.cpp:209
static constexpr FwTaskPriorityType TASK_PRIORITY_DEFAULT
Definition: Task.hpp:38
Task::Status posix_status_to_task_status(int posix_status)
Definition: error.cpp:147
message sent/received okay
Definition: Task.hpp:40
bool m_is_valid
Is the above descriptor valid.
Definition: Task.hpp:30
PermissionExpectation
Enumeration of permission expectations.
Definition: Task.hpp:37
pthread_t m_task_descriptor
Posix task descriptor.
Definition: Task.hpp:28
TaskHandle * getHandle() override
return the underlying task handle (implementation specific)
Definition: Task.cpp:195
static void run(void *task_pointer)
run the task routine wrapper
Definition: Task.cpp:29
Wrapper for task routine that ensures onStart() is called once the task actually begins.
Definition: Task.hpp:202
const Os::TaskString m_name
Definition: Task.hpp:84
void * pthread_entry_wrapper(void *wrapper_pointer)
Definition: Task.cpp:25
FwSizeType m_cpuAffinity
Definition: Task.hpp:89
int set_stack_size(pthread_attr_t &attributes, const Os::Task::Arguments &arguments)
Definition: Task.cpp:32
U32 getUSeconds() const
static const int SCHED_POLICY
Definition: Task.cpp:21
Expect that you hold necessary permissions.
Definition: Task.hpp:38
Status join() override
block until the task has ended
Definition: Task.cpp:184
Status start(const Arguments &arguments) override
start the task
Definition: Task.cpp:154
FwTaskPriorityType m_priority
Definition: Task.hpp:87
int set_cpu_affinity(pthread_attr_t &attributes, const Os::Task::Arguments &arguments)
Definition: Task.cpp:97
void resume() override
resume a suspended task
Definition: Task.cpp:205
void onStart() override
perform required task start actions
Definition: Task.cpp:152
#define FW_ASSERT(...)
Definition: Assert.hpp:14
U32 getSeconds() const