Debian Codegraph @

src/dcp_thread.c

raw symbols SCIP
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3 * Copyright (C) 2020-2025 Linutronix GmbH
4 * Author Kurt Kanzenbach <[email protected]>
5 */
6
7 #include <errno.h>
8 #include <pthread.h>
9 #include <signal.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <unistd.h>
14
15 #include <arpa/inet.h>
16
17 #include <linux/if_ether.h>
18 #include <linux/if_link.h>
19 #include <linux/if_packet.h>
20 #include <linux/if_vlan.h>
21
22 #include "config.h"
23 #include "dcp_thread.h"
24 #include "log.h"
25 #include "net.h"
26 #include "packet.h"
27 #include "security.h"
28 #include "stat.h"
29 #include "utils.h"
30
31 static void dcp_initialize_frames(struct thread_context *thread_context, unsigned char *frame_data,
32 size_t num_frames, const unsigned char *source)
33 {
34 const struct traffic_class_config *dcp_config = thread_context->conf;
35 size_t i;
36
37 for (i = 0; i < num_frames; ++i)
38 initialize_profinet_frame(
39 SECURITY_MODE_NONE, frame_idx(frame_data, i), MAX_FRAME_SIZE, source,
40 dcp_config->l2_destination, dcp_config->payload_pattern,
41 dcp_config->payload_pattern_length,
42 dcp_config->vid | dcp_config->pcp << VLAN_PCP_SHIFT, DCP_FRAMEID);
43 }
44
45 static void dcp_build_frame_from_rx(struct thread_context *thread_context,
46 const unsigned char *old_frame, size_t old_frame_len,
47 unsigned char *new_frame, size_t new_frame_len,
48 const unsigned char *source)
49 {
50 const struct traffic_class_config *dcp_config = thread_context->conf;
51 struct vlan_ethernet_header *eth_new, *eth_old;
52 struct profinet_rt_header *rt;
53
54 /*
55 * Three tasks:
56 * -> Keep destination and adjust source
57 * -> Set new Tx Timestamp
58 * -> Inject VLAN header
59 */
60
61 if (new_frame_len < old_frame_len + sizeof(struct vlan_header))
62 return;
63
64 /* Copy payload */
65 memcpy(new_frame + ETH_ALEN * 2 + sizeof(struct vlan_header), old_frame + ETH_ALEN * 2,
66 old_frame_len - ETH_ALEN * 2);
67
68 /* Swap source destination */
69 eth_new = (struct vlan_ethernet_header *)new_frame;
70 eth_old = (struct vlan_ethernet_header *)old_frame;
71
72 memcpy(eth_new->destination, eth_old->destination, ETH_ALEN);
73 memcpy(eth_new->source, source, ETH_ALEN);
74
75 /* Inject VLAN info */
76 eth_new->vlan_proto = htons(ETH_P_8021Q);
77 eth_new->vlantci = htons(dcp_config->vid | dcp_config->pcp << VLAN_PCP_SHIFT);
78 eth_new->vlan_encapsulated_proto = htons(ETH_P_PROFINET_RT);
79
80 rt = (struct profinet_rt_header *)(new_frame + sizeof(*eth_new));
81 set_mirror_tx_timestamp(&rt->meta_data);
82 }
83
84 static int dcp_send_messages(struct thread_context *thread_context, int socket_fd,
85 struct sockaddr_ll *destination, unsigned char *frame_data,
86 size_t num_frames)
87 {
88 const struct traffic_class_config *dcp_config = thread_context->conf;
89 struct packet_send_request send_req = {
90 .traffic_class = stat_frame_type_to_string(DCP_FRAME_TYPE),
91 .socket_fd = socket_fd,
92 .destination = destination,
93 .frame_data = frame_data,
94 .num_frames = num_frames,
95 .frame_length = dcp_config->frame_length,
96 .duration = 0,
97 .tx_time_offset = 0,
98 .meta_data_offset = thread_context->meta_data_offset,
99 .mirror_enabled = dcp_config->rx_mirror_enabled,
100 .tx_time_enabled = false,
101 };
102
103 return packet_send_messages(thread_context->packet_context, &send_req);
104 }
105
106 static int dcp_send_frames(struct thread_context *thread_context, unsigned char *frame_data,
107 size_t num_frames, int socket_fd, struct sockaddr_ll *destination)
108 {
109 const struct traffic_class_config *dcp_config = thread_context->conf;
110 int len, i;
111
112 /* Send them */
113 len = dcp_send_messages(thread_context, socket_fd, destination, frame_data, num_frames);
114
115 for (i = 0; i < len; i++) {
116 uint64_t sequence_counter;
117
118 sequence_counter = get_sequence_counter(frame_data + i * dcp_config->frame_length,
119 thread_context->meta_data_offset,
120 dcp_config->num_frames_per_cycle);
121
122 stat_frame_sent(DCP_FRAME_TYPE, sequence_counter);
123 }
124
125 return len;
126 }
127
128 static void dcp_gen_and_send_frames(struct thread_context *thread_context, int socket_fd,
129 struct sockaddr_ll *destination,
130 uint64_t sequence_counter_begin)
131 {
132 const struct traffic_class_config *dcp_config = thread_context->conf;
133 struct vlan_ethernet_header *eth;
134 struct profinet_rt_header *rt;
135 struct timespec tx_time = {};
136 int len, i;
137
138 clock_gettime(app_config.application_clock_id, &tx_time);
139
140 /* Adjust meta data */
141 for (i = 0; i < dcp_config->num_frames_per_cycle; i++) {
142 rt = (struct profinet_rt_header *)(frame_idx(thread_context->tx_frame_data, i) +
143 sizeof(*eth));
144 sequence_counter_to_meta_data(&rt->meta_data, sequence_counter_begin + i,
145 dcp_config->num_frames_per_cycle);
146
147 tx_timestamp_to_meta_data(&rt->meta_data, ts_to_ns(&tx_time));
148 }
149
150 /* Send them */
151 len = dcp_send_messages(thread_context, socket_fd, destination,
152 thread_context->tx_frame_data, dcp_config->num_frames_per_cycle);
153
154 for (i = 0; i < len; i++)
155 stat_frame_sent(DCP_FRAME_TYPE, sequence_counter_begin + i);
156 }
157
158 static void *dcp_tx_thread_routine(void *data)
159 {
160 struct thread_context *thread_context = data;
161 const struct traffic_class_config *dcp_config = thread_context->conf;
162 size_t received_frames_length = MAX_FRAME_SIZE * dcp_config->num_frames_per_cycle;
163 unsigned char *received_frames = thread_context->rx_frame_data;
164 const bool mirror_enabled = dcp_config->rx_mirror_enabled;
165 pthread_cond_t *cond = &thread_context->data_cond_var;
166 pthread_mutex_t *mutex = &thread_context->data_mutex;
167 struct sockaddr_ll destination;
168 uint64_t sequence_counter = 0;
169 unsigned int if_index;
170 int socket_fd;
171
172 socket_fd = thread_context->socket_fd;
173
174 if_index = if_nametoindex(dcp_config->interface);
175 if (!if_index) {
176 log_message(LOG_LEVEL_ERROR, "DcpTx: if_nametoindex() failed!\n");
177 return NULL;
178 }
179
180 memset(&destination, '\0', sizeof(destination));
181 destination.sll_family = PF_PACKET;
182 destination.sll_ifindex = if_index;
183 destination.sll_halen = ETH_ALEN;
184 memcpy(destination.sll_addr, dcp_config->l2_destination, ETH_ALEN);
185
186 dcp_initialize_frames(thread_context, thread_context->tx_frame_data,
187 dcp_config->num_frames_per_cycle, thread_context->source);
188
189 while (!thread_context->stop) {
190 struct timespec timeout;
191 size_t num_frames;
192 int ret;
193
194 /*
195 * Wait until signalled. These DCP frames have to be sent after the RTA
196 * frames. Therefore, the RTA TxThread signals this one here.
197 */
198 clock_gettime(CLOCK_MONOTONIC, &timeout);
199 timeout.tv_sec++;
200
201 pthread_mutex_lock(mutex);
202 ret = pthread_cond_timedwait(cond, mutex, &timeout);
203 num_frames = thread_context->num_frames_available;
204 thread_context->num_frames_available = 0;
205 pthread_mutex_unlock(mutex);
206
207 /* In case of shutdown a signal may be missing. */
208 if (ret == ETIMEDOUT)
209 continue;
210
211 /*
212 * Send DcpFrames, two possibilites:
213 * a) Generate it, or
214 * b) Use received ones if mirror enabled
215 */
216 if (!mirror_enabled) {
217 if (num_frames) {
218 dcp_gen_and_send_frames(thread_context, socket_fd, &destination,
219 sequence_counter);
220
221 sequence_counter += num_frames;
222 }
223 } else {
224 size_t len;
225
226 ring_buffer_fetch(thread_context->mirror_buffer, received_frames,
227 received_frames_length, &len);
228
229 /* Len should be a multiple of frame size */
230 num_frames = len / dcp_config->frame_length;
231 dcp_send_frames(thread_context, received_frames, num_frames, socket_fd,
232 &destination);
233
234 pthread_mutex_lock(&thread_context->data_mutex);
235 thread_context->num_frames_available = 0;
236 pthread_mutex_unlock(&thread_context->data_mutex);
237 }
238
239 /* Signal next Tx thread */
240 if (thread_context->next) {
241 pthread_mutex_lock(&thread_context->next->data_mutex);
242 pthread_cond_signal(&thread_context->next->data_cond_var);
243 pthread_mutex_unlock(&thread_context->next->data_mutex);
244 }
245
246 if (thread_context->is_last)
247 stat_update();
248 }
249
250 return NULL;
251 }
252
253 static int dcp_rx_frame(void *data, unsigned char *frame_data, size_t len)
254 {
255 struct thread_context *thread_context = data;
256 const struct traffic_class_config *dcp_config = thread_context->conf;
257 const unsigned char *expected_pattern = (const unsigned char *)dcp_config->payload_pattern;
258 const size_t expected_pattern_length = dcp_config->payload_pattern_length;
259 const size_t num_frames_per_cycle = dcp_config->num_frames_per_cycle;
260 const bool mirror_enabled = dcp_config->rx_mirror_enabled;
261 const bool ignore_rx_errors = dcp_config->ignore_rx_errors;
262 const size_t frame_length = dcp_config->frame_length;
263 bool out_of_order, payload_mismatch, frame_id_mismatch;
264 unsigned char new_frame[MAX_FRAME_SIZE];
265 struct profinet_rt_header *rt;
266 uint64_t sequence_counter;
267 uint64_t tx_timestamp;
268
269 if (len != frame_length - 4) {
270 log_message(LOG_LEVEL_ERROR, "DcpRx: Frame with wrong length received!\n");
271 return -EINVAL;
272 }
273
274 /*
275 * Check cycle counter and payload. The frame id range is checked by the attached BPF
276 * filter.
277 */
278 rt = (struct profinet_rt_header *)(frame_data + sizeof(struct ethhdr));
279 sequence_counter = meta_data_to_sequence_counter(&rt->meta_data, num_frames_per_cycle);
280
281 tx_timestamp = meta_data_to_tx_timestamp(&rt->meta_data);
282
283 out_of_order = sequence_counter != thread_context->rx_sequence_counter;
284 payload_mismatch = memcmp(frame_data + sizeof(struct ethhdr) + sizeof(*rt),
285 expected_pattern, expected_pattern_length);
286 frame_id_mismatch = false;
287
288 stat_frame_received(DCP_FRAME_TYPE, sequence_counter, out_of_order, payload_mismatch,
289 frame_id_mismatch, tx_timestamp, 0, 0);
290
291 if (out_of_order) {
292 if (!ignore_rx_errors)
293 log_message(LOG_LEVEL_WARNING,
294 "DcpRx: frame[%" PRIu64 "] SequenceCounter mismatch: %" PRIu64
295 "!\n",
296 sequence_counter, thread_context->rx_sequence_counter);
297 thread_context->rx_sequence_counter++;
298 }
299
300 if (payload_mismatch)
301 log_message(LOG_LEVEL_WARNING,
302 "DcpRx: frame[%" PRIu64 "] Payload Pattern mismatch!\n",
303 sequence_counter);
304
305 thread_context->rx_sequence_counter++;
306
307 /* If mirror enabled, assemble and store the frame for Tx later. */
308 if (!mirror_enabled)
309 return 0;
310
311 /* Build new frame for Tx with VLAN info. */
312 dcp_build_frame_from_rx(thread_context, frame_data, len, new_frame, sizeof(new_frame),
313 thread_context->source);
314
315 /* Store the new frame. */
316 ring_buffer_add(thread_context->mirror_buffer, new_frame, len + sizeof(struct vlan_header));
317
318 pthread_mutex_lock(&thread_context->data_mutex);
319 thread_context->num_frames_available++;
320 pthread_mutex_unlock(&thread_context->data_mutex);
321
322 return 0;
323 }
324
325 static void *dcp_rx_thread_routine(void *data)
326 {
327 struct thread_context *thread_context = data;
328 const uint64_t cycle_time_ns = app_config.application_base_cycle_time_ns;
329 struct timespec wakeup_time;
330 int socket_fd, ret;
331
332 socket_fd = thread_context->socket_fd;
333
334 ret = get_thread_start_time(app_config.application_rx_base_offset_ns, &wakeup_time);
335 if (ret) {
336 log_message(LOG_LEVEL_ERROR, "DcpRx: Failed to calculate thread start time: %s!\n",
337 strerror(errno));
338 return NULL;
339 }
340
341 while (!thread_context->stop) {
342 struct packet_receive_request recv_req = {
343 .traffic_class = thread_context->traffic_class,
344 .socket_fd = socket_fd,
345 .receive_function = dcp_rx_frame,
346 .data = thread_context,
347 };
348
349 /* Wait until next period. */
350 increment_period(&wakeup_time, cycle_time_ns);
351
352 do {
353 ret = clock_nanosleep(app_config.application_clock_id, TIMER_ABSTIME,
354 &wakeup_time, NULL);
355 } while (ret == EINTR);
356
357 if (ret) {
358 log_message(LOG_LEVEL_ERROR, "DcpRx: clock_nanosleep() failed: %s\n",
359 strerror(ret));
360 return NULL;
361 }
362
363 /* Receive Dcp frames. */
364 packet_receive_messages(thread_context->packet_context, &recv_req);
365 }
366
367 return NULL;
368 }
369
370 static void *dcp_tx_generation_thread_routine(void *data)
371 {
372 struct thread_context *thread_context = data;
373 const struct traffic_class_config *dcp_config = thread_context->conf;
374 uint64_t num_frames = dcp_config->num_frames_per_cycle;
375 pthread_mutex_t *mutex = &thread_context->data_mutex;
376 uint64_t cycle_time_ns = dcp_config->burst_period_ns;
377 struct timespec wakeup_time;
378 int ret;
379
380 /*
381 * The DCP frames are generated by bursts with a certain period. This thread is responsible
382 * for generating it.
383 */
384
385 ret = get_thread_start_time(0, &wakeup_time);
386 if (ret) {
387 log_message(LOG_LEVEL_ERROR,
388 "DcpTxGen: Failed to calculate thread start time: %s!\n",
389 strerror(errno));
390 return NULL;
391 }
392
393 while (!thread_context->stop) {
394 /* Wait until next period */
395 increment_period(&wakeup_time, cycle_time_ns);
396
397 do {
398 ret = clock_nanosleep(app_config.application_clock_id, TIMER_ABSTIME,
399 &wakeup_time, NULL);
400 } while (ret == EINTR);
401
402 if (ret) {
403 log_message(LOG_LEVEL_ERROR, "DcpTxGen: clock_nanosleep() failed: %s\n",
404 strerror(ret));
405 return NULL;
406 }
407
408 /* Generate frames */
409 pthread_mutex_lock(mutex);
410 thread_context->num_frames_available = num_frames;
411 pthread_mutex_unlock(mutex);
412 }
413
414 return NULL;
415 }
416
417 int dcp_threads_create(struct thread_context *thread_context)
418 {
419 struct traffic_class_config *dcp_config;
420 int ret;
421
422 if (!config_is_traffic_class_active("Dcp"))
423 goto out;
424
425 thread_context->conf = dcp_config = &app_config.classes[DCP_FRAME_TYPE];
426 thread_context->frame_type = DCP_FRAME_TYPE;
427 thread_context->traffic_class = stat_frame_type_to_string(DCP_FRAME_TYPE);
428 thread_context->frame_id = DCP_FRAME_TYPE;
429
430 thread_context->socket_fd = create_dcp_socket();
431 if (thread_context->socket_fd < 0) {
432 fprintf(stderr, "Failed to create DcpSocket!\n");
433 ret = -ENOMEM;
434 goto err;
435 }
436
437 init_mutex(&thread_context->data_mutex);
438 init_condition_variable(&thread_context->data_cond_var);
439
440 thread_context->packet_context = packet_init(dcp_config->num_frames_per_cycle);
441 if (!thread_context->packet_context) {
442 fprintf(stderr, "Failed to allocate Dcp packet context!\n");
443 ret = -ENOMEM;
444 goto err_packet;
445 }
446
447 thread_context->tx_frame_data = calloc(dcp_config->num_frames_per_cycle, MAX_FRAME_SIZE);
448 if (!thread_context->tx_frame_data) {
449 fprintf(stderr, "Failed to allocate DcpTxFrameData!\n");
450 ret = -ENOMEM;
451 goto err_tx;
452 }
453
454 thread_context->rx_frame_data = calloc(dcp_config->num_frames_per_cycle, MAX_FRAME_SIZE);
455 if (!thread_context->rx_frame_data) {
456 fprintf(stderr, "Failed to allocate DcpRxFrameData!\n");
457 ret = -ENOMEM;
458 goto err_rx;
459 }
460
461 ret = get_interface_mac_address(dcp_config->interface, thread_context->source,
462 sizeof(thread_context->source));
463 if (ret < 0) {
464 fprintf(stderr, "Failed to get Dcp Source MAC address!\n");
465 goto err_mac;
466 }
467
468 if (dcp_config->rx_mirror_enabled) {
469 /* Per period the expectation is: DcpNumFramesPerCycle * MAX_FRAME */
470 thread_context->mirror_buffer =
471 ring_buffer_allocate(MAX_FRAME_SIZE * dcp_config->num_frames_per_cycle);
472 if (!thread_context->mirror_buffer) {
473 fprintf(stderr, "Failed to allocate Dcp Mirror RingBuffer!\n");
474 ret = -ENOMEM;
475 goto err_mac;
476 }
477 }
478
479 ret = create_rt_thread(&thread_context->tx_task_id, "DcpTxThread",
480 dcp_config->tx_thread_priority, dcp_config->tx_thread_cpu,
481 dcp_tx_thread_routine, thread_context);
482 if (ret) {
483 fprintf(stderr, "Failed to create Dcp Tx Thread!\n");
484 goto err_thread;
485 }
486
487 if (!dcp_config->rx_mirror_enabled) {
488 ret = create_rt_thread(&thread_context->tx_gen_task_id, "DcpTxGenThread",
489 dcp_config->tx_thread_priority, dcp_config->tx_thread_cpu,
490 dcp_tx_generation_thread_routine, thread_context);
491 if (ret) {
492 fprintf(stderr, "Failed to create Dcp TxGen Thread!\n");
493 goto err_thread_txgen;
494 }
495 }
496
497 ret = create_rt_thread(&thread_context->rx_task_id, "DcpRxThread",
498 dcp_config->rx_thread_priority, dcp_config->rx_thread_cpu,
499 dcp_rx_thread_routine, thread_context);
500 if (ret) {
501 fprintf(stderr, "Failed to create Dcp Rx Thread!\n");
502 goto err_thread_rx;
503 }
504
505 thread_context->meta_data_offset = get_meta_data_offset(DCP_FRAME_TYPE, SECURITY_MODE_NONE);
506
507 out:
508 return 0;
509
510 err_thread_rx:
511 thread_context->stop = 1;
512 if (thread_context->tx_gen_task_id)
513 pthread_join(thread_context->tx_gen_task_id, NULL);
514 err_thread_txgen:
515 thread_context->stop = 1;
516 pthread_join(thread_context->tx_task_id, NULL);
517 err_thread:
518 ring_buffer_free(thread_context->mirror_buffer);
519 err_mac:
520 free(thread_context->rx_frame_data);
521 err_rx:
522 free(thread_context->tx_frame_data);
523 err_tx:
524 packet_free(thread_context->packet_context);
525 err_packet:
526 close(thread_context->socket_fd);
527 err:
528 return ret;
529 }
530
531 void dcp_threads_free(struct thread_context *thread_context)
532 {
533 if (!thread_context)
534 return;
535
536 ring_buffer_free(thread_context->mirror_buffer);
537
538 packet_free(thread_context->packet_context);
539 free(thread_context->tx_frame_data);
540 free(thread_context->rx_frame_data);
541
542 if (thread_context->socket_fd > 0)
543 close(thread_context->socket_fd);
544 }
545
546 void dcp_threads_wait_for_finish(struct thread_context *thread_context)
547 {
548 if (!thread_context)
549 return;
550
551 if (thread_context->rx_task_id)
552 pthread_join(thread_context->rx_task_id, NULL);
553 if (thread_context->tx_task_id)
554 pthread_join(thread_context->tx_task_id, NULL);
555 if (thread_context->tx_gen_task_id)
556 pthread_join(thread_context->tx_gen_task_id, NULL);
557 }