Contiki-NG
tsch-slot-operation.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015, SICS Swedish ICT.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * This file is part of the Contiki operating system.
30  *
31  */
32 
33 /**
34  * \file
35  * TSCH slot operation implementation, running from interrupt.
36  * \author
37  * Simon Duquennoy <simonduq@sics.se>
38  * Beshr Al Nahas <beshr@sics.se>
39  * Atis Elsts <atis.elsts@bristol.ac.uk>
40  *
41  */
42 
43 /**
44  * \addtogroup tsch
45  * @{
46 */
47 
48 #include "dev/radio.h"
49 #include "contiki.h"
50 #include "net/netstack.h"
51 #include "net/packetbuf.h"
52 #include "net/queuebuf.h"
54 #include "net/mac/tsch/tsch.h"
55 #include "sys/critical.h"
56 
57 #include "sys/log.h"
58 /* TSCH debug macros, i.e. to set LEDs or GPIOs on various TSCH
59  * timeslot events */
60 #ifndef TSCH_DEBUG_INIT
61 #define TSCH_DEBUG_INIT()
62 #endif
63 #ifndef TSCH_DEBUG_INTERRUPT
64 #define TSCH_DEBUG_INTERRUPT()
65 #endif
66 #ifndef TSCH_DEBUG_RX_EVENT
67 #define TSCH_DEBUG_RX_EVENT()
68 #endif
69 #ifndef TSCH_DEBUG_TX_EVENT
70 #define TSCH_DEBUG_TX_EVENT()
71 #endif
72 #ifndef TSCH_DEBUG_SLOT_START
73 #define TSCH_DEBUG_SLOT_START()
74 #endif
75 #ifndef TSCH_DEBUG_SLOT_END
76 #define TSCH_DEBUG_SLOT_END()
77 #endif
78 
79 /* Check if TSCH_MAX_INCOMING_PACKETS is power of two */
80 #if (TSCH_MAX_INCOMING_PACKETS & (TSCH_MAX_INCOMING_PACKETS - 1)) != 0
81 #error TSCH_MAX_INCOMING_PACKETS must be power of two
82 #endif
83 
84 /* Check if TSCH_DEQUEUED_ARRAY_SIZE is power of two and greater or equal to QUEUEBUF_NUM */
85 #if TSCH_DEQUEUED_ARRAY_SIZE < QUEUEBUF_NUM
86 #error TSCH_DEQUEUED_ARRAY_SIZE must be greater or equal to QUEUEBUF_NUM
87 #endif
88 #if (TSCH_DEQUEUED_ARRAY_SIZE & (TSCH_DEQUEUED_ARRAY_SIZE - 1)) != 0
89 #error TSCH_DEQUEUED_ARRAY_SIZE must be power of two
90 #endif
91 
92 /* Truncate received drift correction information to maximum half
93  * of the guard time (one fourth of TSCH_DEFAULT_TS_RX_WAIT) */
94 #define SYNC_IE_BOUND ((int32_t)US_TO_RTIMERTICKS(tsch_timing_us[tsch_ts_rx_wait] / 4))
95 
96 /* By default: check that rtimer runs at >=32kHz and use a guard time of 10us */
97 #if RTIMER_SECOND < (32 * 1024)
98 #error "TSCH: RTIMER_SECOND < (32 * 1024)"
99 #endif
100 #if CONTIKI_TARGET_COOJA
101 /* Use 0 usec guard time for Cooja Mote with a 1 MHz Rtimer*/
102 #define RTIMER_GUARD 0u
103 #elif RTIMER_SECOND >= 200000
104 #define RTIMER_GUARD (RTIMER_SECOND / 100000)
105 #else
106 #define RTIMER_GUARD 2u
107 #endif
108 
109 enum tsch_radio_state_on_cmd {
110  TSCH_RADIO_CMD_ON_START_OF_TIMESLOT,
111  TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT,
112  TSCH_RADIO_CMD_ON_FORCE,
113 };
114 
115 enum tsch_radio_state_off_cmd {
116  TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT,
117  TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT,
118  TSCH_RADIO_CMD_OFF_FORCE,
119 };
120 
121 /* A ringbuf storing outgoing packets after they were dequeued.
122  * Will be processed layer by tsch_tx_process_pending */
123 struct ringbufindex dequeued_ringbuf;
124 struct tsch_packet *dequeued_array[TSCH_DEQUEUED_ARRAY_SIZE];
125 /* A ringbuf storing incoming packets.
126  * Will be processed layer by tsch_rx_process_pending */
127 struct ringbufindex input_ringbuf;
128 struct input_packet input_array[TSCH_MAX_INCOMING_PACKETS];
129 
130 /* Updates and reads of the next two variables must be atomic (i.e. both together) */
131 /* Last time we received Sync-IE (ACK or data packet from a time source) */
132 static struct tsch_asn_t last_sync_asn;
133 clock_time_t tsch_last_sync_time; /* Same info, in clock_time_t units */
134 
135 /* A global lock for manipulating data structures safely from outside of interrupt */
136 static volatile int tsch_locked = 0;
137 /* As long as this is set, skip all slot operation */
138 static volatile int tsch_lock_requested = 0;
139 
140 /* Last estimated drift in RTIMER ticks
141  * (Sky: 1 tick = 30.517578125 usec exactly) */
142 static int32_t drift_correction = 0;
143 /* Is drift correction used? (Can be true even if drift_correction == 0) */
144 static uint8_t is_drift_correction_used;
145 
146 /* Used from tsch_slot_operation and sub-protothreads */
147 static rtimer_clock_t volatile current_slot_start;
148 
149 /* Are we currently inside a slot? */
150 static volatile int tsch_in_slot_operation = 0;
151 
152 /* If we are inside a slot, this tells the current channel */
153 uint8_t tsch_current_channel;
154 
155 /* Info about the link, packet and neighbor of
156  * the current (or next) slot */
157 struct tsch_link *current_link = NULL;
158 /* A backup link with Rx flag, overlapping with current_link.
159  * If the current link is Tx-only and the Tx queue
160  * is empty while executing the link, fallback to the backup link. */
161 static struct tsch_link *backup_link = NULL;
162 static struct tsch_packet *current_packet = NULL;
163 static struct tsch_neighbor *current_neighbor = NULL;
164 
165 /* Indicates whether an extra link is needed to handle the current burst */
166 static int burst_link_scheduled = 0;
167 /* Counts the length of the current burst */
168 int tsch_current_burst_count = 0;
169 
170 /* Protothread for association */
171 PT_THREAD(tsch_scan(struct pt *pt));
172 /* Protothread for slot operation, called from rtimer interrupt
173  * and scheduled from tsch_schedule_slot_operation */
174 static PT_THREAD(tsch_slot_operation(struct rtimer *t, void *ptr));
175 static struct pt slot_operation_pt;
176 /* Sub-protothreads of tsch_slot_operation */
177 static PT_THREAD(tsch_tx_slot(struct pt *pt, struct rtimer *t));
178 static PT_THREAD(tsch_rx_slot(struct pt *pt, struct rtimer *t));
179 
180 /*---------------------------------------------------------------------------*/
181 /* TSCH locking system. TSCH is locked during slot operations */
182 
183 /* Is TSCH locked? */
184 int
186 {
187  return tsch_locked;
188 }
189 
190 /* Lock TSCH (no slot operation) */
191 int
193 {
194  if(!tsch_locked) {
195  rtimer_clock_t busy_wait_time;
196  int busy_wait = 0; /* Flag used for logging purposes */
197  /* Make sure no new slot operation will start */
198  tsch_lock_requested = 1;
199  /* Wait for the end of current slot operation. */
200  if(tsch_in_slot_operation) {
201  busy_wait = 1;
202  busy_wait_time = RTIMER_NOW();
203  while(tsch_in_slot_operation) {
205  }
206  busy_wait_time = RTIMER_NOW() - busy_wait_time;
207  }
208  if(!tsch_locked) {
209  /* Take the lock if it is free */
210  tsch_locked = 1;
211  tsch_lock_requested = 0;
212  if(busy_wait) {
213  /* Issue a log whenever we had to busy wait until getting the lock */
214  TSCH_LOG_ADD(tsch_log_message,
215  snprintf(log->message, sizeof(log->message),
216  "!get lock delay %u", (unsigned)busy_wait_time);
217  );
218  }
219  return 1;
220  }
221  }
222  TSCH_LOG_ADD(tsch_log_message,
223  snprintf(log->message, sizeof(log->message),
224  "!failed to lock");
225  );
226  return 0;
227 }
228 
229 /* Release TSCH lock */
230 void
232 {
233  tsch_locked = 0;
234 }
235 
236 /*---------------------------------------------------------------------------*/
237 /* Channel hopping utility functions */
238 
239 /* Return channel from ASN and channel offset */
240 uint8_t
241 tsch_calculate_channel(struct tsch_asn_t *asn, uint16_t channel_offset, struct tsch_packet *p)
242 {
243  uint16_t index_of_0, index_of_offset;
244 #if TSCH_WITH_LINK_SELECTOR
245  if(p != NULL) {
246  uint16_t packet_channel_offset = queuebuf_attr(p->qb, PACKETBUF_ATTR_TSCH_CHANNEL_OFFSET);
247  if(packet_channel_offset != 0xffff) {
248  /* The schedule specifies a channel offset for this one; use it */
249  channel_offset = packet_channel_offset;
250  }
251  }
252 #endif
253  index_of_0 = TSCH_ASN_MOD(*asn, tsch_hopping_sequence_length);
254  index_of_offset = (index_of_0 + channel_offset) % tsch_hopping_sequence_length.val;
255  return tsch_hopping_sequence[index_of_offset];
256 }
257 
258 /*---------------------------------------------------------------------------*/
259 /* Timing utility functions */
260 
261 /* Checks if the current time has passed a ref time + offset. Assumes
262  * a single overflow and ref time prior to now. */
263 static uint8_t
264 check_timer_miss(rtimer_clock_t ref_time, rtimer_clock_t offset, rtimer_clock_t now)
265 {
266  rtimer_clock_t target = ref_time + offset;
267  int now_has_overflowed = now < ref_time;
268  int target_has_overflowed = target < ref_time;
269 
270  if(now_has_overflowed == target_has_overflowed) {
271  /* Both or none have overflowed, just compare now to the target */
272  return target <= now;
273  } else {
274  /* Either now or target of overflowed.
275  * If it is now, then it has passed the target.
276  * If it is target, then we haven't reached it yet.
277  * */
278  return now_has_overflowed;
279  }
280 }
281 /*---------------------------------------------------------------------------*/
282 /* Schedule a wakeup at a specified offset from a reference time.
283  * Provides basic protection against missed deadlines and timer overflows
284  * A return value of zero signals a missed deadline: no rtimer was scheduled. */
285 static uint8_t
286 tsch_schedule_slot_operation(struct rtimer *tm, rtimer_clock_t ref_time, rtimer_clock_t offset, const char *str)
287 {
288  rtimer_clock_t now = RTIMER_NOW();
289  int r;
290  /* Subtract RTIMER_GUARD before checking for deadline miss
291  * because we can not schedule rtimer less than RTIMER_GUARD in the future */
292  int missed = check_timer_miss(ref_time, offset - RTIMER_GUARD, now);
293 
294  if(missed) {
295  TSCH_LOG_ADD(tsch_log_message,
296  snprintf(log->message, sizeof(log->message),
297  "!dl-miss %s %d %d",
298  str, (int)(now-ref_time), (int)offset);
299  );
300  } else {
301  r = rtimer_set(tm, ref_time + offset, 1, (void (*)(struct rtimer *, void *))tsch_slot_operation, NULL);
302  if(r == RTIMER_OK) {
303  return 1;
304  }
305  }
306 
307  /* block until the time to schedule comes */
308  RTIMER_BUSYWAIT_UNTIL_ABS(0, ref_time, offset);
309  return 0;
310 }
311 /*---------------------------------------------------------------------------*/
312 /* Schedule slot operation conditionally, and YIELD if success only.
313  * Always attempt to schedule RTIMER_GUARD before the target to make sure to wake up
314  * ahead of time and then busy wait to exactly hit the target. */
315 #define TSCH_SCHEDULE_AND_YIELD(pt, tm, ref_time, offset, str) \
316  do { \
317  if(tsch_schedule_slot_operation(tm, ref_time, offset - RTIMER_GUARD, str)) { \
318  PT_YIELD(pt); \
319  RTIMER_BUSYWAIT_UNTIL_ABS(0, ref_time, offset); \
320  } \
321  } while(0);
322 /*---------------------------------------------------------------------------*/
323 /* Get EB, broadcast or unicast packet to be sent, and target neighbor. */
324 static struct tsch_packet *
325 get_packet_and_neighbor_for_link(struct tsch_link *link, struct tsch_neighbor **target_neighbor)
326 {
327  struct tsch_packet *p = NULL;
328  struct tsch_neighbor *n = NULL;
329 
330  /* Is this a Tx link? */
331  if(link->link_options & LINK_OPTION_TX) {
332  /* is it for advertisement of EB? */
333  if(link->link_type == LINK_TYPE_ADVERTISING || link->link_type == LINK_TYPE_ADVERTISING_ONLY) {
334  /* fetch EB packets */
335  n = n_eb;
336  p = tsch_queue_get_packet_for_nbr(n, link);
337  }
338  if(link->link_type != LINK_TYPE_ADVERTISING_ONLY) {
339  /* NORMAL link or no EB to send, pick a data packet */
340  if(p == NULL) {
341  /* Get neighbor queue associated to the link and get packet from it */
342  n = tsch_queue_get_nbr(&link->addr);
343  p = tsch_queue_get_packet_for_nbr(n, link);
344  /* if it is a broadcast slot and there were no broadcast packets, pick any unicast packet */
345  if(p == NULL && n == n_broadcast) {
347  }
348  }
349  }
350  }
351  /* return nbr (by reference) */
352  if(target_neighbor != NULL) {
353  *target_neighbor = n;
354  }
355 
356  return p;
357 }
358 /*---------------------------------------------------------------------------*/
359 uint64_t
361 {
362  uint64_t uptime_asn;
363  uint64_t uptime_ticks;
364  int_master_status_t status;
365 
366  if(!tsch_is_associated) {
367  /* not associated, network uptime is not known */
368  return (uint64_t)-1;
369  }
370 
371  status = critical_enter();
372 
373  uptime_asn = last_sync_asn.ls4b + ((uint64_t)last_sync_asn.ms1b << 32);
374  /* first calculate the at the uptime at the last sync in rtimer ticks */
375  uptime_ticks = uptime_asn * tsch_timing[tsch_ts_timeslot_length];
376  /* then convert to clock ticks (assume that CLOCK_SECOND divides RTIMER_ARCH_SECOND) */
377  uptime_ticks /= (RTIMER_ARCH_SECOND / CLOCK_SECOND);
378  /* then add the ticks passed since the last timesync */
379  uptime_ticks += (clock_time() - tsch_last_sync_time);
380 
381  critical_exit(status);
382 
383  return uptime_ticks;
384 }
385 /*---------------------------------------------------------------------------*/
386 /**
387  * This function turns on the radio. Its semantics is dependent on
388  * the value of TSCH_RADIO_ON_DURING_TIMESLOT constant:
389  * - if enabled, the radio is turned on at the start of the slot
390  * - if disabled, the radio is turned on within the slot,
391  * directly before the packet Rx guard time and ACK Rx guard time.
392  */
393 static void
394 tsch_radio_on(enum tsch_radio_state_on_cmd command)
395 {
396  int do_it = 0;
397  switch(command) {
398  case TSCH_RADIO_CMD_ON_START_OF_TIMESLOT:
399  if(TSCH_RADIO_ON_DURING_TIMESLOT) {
400  do_it = 1;
401  }
402  break;
403  case TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT:
404  if(!TSCH_RADIO_ON_DURING_TIMESLOT) {
405  do_it = 1;
406  }
407  break;
408  case TSCH_RADIO_CMD_ON_FORCE:
409  do_it = 1;
410  break;
411  }
412  if(do_it) {
413  NETSTACK_RADIO.on();
414  }
415 }
416 /*---------------------------------------------------------------------------*/
417 /**
418  * This function turns off the radio. In the same way as for tsch_radio_on(),
419  * it depends on the value of TSCH_RADIO_ON_DURING_TIMESLOT constant:
420  * - if enabled, the radio is turned off at the end of the slot
421  * - if disabled, the radio is turned off within the slot,
422  * directly after Tx'ing or Rx'ing a packet or Tx'ing an ACK.
423  */
424 static void
425 tsch_radio_off(enum tsch_radio_state_off_cmd command)
426 {
427  int do_it = 0;
428  switch(command) {
429  case TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT:
430  if(TSCH_RADIO_ON_DURING_TIMESLOT) {
431  do_it = 1;
432  }
433  break;
434  case TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT:
435  if(!TSCH_RADIO_ON_DURING_TIMESLOT) {
436  do_it = 1;
437  }
438  break;
439  case TSCH_RADIO_CMD_OFF_FORCE:
440  do_it = 1;
441  break;
442  }
443  if(do_it) {
444  NETSTACK_RADIO.off();
445  }
446 }
447 /*---------------------------------------------------------------------------*/
448 static
449 PT_THREAD(tsch_tx_slot(struct pt *pt, struct rtimer *t))
450 {
451  /**
452  * TX slot:
453  * 1. Copy packet to radio buffer
454  * 2. Perform CCA if enabled
455  * 3. Sleep until it is time to transmit
456  * 4. Wait for ACK if it is a unicast packet
457  * 5. Extract drift if we received an E-ACK from a time source neighbor
458  * 6. Update CSMA parameters according to TX status
459  * 7. Schedule mac_call_sent_callback
460  **/
461 
462  /* tx status */
463  static uint8_t mac_tx_status;
464  /* is the packet in its neighbor's queue? */
465  uint8_t in_queue;
466  static int dequeued_index;
467  static int packet_ready = 1;
468 
469  PT_BEGIN(pt);
470 
471  TSCH_DEBUG_TX_EVENT();
472 
473  /* First check if we have space to store a newly dequeued packet (in case of
474  * successful Tx or Drop) */
475  dequeued_index = ringbufindex_peek_put(&dequeued_ringbuf);
476  if(dequeued_index != -1) {
477  if(current_packet == NULL || current_packet->qb == NULL) {
478  mac_tx_status = MAC_TX_ERR_FATAL;
479  } else {
480  /* packet payload */
481  static void *packet;
482 #if LLSEC802154_ENABLED
483  /* encrypted payload */
484  static uint8_t encrypted_packet[TSCH_PACKET_MAX_LEN];
485 #endif /* LLSEC802154_ENABLED */
486  /* packet payload length */
487  static uint8_t packet_len;
488  /* packet seqno */
489  static uint8_t seqno;
490  /* wait for ack? */
491  static uint8_t do_wait_for_ack;
492  static rtimer_clock_t tx_start_time;
493  /* Did we set the frame pending bit to request an extra burst link? */
494  static int burst_link_requested;
495 
496 #if TSCH_CCA_ENABLED
497  static uint8_t cca_status;
498 #endif /* TSCH_CCA_ENABLED */
499 
500  /* get payload */
501  packet = queuebuf_dataptr(current_packet->qb);
502  packet_len = queuebuf_datalen(current_packet->qb);
503  /* if is this a broadcast packet, don't wait for ack */
504  do_wait_for_ack = !current_neighbor->is_broadcast;
505  /* Unicast. More packets in queue for the neighbor? */
506  burst_link_requested = 0;
507  if(do_wait_for_ack
508  && tsch_current_burst_count + 1 < TSCH_BURST_MAX_LEN
509  && tsch_queue_packet_count(&current_neighbor->addr) > 1) {
510  burst_link_requested = 1;
511  tsch_packet_set_frame_pending(packet, packet_len);
512  }
513  /* read seqno from payload */
514  seqno = ((uint8_t *)(packet))[2];
515  /* if this is an EB, then update its Sync-IE */
516  if(current_neighbor == n_eb) {
517  packet_ready = tsch_packet_update_eb(packet, packet_len, current_packet->tsch_sync_ie_offset);
518  } else {
519  packet_ready = 1;
520  }
521 
522 #if LLSEC802154_ENABLED
523  if(tsch_is_pan_secured) {
524  /* If we are going to encrypt, we need to generate the output in a separate buffer and keep
525  * the original untouched. This is to allow for future retransmissions. */
526  int with_encryption = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_SECURITY_LEVEL) & 0x4;
527  packet_len += tsch_security_secure_frame(packet, with_encryption ? encrypted_packet : packet, current_packet->header_len,
528  packet_len - current_packet->header_len, &tsch_current_asn);
529  if(with_encryption) {
530  packet = encrypted_packet;
531  }
532  }
533 #endif /* LLSEC802154_ENABLED */
534 
535  /* prepare packet to send: copy to radio buffer */
536  if(packet_ready && NETSTACK_RADIO.prepare(packet, packet_len) == 0) { /* 0 means success */
537  static rtimer_clock_t tx_duration;
538 
539 #if TSCH_CCA_ENABLED
540  cca_status = 1;
541  /* delay before CCA */
542  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_cca_offset], "cca");
543  TSCH_DEBUG_TX_EVENT();
544  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
545  /* CCA */
546  RTIMER_BUSYWAIT_UNTIL_ABS(!(cca_status &= NETSTACK_RADIO.channel_clear()),
547  current_slot_start, tsch_timing[tsch_ts_cca_offset] + tsch_timing[tsch_ts_cca]);
548  TSCH_DEBUG_TX_EVENT();
549  /* there is not enough time to turn radio off */
550  /* NETSTACK_RADIO.off(); */
551  if(cca_status == 0) {
552  mac_tx_status = MAC_TX_COLLISION;
553  } else
554 #endif /* TSCH_CCA_ENABLED */
555  {
556  /* delay before TX */
557  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_tx_offset] - RADIO_DELAY_BEFORE_TX, "TxBeforeTx");
558  TSCH_DEBUG_TX_EVENT();
559  /* send packet already in radio tx buffer */
560  mac_tx_status = NETSTACK_RADIO.transmit(packet_len);
561  tx_count++;
562  /* Save tx timestamp */
563  tx_start_time = current_slot_start + tsch_timing[tsch_ts_tx_offset];
564  /* calculate TX duration based on sent packet len */
565  tx_duration = TSCH_PACKET_DURATION(packet_len);
566  /* limit tx_time to its max value */
567  tx_duration = MIN(tx_duration, tsch_timing[tsch_ts_max_tx]);
568  /* turn tadio off -- will turn on again to wait for ACK if needed */
569  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
570 
571  if(mac_tx_status == RADIO_TX_OK) {
572  if(do_wait_for_ack) {
573  uint8_t ackbuf[TSCH_PACKET_MAX_LEN];
574  int ack_len;
575  rtimer_clock_t ack_start_time;
576  int is_time_source;
577  struct ieee802154_ies ack_ies;
578  uint8_t ack_hdrlen;
579  frame802154_t frame;
580 
581 #if TSCH_HW_FRAME_FILTERING
582  radio_value_t radio_rx_mode;
583  /* Entering promiscuous mode so that the radio accepts the enhanced ACK */
584  NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode);
585  NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode & (~RADIO_RX_MODE_ADDRESS_FILTER));
586 #endif /* TSCH_HW_FRAME_FILTERING */
587  /* Unicast: wait for ack after tx: sleep until ack time */
588  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start,
589  tsch_timing[tsch_ts_tx_offset] + tx_duration + tsch_timing[tsch_ts_rx_ack_delay] - RADIO_DELAY_BEFORE_RX, "TxBeforeAck");
590  TSCH_DEBUG_TX_EVENT();
591  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
592  /* Wait for ACK to come */
593  RTIMER_BUSYWAIT_UNTIL_ABS(NETSTACK_RADIO.receiving_packet(),
594  tx_start_time, tx_duration + tsch_timing[tsch_ts_rx_ack_delay] + tsch_timing[tsch_ts_ack_wait] + RADIO_DELAY_BEFORE_DETECT);
595  TSCH_DEBUG_TX_EVENT();
596 
597  ack_start_time = RTIMER_NOW() - RADIO_DELAY_BEFORE_DETECT;
598 
599  /* Wait for ACK to finish */
600  RTIMER_BUSYWAIT_UNTIL_ABS(!NETSTACK_RADIO.receiving_packet(),
601  ack_start_time, tsch_timing[tsch_ts_max_ack]);
602  TSCH_DEBUG_TX_EVENT();
603  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
604 
605 #if TSCH_HW_FRAME_FILTERING
606  /* Leaving promiscuous mode */
607  NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode);
608  NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode | RADIO_RX_MODE_ADDRESS_FILTER);
609 #endif /* TSCH_HW_FRAME_FILTERING */
610 
611  /* Read ack frame */
612  ack_len = NETSTACK_RADIO.read((void *)ackbuf, sizeof(ackbuf));
613 
614  is_time_source = 0;
615  /* The radio driver should return 0 if no valid packets are in the rx buffer */
616  if(ack_len > 0) {
617  is_time_source = current_neighbor != NULL && current_neighbor->is_time_source;
618  if(tsch_packet_parse_eack(ackbuf, ack_len, seqno,
619  &frame, &ack_ies, &ack_hdrlen) == 0) {
620  ack_len = 0;
621  }
622 
623 #if LLSEC802154_ENABLED
624  if(ack_len != 0) {
625  if(!tsch_security_parse_frame(ackbuf, ack_hdrlen, ack_len - ack_hdrlen - tsch_security_mic_len(&frame),
626  &frame, &current_neighbor->addr, &tsch_current_asn)) {
627  TSCH_LOG_ADD(tsch_log_message,
628  snprintf(log->message, sizeof(log->message),
629  "!failed to authenticate ACK"));
630  ack_len = 0;
631  }
632  } else {
633  TSCH_LOG_ADD(tsch_log_message,
634  snprintf(log->message, sizeof(log->message),
635  "!failed to parse ACK"));
636  }
637 #endif /* LLSEC802154_ENABLED */
638  }
639 
640  if(ack_len != 0) {
641  if(is_time_source) {
642  int32_t eack_time_correction = US_TO_RTIMERTICKS(ack_ies.ie_time_correction);
643  int32_t since_last_timesync = TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn);
644  if(eack_time_correction > SYNC_IE_BOUND) {
645  drift_correction = SYNC_IE_BOUND;
646  } else if(eack_time_correction < -SYNC_IE_BOUND) {
647  drift_correction = -SYNC_IE_BOUND;
648  } else {
649  drift_correction = eack_time_correction;
650  }
651  if(drift_correction != eack_time_correction) {
652  TSCH_LOG_ADD(tsch_log_message,
653  snprintf(log->message, sizeof(log->message),
654  "!truncated dr %d %d", (int)eack_time_correction, (int)drift_correction);
655  );
656  }
657  tsch_stats_on_time_synchronization(eack_time_correction);
658  is_drift_correction_used = 1;
659  tsch_timesync_update(current_neighbor, since_last_timesync, drift_correction);
660  /* Keep track of sync time */
661  last_sync_asn = tsch_current_asn;
662  tsch_last_sync_time = clock_time();
664  }
665  mac_tx_status = MAC_TX_OK;
666 
667  /* We requested an extra slot and got an ack. This means
668  the extra slot will be scheduled at the received */
669  if(burst_link_requested) {
670  burst_link_scheduled = 1;
671  }
672  } else {
673  mac_tx_status = MAC_TX_NOACK;
674  }
675  } else {
676  mac_tx_status = MAC_TX_OK;
677  }
678  } else {
679  mac_tx_status = MAC_TX_ERR;
680  }
681  }
682  } else {
683  mac_tx_status = MAC_TX_ERR;
684  }
685  }
686 
687  tsch_radio_off(TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT);
688 
689  current_packet->transmissions++;
690  current_packet->ret = mac_tx_status;
691 
692  /* Post TX: Update neighbor queue state */
693  in_queue = tsch_queue_packet_sent(current_neighbor, current_packet, current_link, mac_tx_status);
694 
695  /* The packet was dequeued, add it to dequeued_ringbuf for later processing */
696  if(in_queue == 0) {
697  dequeued_array[dequeued_index] = current_packet;
698  ringbufindex_put(&dequeued_ringbuf);
699  }
700 
701  /* If this is an unicast packet to timesource, update stats */
702  if(current_neighbor != NULL && current_neighbor->is_time_source) {
703  tsch_stats_tx_packet(current_neighbor, mac_tx_status, tsch_current_channel);
704  }
705 
706  /* Log every tx attempt */
707  TSCH_LOG_ADD(tsch_log_tx,
708  log->tx.mac_tx_status = mac_tx_status;
709  log->tx.num_tx = current_packet->transmissions;
710  log->tx.datalen = queuebuf_datalen(current_packet->qb);
711  log->tx.drift = drift_correction;
712  log->tx.drift_used = is_drift_correction_used;
713  log->tx.is_data = ((((uint8_t *)(queuebuf_dataptr(current_packet->qb)))[0]) & 7) == FRAME802154_DATAFRAME;
714 #if LLSEC802154_ENABLED
715  log->tx.sec_level = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_SECURITY_LEVEL);
716 #else /* LLSEC802154_ENABLED */
717  log->tx.sec_level = 0;
718 #endif /* LLSEC802154_ENABLED */
719  linkaddr_copy(&log->tx.dest, queuebuf_addr(current_packet->qb, PACKETBUF_ADDR_RECEIVER));
720  log->tx.seqno = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_MAC_SEQNO);
721  );
722 
723  /* Poll process for later processing of packet sent events and logs */
724  process_poll(&tsch_pending_events_process);
725  }
726 
727  TSCH_DEBUG_TX_EVENT();
728 
729  PT_END(pt);
730 }
731 /*---------------------------------------------------------------------------*/
732 static
733 PT_THREAD(tsch_rx_slot(struct pt *pt, struct rtimer *t))
734 {
735  /**
736  * RX slot:
737  * 1. Check if it is used for TIME_KEEPING
738  * 2. Sleep and wake up just before expected RX time (with a guard time: TS_LONG_GT)
739  * 3. Check for radio activity for the guard time: TS_LONG_GT
740  * 4. Prepare and send ACK if needed
741  * 5. Drift calculated in the ACK callback registered with the radio driver. Use it if receiving from a time source neighbor.
742  **/
743 
744  struct tsch_neighbor *n;
745  static linkaddr_t source_address;
746  static linkaddr_t destination_address;
747  static int16_t input_index;
748  static int input_queue_drop = 0;
749 
750  PT_BEGIN(pt);
751 
752  TSCH_DEBUG_RX_EVENT();
753 
754  input_index = ringbufindex_peek_put(&input_ringbuf);
755  if(input_index == -1) {
756  input_queue_drop++;
757  } else {
758  static struct input_packet *current_input;
759  /* Estimated drift based on RX time */
760  static int32_t estimated_drift;
761  /* Rx timestamps */
762  static rtimer_clock_t rx_start_time;
763  static rtimer_clock_t expected_rx_time;
764  static rtimer_clock_t packet_duration;
765  uint8_t packet_seen;
766 
767  expected_rx_time = current_slot_start + tsch_timing[tsch_ts_tx_offset];
768  /* Default start time: expected Rx time */
769  rx_start_time = expected_rx_time;
770 
771  current_input = &input_array[input_index];
772 
773  /* Wait before starting to listen */
774  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_rx_offset] - RADIO_DELAY_BEFORE_RX, "RxBeforeListen");
775  TSCH_DEBUG_RX_EVENT();
776 
777  /* Start radio for at least guard time */
778  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
779  packet_seen = NETSTACK_RADIO.receiving_packet() || NETSTACK_RADIO.pending_packet();
780  if(!packet_seen) {
781  /* Check if receiving within guard time */
782  RTIMER_BUSYWAIT_UNTIL_ABS((packet_seen = NETSTACK_RADIO.receiving_packet()),
783  current_slot_start, tsch_timing[tsch_ts_rx_offset] + tsch_timing[tsch_ts_rx_wait] + RADIO_DELAY_BEFORE_DETECT);
784  }
785  if(!packet_seen) {
786  /* no packets on air */
787  tsch_radio_off(TSCH_RADIO_CMD_OFF_FORCE);
788  } else {
789  TSCH_DEBUG_RX_EVENT();
790  /* Save packet timestamp */
791  rx_start_time = RTIMER_NOW() - RADIO_DELAY_BEFORE_DETECT;
792 
793  /* Wait until packet is received, turn radio off */
794  RTIMER_BUSYWAIT_UNTIL_ABS(!NETSTACK_RADIO.receiving_packet(),
795  current_slot_start, tsch_timing[tsch_ts_rx_offset] + tsch_timing[tsch_ts_rx_wait] + tsch_timing[tsch_ts_max_tx]);
796  TSCH_DEBUG_RX_EVENT();
797  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
798 
799  if(NETSTACK_RADIO.pending_packet()) {
800  static int frame_valid;
801  static int header_len;
802  static frame802154_t frame;
803  radio_value_t radio_last_rssi;
804  radio_value_t radio_last_lqi;
805 
806  /* Read packet */
807  current_input->len = NETSTACK_RADIO.read((void *)current_input->payload, TSCH_PACKET_MAX_LEN);
808  NETSTACK_RADIO.get_value(RADIO_PARAM_LAST_RSSI, &radio_last_rssi);
809  current_input->rx_asn = tsch_current_asn;
810  current_input->rssi = (signed)radio_last_rssi;
811  current_input->channel = tsch_current_channel;
812  header_len = frame802154_parse((uint8_t *)current_input->payload, current_input->len, &frame);
813  frame_valid = header_len > 0 &&
814  frame802154_check_dest_panid(&frame) &&
815  frame802154_extract_linkaddr(&frame, &source_address, &destination_address);
816 
817 #if TSCH_RESYNC_WITH_SFD_TIMESTAMPS
818  /* At the end of the reception, get an more accurate estimate of SFD arrival time */
819  NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &rx_start_time, sizeof(rtimer_clock_t));
820 #endif
821 
822  packet_duration = TSCH_PACKET_DURATION(current_input->len);
823  /* limit packet_duration to its max value */
824  packet_duration = MIN(packet_duration, tsch_timing[tsch_ts_max_tx]);
825 
826  if(!frame_valid) {
827  TSCH_LOG_ADD(tsch_log_message,
828  snprintf(log->message, sizeof(log->message),
829  "!failed to parse frame %u %u", header_len, current_input->len));
830  }
831 
832  if(frame_valid) {
833  if(frame.fcf.frame_type != FRAME802154_DATAFRAME
834  && frame.fcf.frame_type != FRAME802154_BEACONFRAME) {
835  TSCH_LOG_ADD(tsch_log_message,
836  snprintf(log->message, sizeof(log->message),
837  "!discarding frame with type %u, len %u", frame.fcf.frame_type, current_input->len));
838  frame_valid = 0;
839  }
840  }
841 
842 #if LLSEC802154_ENABLED
843  /* Decrypt and verify incoming frame */
844  if(frame_valid) {
846  current_input->payload, header_len, current_input->len - header_len - tsch_security_mic_len(&frame),
847  &frame, &source_address, &tsch_current_asn)) {
848  current_input->len -= tsch_security_mic_len(&frame);
849  } else {
850  TSCH_LOG_ADD(tsch_log_message,
851  snprintf(log->message, sizeof(log->message),
852  "!failed to authenticate frame %u", current_input->len));
853  frame_valid = 0;
854  }
855  }
856 #endif /* LLSEC802154_ENABLED */
857 
858  if(frame_valid) {
859  /* Check that frome is for us or broadcast, AND that it is not from
860  * ourselves. This is for consistency with CSMA and to avoid adding
861  * ourselves to neighbor tables in case frames are being replayed. */
862  if((linkaddr_cmp(&destination_address, &linkaddr_node_addr)
863  || linkaddr_cmp(&destination_address, &linkaddr_null))
864  && !linkaddr_cmp(&source_address, &linkaddr_node_addr)) {
865  int do_nack = 0;
866  rx_count++;
867  estimated_drift = RTIMER_CLOCK_DIFF(expected_rx_time, rx_start_time);
868  tsch_stats_on_time_synchronization(estimated_drift);
869 
870 #if TSCH_TIMESYNC_REMOVE_JITTER
871  /* remove jitter due to measurement errors */
872  if(ABS(estimated_drift) <= TSCH_TIMESYNC_MEASUREMENT_ERROR) {
873  estimated_drift = 0;
874  } else if(estimated_drift > 0) {
875  estimated_drift -= TSCH_TIMESYNC_MEASUREMENT_ERROR;
876  } else {
877  estimated_drift += TSCH_TIMESYNC_MEASUREMENT_ERROR;
878  }
879 #endif
880 
881 #ifdef TSCH_CALLBACK_DO_NACK
882  if(frame.fcf.ack_required) {
883  do_nack = TSCH_CALLBACK_DO_NACK(current_link,
884  &source_address, &destination_address);
885  }
886 #endif
887 
888  if(frame.fcf.ack_required) {
889  static uint8_t ack_buf[TSCH_PACKET_MAX_LEN];
890  static int ack_len;
891 
892  /* Build ACK frame */
893  ack_len = tsch_packet_create_eack(ack_buf, sizeof(ack_buf),
894  &source_address, frame.seq, (int16_t)RTIMERTICKS_TO_US(estimated_drift), do_nack);
895 
896  if(ack_len > 0) {
897 #if LLSEC802154_ENABLED
898  if(tsch_is_pan_secured) {
899  /* Secure ACK frame. There is only header and header IEs, therefore data len == 0. */
900  ack_len += tsch_security_secure_frame(ack_buf, ack_buf, ack_len, 0, &tsch_current_asn);
901  }
902 #endif /* LLSEC802154_ENABLED */
903 
904  /* Copy to radio buffer */
905  NETSTACK_RADIO.prepare((const void *)ack_buf, ack_len);
906 
907  /* Wait for time to ACK and transmit ACK */
908  TSCH_SCHEDULE_AND_YIELD(pt, t, rx_start_time,
909  packet_duration + tsch_timing[tsch_ts_tx_ack_delay] - RADIO_DELAY_BEFORE_TX, "RxBeforeAck");
910  TSCH_DEBUG_RX_EVENT();
911  NETSTACK_RADIO.transmit(ack_len);
912  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
913 
914  /* Schedule a burst link iff the frame pending bit was set */
915  burst_link_scheduled = tsch_packet_get_frame_pending(current_input->payload, current_input->len);
916  }
917  }
918 
919  /* If the sender is a time source, proceed to clock drift compensation */
920  n = tsch_queue_get_nbr(&source_address);
921  if(n != NULL && n->is_time_source) {
922  int32_t since_last_timesync = TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn);
923  /* Keep track of last sync time */
924  last_sync_asn = tsch_current_asn;
925  tsch_last_sync_time = clock_time();
926  /* Save estimated drift */
927  drift_correction = -estimated_drift;
928  is_drift_correction_used = 1;
929  sync_count++;
930  tsch_timesync_update(n, since_last_timesync, -estimated_drift);
932  }
933 
934  /* Add current input to ringbuf */
935  ringbufindex_put(&input_ringbuf);
936 
937  /* If the neighbor is known, update its stats */
938  if(n != NULL) {
939  NETSTACK_RADIO.get_value(RADIO_PARAM_LAST_LINK_QUALITY, &radio_last_lqi);
940  tsch_stats_rx_packet(n, current_input->rssi, radio_last_lqi, tsch_current_channel);
941  }
942 
943  /* Log every reception */
944  TSCH_LOG_ADD(tsch_log_rx,
945  linkaddr_copy(&log->rx.src, (linkaddr_t *)&frame.src_addr);
946  log->rx.is_unicast = frame.fcf.ack_required;
947  log->rx.datalen = current_input->len;
948  log->rx.drift = drift_correction;
949  log->rx.drift_used = is_drift_correction_used;
950  log->rx.is_data = frame.fcf.frame_type == FRAME802154_DATAFRAME;
951  log->rx.sec_level = frame.aux_hdr.security_control.security_level;
952  log->rx.estimated_drift = estimated_drift;
953  log->rx.seqno = frame.seq;
954  );
955  }
956 
957  /* Poll process for processing of pending input and logs */
958  process_poll(&tsch_pending_events_process);
959  }
960  }
961 
962  tsch_radio_off(TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT);
963  }
964 
965  if(input_queue_drop != 0) {
966  TSCH_LOG_ADD(tsch_log_message,
967  snprintf(log->message, sizeof(log->message),
968  "!queue full skipped %u", input_queue_drop);
969  );
970  input_queue_drop = 0;
971  }
972  }
973 
974  TSCH_DEBUG_RX_EVENT();
975 
976  PT_END(pt);
977 }
978 /*---------------------------------------------------------------------------*/
979 /* Protothread for slot operation, called from rtimer interrupt
980  * and scheduled from tsch_schedule_slot_operation */
981 static
982 PT_THREAD(tsch_slot_operation(struct rtimer *t, void *ptr))
983 {
984  TSCH_DEBUG_INTERRUPT();
985  PT_BEGIN(&slot_operation_pt);
986 
987  /* Loop over all active slots */
988  while(tsch_is_associated) {
989 
990  if(current_link == NULL || tsch_lock_requested) { /* Skip slot operation if there is no link
991  or if there is a pending request for getting the lock */
992  /* Issue a log whenever skipping a slot */
993  TSCH_LOG_ADD(tsch_log_message,
994  snprintf(log->message, sizeof(log->message),
995  "!skipped slot %u %u %u",
996  tsch_locked,
997  tsch_lock_requested,
998  current_link == NULL);
999  );
1000 
1001  } else {
1002  int is_active_slot;
1003  TSCH_DEBUG_SLOT_START();
1004  tsch_in_slot_operation = 1;
1005  /* Measure on-air noise level while TSCH is idle */
1006  tsch_stats_sample_rssi();
1007  /* Reset drift correction */
1008  drift_correction = 0;
1009  is_drift_correction_used = 0;
1010  /* Get a packet ready to be sent */
1011  current_packet = get_packet_and_neighbor_for_link(current_link, &current_neighbor);
1012  /* There is no packet to send, and this link does not have Rx flag. Instead of doing
1013  * nothing, switch to the backup link (has Rx flag) if any. */
1014  if(current_packet == NULL && !(current_link->link_options & LINK_OPTION_RX) && backup_link != NULL) {
1015  current_link = backup_link;
1016  current_packet = get_packet_and_neighbor_for_link(current_link, &current_neighbor);
1017  }
1018  is_active_slot = current_packet != NULL || (current_link->link_options & LINK_OPTION_RX);
1019  if(is_active_slot) {
1020  /* If we are in a burst, we stick to current channel instead of
1021  * doing channel hopping, as per IEEE 802.15.4-2015 */
1022  if(burst_link_scheduled) {
1023  /* Reset burst_link_scheduled flag. Will be set again if burst continue. */
1024  burst_link_scheduled = 0;
1025  } else {
1026  /* Hop channel */
1027  tsch_current_channel = tsch_calculate_channel(&tsch_current_asn,
1028  current_link->channel_offset, current_packet);
1029  }
1030  NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, tsch_current_channel);
1031  /* Turn the radio on already here if configured so; necessary for radios with slow startup */
1032  tsch_radio_on(TSCH_RADIO_CMD_ON_START_OF_TIMESLOT);
1033  /* Decide whether it is a TX/RX/IDLE or OFF slot */
1034  /* Actual slot operation */
1035  if(current_packet != NULL) {
1036  /* We have something to transmit, do the following:
1037  * 1. send
1038  * 2. update_backoff_state(current_neighbor)
1039  * 3. post tx callback
1040  **/
1041  static struct pt slot_tx_pt;
1042  PT_SPAWN(&slot_operation_pt, &slot_tx_pt, tsch_tx_slot(&slot_tx_pt, t));
1043  } else {
1044  /* Listen */
1045  static struct pt slot_rx_pt;
1046  PT_SPAWN(&slot_operation_pt, &slot_rx_pt, tsch_rx_slot(&slot_rx_pt, t));
1047  }
1048  } else {
1049  /* Make sure to end the burst in cast, for some reason, we were
1050  * in a burst but now without any more packet to send. */
1051  burst_link_scheduled = 0;
1052  }
1053  TSCH_DEBUG_SLOT_END();
1054  }
1055 
1056  /* End of slot operation, schedule next slot or resynchronize */
1057 
1058  if(tsch_is_coordinator) {
1059  /* Update the `last_sync_*` variables to avoid large errors
1060  * in the application-level time synchronization */
1061  last_sync_asn = tsch_current_asn;
1062  tsch_last_sync_time = clock_time();
1063  }
1064 
1065  /* Do we need to resynchronize? i.e., wait for EB again */
1066  if(!tsch_is_coordinator && (TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn) >
1067  (100 * TSCH_CLOCK_TO_SLOTS(TSCH_DESYNC_THRESHOLD / 100, tsch_timing[tsch_ts_timeslot_length])))) {
1068  TSCH_LOG_ADD(tsch_log_message,
1069  snprintf(log->message, sizeof(log->message),
1070  "! leaving the network, last sync %u",
1071  (unsigned)TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn));
1072  );
1074  } else {
1075  /* backup of drift correction for printing debug messages */
1076  /* int32_t drift_correction_backup = drift_correction; */
1077  uint16_t timeslot_diff = 0;
1078  rtimer_clock_t prev_slot_start;
1079  /* Time to next wake up */
1080  rtimer_clock_t time_to_next_active_slot;
1081  /* Schedule next wakeup skipping slots if missed deadline */
1082  do {
1083  if(current_link != NULL
1084  && current_link->link_options & LINK_OPTION_TX
1085  && current_link->link_options & LINK_OPTION_SHARED) {
1086  /* Decrement the backoff window for all neighbors able to transmit over
1087  * this Tx, Shared link. */
1088  tsch_queue_update_all_backoff_windows(&current_link->addr);
1089  }
1090 
1091  /* A burst link was scheduled. Replay the current link at the
1092  next time offset */
1093  if(burst_link_scheduled && current_link != NULL) {
1094  timeslot_diff = 1;
1095  backup_link = NULL;
1096  /* Keep track of the number of repetitions */
1097  tsch_current_burst_count++;
1098  } else {
1099  /* Get next active link */
1100  current_link = tsch_schedule_get_next_active_link(&tsch_current_asn, &timeslot_diff, &backup_link);
1101  if(current_link == NULL) {
1102  /* There is no next link. Fall back to default
1103  * behavior: wake up at the next slot. */
1104  timeslot_diff = 1;
1105  } else {
1106  /* Reset burst index now that the link was scheduled from
1107  normal schedule (as opposed to from ongoing burst) */
1108  tsch_current_burst_count = 0;
1109  }
1110  }
1111 
1112  /* Update ASN */
1113  TSCH_ASN_INC(tsch_current_asn, timeslot_diff);
1114  /* Time to next wake up */
1115  time_to_next_active_slot = timeslot_diff * tsch_timing[tsch_ts_timeslot_length] + drift_correction;
1116  time_to_next_active_slot += tsch_timesync_adaptive_compensate(time_to_next_active_slot);
1117  drift_correction = 0;
1118  is_drift_correction_used = 0;
1119  /* Update current slot start */
1120  prev_slot_start = current_slot_start;
1121  current_slot_start += time_to_next_active_slot;
1122  } while(!tsch_schedule_slot_operation(t, prev_slot_start, time_to_next_active_slot, "main"));
1123  }
1124 
1125  tsch_in_slot_operation = 0;
1126  PT_YIELD(&slot_operation_pt);
1127  }
1128 
1129  PT_END(&slot_operation_pt);
1130 }
1131 /*---------------------------------------------------------------------------*/
1132 /* Set global time before starting slot operation,
1133  * with a rtimer time and an ASN */
1134 void
1136 {
1137  static struct rtimer slot_operation_timer;
1138  rtimer_clock_t time_to_next_active_slot;
1139  rtimer_clock_t prev_slot_start;
1140  TSCH_DEBUG_INIT();
1141  do {
1142  uint16_t timeslot_diff;
1143  /* Get next active link */
1144  current_link = tsch_schedule_get_next_active_link(&tsch_current_asn, &timeslot_diff, &backup_link);
1145  if(current_link == NULL) {
1146  /* There is no next link. Fall back to default
1147  * behavior: wake up at the next slot. */
1148  timeslot_diff = 1;
1149  }
1150  /* Update ASN */
1151  TSCH_ASN_INC(tsch_current_asn, timeslot_diff);
1152  /* Time to next wake up */
1153  time_to_next_active_slot = timeslot_diff * tsch_timing[tsch_ts_timeslot_length];
1154  /* Update current slot start */
1155  prev_slot_start = current_slot_start;
1156  current_slot_start += time_to_next_active_slot;
1157  } while(!tsch_schedule_slot_operation(&slot_operation_timer, prev_slot_start, time_to_next_active_slot, "assoc"));
1158 }
1159 /*---------------------------------------------------------------------------*/
1160 /* Start actual slot operation */
1161 void
1162 tsch_slot_operation_sync(rtimer_clock_t next_slot_start,
1163  struct tsch_asn_t *next_slot_asn)
1164 {
1165  int_master_status_t status;
1166 
1167  current_slot_start = next_slot_start;
1168  tsch_current_asn = *next_slot_asn;
1169  status = critical_enter();
1170  last_sync_asn = tsch_current_asn;
1171  tsch_last_sync_time = clock_time();
1172  critical_exit(status);
1173  current_link = NULL;
1174 }
1175 /*---------------------------------------------------------------------------*/
1176 /** @} */
TSCH packet information.
Definition: tsch-types.h:97
#define TSCH_LOG_ADD(log_type, init_code)
Use this macro to add a log to the queue (will be printed out later, after leaving interrupt context)...
Definition: tsch-log.h:140
frame802154_scf_t security_control
Security control bitfield.
Definition: frame802154.h:188
struct tsch_neighbor * tsch_queue_get_nbr(const linkaddr_t *addr)
Get a TSCH neighbor.
Definition: tsch-queue.c:108
static void tsch_radio_off(enum tsch_radio_state_off_cmd command)
This function turns off the radio.
int rtimer_set(struct rtimer *rtimer, rtimer_clock_t time, rtimer_clock_t duration, rtimer_callback_t func, void *ptr)
Post a real-time task.
Definition: rtimer.c:67
The MAC layer did not get an acknowledgement for the packet.
Definition: mac.h:91
frame802154_fcf_t fcf
Frame control field.
Definition: frame802154.h:204
Representation of a real-time task.
Definition: rtimer.h:133
int tsch_get_lock(void)
Takes the TSCH lock.
Header file for the radio API
uint8_t security_level
3 bit.
Definition: frame802154.h:168
static void critical_exit(int_master_status_t status)
Exit a critical section and restore the master interrupt.
Definition: critical.h:81
void tsch_release_lock(void)
Releases the TSCH lock.
int frame802154_parse(uint8_t *data, int len, frame802154_t *pf)
Parses an input frame.
Definition: frame802154.c:500
TSCH neighbor information.
Definition: tsch-types.h:109
void tsch_queue_update_all_backoff_windows(const linkaddr_t *dest_addr)
Decrement backoff window for the queue(s) able to Tx to a given address.
Definition: tsch-queue.c:510
unsigned int tsch_security_parse_frame(const uint8_t *hdr, int hdrlen, int datalen, const frame802154_t *frame, const linkaddr_t *sender, struct tsch_asn_t *asn)
Parse and check a frame protected with encryption and/or MIC.
#define PT_BEGIN(pt)
Declare the start of a protothread inside the C function implementing the protothread.
Definition: pt.h:114
void tsch_timesync_update(struct tsch_neighbor *n, uint16_t time_delta_asn, int32_t drift_correction)
Updates timesync information for a given neighbor.
int radio_value_t
Each radio has a set of parameters that designate the current configuration and state of the radio...
Definition: radio.h:88
uint8_t src_addr[8]
Source address.
Definition: frame802154.h:203
A MAC framer for IEEE 802.15.4
const linkaddr_t linkaddr_null
The null link-layer address.
#define PT_SPAWN(pt, child, thread)
Spawn a child protothread and wait until it exits.
Definition: pt.h:205
The MAC layer transmission was OK.
Definition: mac.h:87
rtimer task is scheduled successfully
Definition: rtimer.h:143
int tsch_packet_update_eb(uint8_t *buf, int buf_size, uint8_t tsch_sync_ie_offset)
Update ASN in EB packet.
Definition: tsch-packet.c:377
linkaddr_t linkaddr_node_addr
The link-layer address of the node.
Definition: linkaddr.c:48
static int_master_status_t critical_enter()
Enter a critical section.
Definition: critical.h:65
#define RTIMER_NOW()
Get the current clock time.
Definition: rtimer.h:185
int32_t tsch_timesync_adaptive_compensate(rtimer_clock_t delta_ticks)
Computes time compensation for a given point in the future.
unsigned int tsch_security_mic_len(const frame802154_t *frame)
Return MIC length.
INT_MASTER_STATUS_DATATYPE int_master_status_t
Master interrupt state representation data type.
Definition: int-master.h:62
#define CLOCK_SECOND
A second, measured in system clock time.
Definition: clock.h:82
#define PT_END(pt)
Declare the end of a protothread.
Definition: pt.h:126
Header file for the Packet queue buffer management
void process_poll(struct process *p)
Request a process to be polled.
Definition: process.c:371
struct tsch_link * tsch_schedule_get_next_active_link(struct tsch_asn_t *asn, uint16_t *time_offset, struct tsch_link **backup_link)
Returns the next active link after a given ASN, and a backup link (for the same ASN, with Rx flag)
void tsch_schedule_keepalive(int immediate)
Schedule a keep-alive transmission within [timeout*0.9, timeout[ Can be called from an interrupt...
Definition: tsch.c:330
#define TSCH_ASN_MOD(asn, div)
Returns the result (16 bits) of a modulo operation on ASN, with divisor being a struct asn_divisor_t...
Definition: tsch-asn.h:93
#define PT_YIELD(pt)
Yield from the current protothread.
Definition: pt.h:289
int tsch_packet_parse_eack(const uint8_t *buf, int buf_size, uint8_t seqno, frame802154_t *frame, struct ieee802154_ies *ies, uint8_t *hdr_len)
Parse enhanced ACK packet.
Definition: tsch-packet.c:155
Main API declarations for TSCH.
clock_time_t clock_time(void)
Get the current clock time.
Definition: clock.c:118
#define RTIMER_BUSYWAIT_UNTIL_ABS(cond, t0, max_time)
Busy-wait until a condition.
Definition: rtimer.h:202
The MAC layer transmission could not be performed because of a fatal error.
Definition: mac.h:101
struct tsch_packet * tsch_queue_get_packet_for_nbr(const struct tsch_neighbor *n, struct tsch_link *link)
Returns the first packet that can be sent from a queue on a given link.
Definition: tsch-queue.c:417
#define RADIO_RX_MODE_ADDRESS_FILTER
The radio reception mode controls address filtering and automatic transmission of acknowledgements in...
Definition: radio.h:252
int tsch_is_locked(void)
Checks if the TSCH lock is set.
uint8_t frame_type
3 bit.
Definition: frame802154.h:153
void tsch_slot_operation_sync(rtimer_clock_t next_slot_start, struct tsch_asn_t *next_slot_asn)
Set global time before starting slot operation, with a rtimer time and an ASN.
Parameters used by the frame802154_create() function.
Definition: frame802154.h:198
void linkaddr_copy(linkaddr_t *dest, const linkaddr_t *src)
Copy a link-layer address.
Definition: linkaddr.c:63
#define PT_THREAD(name_args)
Declaration of a protothread.
Definition: pt.h:99
uint64_t tsch_get_network_uptime_ticks(void)
Get the time, in clock ticks, since the TSCH network was started.
void tsch_packet_set_frame_pending(uint8_t *buf, int buf_size)
Set frame pending bit in a packet (whose header was already build)
Definition: tsch-packet.c:453
int tsch_queue_packet_sent(struct tsch_neighbor *n, struct tsch_packet *p, struct tsch_link *link, uint8_t mac_tx_status)
Updates neighbor queue state after a transmission.
Definition: tsch-queue.c:329
#define TSCH_ASN_DIFF(asn1, asn2)
Returns the 32-bit diff between asn1 and asn2.
Definition: tsch-asn.h:82
int linkaddr_cmp(const linkaddr_t *addr1, const linkaddr_t *addr2)
Compare two link-layer addresses.
Definition: linkaddr.c:69
static void tsch_radio_on(enum tsch_radio_state_on_cmd command)
This function turns on the radio.
int tsch_queue_packet_count(const linkaddr_t *addr)
Returns the number of packets currently a given neighbor queue.
Definition: tsch-queue.c:287
#define TSCH_ASN_INC(asn, inc)
Increment an ASN by inc (32 bits)
Definition: tsch-asn.h:68
uint8_t seq
Sequence number.
Definition: frame802154.h:205
int tsch_packet_get_frame_pending(uint8_t *buf, int buf_size)
Get frame pending bit from a packet.
Definition: tsch-packet.c:460
int ringbufindex_peek_put(const struct ringbufindex *r)
Check if there is space to put an element.
Definition: ringbufindex.c:78
void tsch_disassociate(void)
Leave the TSCH network we are currently in.
Definition: tsch.c:567
Header file for the Packet buffer (packetbuf) management
Include file for the Contiki low-layer network stack (NETSTACK)
void watchdog_periodic(void)
Writes the WDT clear sequence.
Definition: watchdog.c:85
struct tsch_packet * tsch_queue_get_unicast_packet_for_any(struct tsch_neighbor **n, struct tsch_link *link)
Gets the head packet of any neighbor queue with zero backoff counter.
Definition: tsch-queue.c:456
unsigned int tsch_security_secure_frame(uint8_t *hdr, uint8_t *outbuf, int hdrlen, int datalen, struct tsch_asn_t *asn)
Protect a frame with encryption and/or MIC.
Stores data about an incoming packet.
Definition: tsch-types.h:152
Header file for the logging system
The MAC layer deferred the transmission for a later time.
Definition: mac.h:94
uint8_t ack_required
1 bit.
Definition: frame802154.h:156
int ringbufindex_put(struct ringbufindex *r)
Put one element to the ring buffer.
Definition: ringbufindex.c:58
void tsch_slot_operation_start(void)
Start actual slot operation.
The ASN is an absolute slot number over 5 bytes.
Definition: tsch-asn.h:48
frame802154_aux_hdr_t aux_hdr
Aux security header.
Definition: frame802154.h:208
uint8_t tsch_calculate_channel(struct tsch_asn_t *asn, uint16_t channel_offset, struct tsch_packet *p)
Returns a 802.15.4 channel from an ASN and channel offset.
int tsch_packet_create_eack(uint8_t *buf, uint16_t buf_len, const linkaddr_t *dest_addr, uint8_t seqno, int16_t drift, int nack)
Construct Enhanced ACK packet.
Definition: tsch-packet.c:93