summaryrefslogtreecommitdiff
path: root/mac/fira_session_fsm_active.c
blob: 90ddc941f7e9722cea6af139b8106e7a18e2ba9d (plain)
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
/*
 * This file is part of the UWB stack for linux.
 *
 * Copyright (c) 2022 Qorvo US, Inc.
 *
 * This software is provided under the GNU General Public License, version 2
 * (GPLv2), as well as under a Qorvo commercial license.
 *
 * You may choose to use this software under the terms of the GPLv2 License,
 * version 2 ("GPLv2"), as published by the Free Software Foundation.
 * You should have received a copy of the GPLv2 along with this program.  If
 * not, see <http://www.gnu.org/licenses/>.
 *
 * This program is distributed under the GPLv2 in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GPLv2 for more
 * details.
 *
 * If you cannot meet the requirements of the GPLv2, you may not use this
 * software for any purpose without first obtaining a commercial license from
 * Qorvo. Please contact Qorvo to inquire about licensing terms.
 */

#include <net/mcps802154_frame.h>
#include <net/fira_region_nl.h>
#include <linux/errno.h>
#include <linux/math64.h>

#include "fira_round_hopping_sequence.h"
#include "fira_session_fsm_init.h"
#include "fira_session_fsm_idle.h"
#include "fira_session_fsm_active.h"
#include "fira_session.h"
#include "fira_trace.h"
#include "warn_return.h"

/**
 * list_move_to_active() - Move from inactive list to active list.
 * @local: FiRa context.
 * @session: Session context.
 */
static void list_move_to_active(struct fira_local *local,
				struct fira_session *session)
{
	struct list_head *position = &local->active_sessions;
	struct fira_session *tmp;

	/*
	 * Search the position to maintain a list sorted from highest to
	 * lowest priority. And for the same priority keep the call
	 * order (moved to the tail).
	 * Highest value of priority is the highest priority.
	 * Range of priority is between: 0 to FIRA_PRIORITY_MAX.
	 */
	list_for_each_entry (tmp, &local->active_sessions, entry) {
		if (session->params.priority <= tmp->params.priority)
			position = &tmp->entry;
		else
			break;
	}
	list_move(&session->entry, position);
}

/**
 * get_channel() - Retrieve the channel to applied on the access.
 * @local: FiRa context.
 * @session: Session context.
 *
 * Return: The channel.
 */
static const struct mcps802154_channel *
get_channel(struct fira_local *local, const struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;

	if (params->channel_number || params->preamble_code_index) {
		const struct mcps802154_channel *channel =
			mcps802154_get_current_channel(local->llhw);

		local->channel = *channel;
		if (params->channel_number)
			local->channel.channel = params->channel_number;
		if (params->preamble_code_index)
			local->channel.preamble_code =
				params->preamble_code_index;
		return &local->channel;
	}
	return NULL;
}

/**
 * get_round_index() - Return the round index for a specific block index.
 * @session: Session context.
 * @block_index: Block index.
 *
 * Return: Round index freshly computed or the round index saved.
 */
static int get_round_index(const struct fira_session *session, int block_index)
{
	const struct fira_session_params *params = &session->params;
	int expected_block_index;

	switch (params->device_type) {
	default:
	case FIRA_DEVICE_TYPE_CONTROLLER:
		if (!params->round_hopping)
			return 0;
		/*
		 * Avoid to rebuild the round_index.
		 * The condition is true on first get_access too.
		 */
		if (session->controller.next_block_index == block_index)
			return session->next_round_index;
		break;
	case FIRA_DEVICE_TYPE_CONTROLEE:
		if (!session->controlee.hopping_mode)
			return 0;
		/*
		 * Return the round index received, only when the block index
		 * match with expected block index.
		 */
		expected_block_index = session->controlee.block_index_sync +
				       session->block_stride_len + 1;
		if (expected_block_index == block_index &&
		    session->controlee.next_round_index_valid)
			return session->next_round_index;
		break;
	}
	return fira_round_hopping_sequence_get(session, block_index);
}

/**
 * get_rx_margin_duration_dtu() - Build the maximum margin tolerance for Rx.
 * @local: FiRa context.
 * @session: Session context.
 *
 * Return: Duration to apply on first and Rx frame of controlee's access.
 */
static int get_rx_margin_duration_dtu(const struct fira_local *local,
				      const struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;
	s64 duration_dtu = (s64)(session->block_stride_len + 1) *
			   params->block_duration_dtu;
	/*
	 * TODO: Unit test should be able to predic timestamp.
	 * - Replace 'local->block_duration_rx_margin_ppm by'
	 *   UWB_BLOCK_DURATION_MARGIN_PPM
	 * - Remove 'local' from args.
	 */
	return div64_s64(duration_dtu * local->block_duration_rx_margin_ppm,
			 1000000);
}

/**
 * get_next_access_timestamp_dtu() - Build the next access timestamp.
 * @local: FiRa context.
 * @session: Session context.
 *
 * Return: Timestamp in dtu.
 */
static u32 get_next_access_timestamp_dtu(const struct fira_local *local,
					 const struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;
	int add_blocks = session->block_stride_len + 1;
	int next_block_index = session->block_index + add_blocks;
	int next_round_index = get_round_index(session, next_block_index);
	int round_duration_dtu =
		params->round_duration_slots * params->slot_duration_dtu;
	u32 next_block_start_dtu = session->block_start_dtu +
				   add_blocks * params->block_duration_dtu +
				   next_round_index * round_duration_dtu;

	switch (params->device_type) {
	default:
	case FIRA_DEVICE_TYPE_CONTROLLER:
		return next_block_start_dtu;
	case FIRA_DEVICE_TYPE_CONTROLEE:
		return next_block_start_dtu -
		       get_rx_margin_duration_dtu(local, session);
	}
}

/**
 * is_controlee_synchronised() - Answer to the question of the synchronisation
 * status.
 * @local: FiRa context.
 * @session: Session context.
 *
 * Return: True when the controlee session is still synchronized.
 */
static bool is_controlee_synchronised(const struct fira_local *local,
				      const struct fira_session *session)
{
#define FIRA_DRIFT_TOLERANCE_PPM 30
	const struct fira_session_params *params = &session->params;
	int n_unsync_blocks;
	s64 unsync_duration_dtu;
	int drift_ppm, rx_margin_ppm;

	if (session->controlee.synchronised) {
		n_unsync_blocks = session->block_index -
				  session->controlee.block_index_sync;
		unsync_duration_dtu =
			n_unsync_blocks * params->block_duration_dtu;
		drift_ppm = div64_s64(unsync_duration_dtu *
					      FIRA_DRIFT_TOLERANCE_PPM,
				      1000000);
		rx_margin_ppm = get_rx_margin_duration_dtu(local, session);

		trace_region_fira_is_controlee_synchronised(session, drift_ppm,
							    rx_margin_ppm);
		if (drift_ppm <= rx_margin_ppm)
			return true;
	}
	return false;
}

/**
 * is_stopped() - Is the session stopped?
 * @session: Session context.
 *
 * Return: True when the session is stopped, false otherwise.
 */
static bool is_stopped(struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;
	int nb_controlee = fira_session_controlees_running_count(session);

	if (params->max_rr_retry &&
	    session->n_ranging_round_retry >= params->max_rr_retry)
		session->stop_no_response = true;

	return (session->stop_request && !nb_controlee) ||
	       session->stop_inband || session->stop_no_response;
}

/**
 * forward_to_next_ranging() - Update the session to forward to next ranging.
 * @session: Session context.
 * @n_ranging: Number of ranging (forward).
 */
static void forward_to_next_ranging(struct fira_session *session, int n_ranging)
{
	const struct fira_session_params *params = &session->params;
	int blocks_per_ranging = session->block_stride_len + 1;
	int add_blocks = n_ranging * blocks_per_ranging;
	int duration_dtu = add_blocks * params->block_duration_dtu;

	session->block_index += add_blocks;
	session->block_start_dtu += duration_dtu;
	session->n_ranging_round_retry += n_ranging;
}

/**
 * ranging_round_done() - Update controlee and notify the upper layer.
 * @local: FiRa context.
 * @session: Session context.
 * @report_info: Report information to forward fira_session_report.
 */
static void ranging_round_done(struct fira_local *local,
			       struct fira_session *session,
			       struct fira_report_info *report_info)
{
	const struct fira_session_params *params = &session->params;

	session->next_access_timestamp_dtu =
		get_next_access_timestamp_dtu(local, session);
	report_info->stopped = is_stopped(session);

	switch (params->device_type) {
	default:
	case FIRA_DEVICE_TYPE_CONTROLLER:
		/* Update controlee's states between two ranging round. */
		fira_session_update_controlees(local, session);
		fira_sts_rotate_keys(session);
		break;
	case FIRA_DEVICE_TYPE_CONTROLEE:
		/* Did the controlee's access lose the synchronisation? */
		session->controlee.synchronised =
			is_controlee_synchronised(local, session);
		if (session->controlee.synchronised)
			fira_sts_rotate_keys(session);
		break;
	}

	fira_session_report(local, session, report_info);

	if (report_info->stopped) {
		fira_session_fsm_change_state(local, session,
					      &fira_session_fsm_idle);
	} else {
		forward_to_next_ranging(session, 1);
	}
}

static void fira_session_fsm_active_enter(struct fira_local *local,
					  struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;

	session->stop_request = false;
	session->stop_inband = false;
	session->stop_no_response = false;
	session->measurements.n_total_achieved = 0;
	session->block_stride_len = params->block_stride_len;
	session->controlee.synchronised = false;
	session->controlee.hopping_mode = false;
	session->controlee.next_round_index_valid = false;
	session->controlee.block_index_sync = 0;
	session->round_index = 0;
	/*
	 * Initialize to 1 when initiation_time_ms is 0,
	 * because first add_blocks built will be 0.
	 */
	session->n_ranging_round_retry = params->initiation_time_ms ? 0 : 1;

	list_move_to_active(local, session);
}

static void fira_session_fsm_active_leave(struct fira_local *local,
					  struct fira_session *session)
{
	fira_sts_deinit(session);
	list_move(&session->entry, &local->inactive_sessions);
	fira_session_restart_controlees(session);
}

static int
fira_session_fsm_active_check_parameters(const struct fira_session *session,
					 struct nlattr **attrs)
{
	const struct fira_session_params *params = &session->params;
	enum fira_session_param_attrs i;

	for (i = FIRA_SESSION_PARAM_ATTR_UNSPEC + 1;
	     i <= FIRA_SESSION_PARAM_ATTR_MAX; i++) {
		const struct nlattr *attr = attrs[i];

		if (!attr)
			/* Attribute not provided. */
			continue;

		switch (i) {
		case FIRA_SESSION_PARAM_ATTR_MEASUREMENT_SEQUENCE:
		case FIRA_SESSION_PARAM_ATTR_DATA_PAYLOAD:
		case FIRA_SESSION_PARAM_ATTR_RANGE_DATA_NTF_CONFIG:
		case FIRA_SESSION_PARAM_ATTR_RANGE_DATA_NTF_PROXIMITY_NEAR:
		case FIRA_SESSION_PARAM_ATTR_RANGE_DATA_NTF_PROXIMITY_FAR:
			/* Allowed for all device type. */
			break;
		case FIRA_SESSION_PARAM_ATTR_BLOCK_STRIDE_LENGTH:
			/* Allowed only for controller. */
			if (params->device_type == FIRA_DEVICE_TYPE_CONTROLLER)
				continue;
			return -EBUSY;
		default:
			return -EBUSY;
		}
	}
	return 0;
}

static void
fira_session_fsm_active_parameters_updated(struct fira_local *local,
					   struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;
	int i;

	if (session->measurements.reset) {
		for (i = 0; i < params->meas_seq.n_steps; i++) {
			const struct fira_measurement_sequence_step *step;

			step = &params->meas_seq.steps[i];
			trace_region_fira_session_meas_seq_params(session, step,
								  i);
		}
	}
}

static int fira_session_fsm_active_start(struct fira_local *local,
					 struct fira_session *session,
					 const struct genl_info *info)
{
	/* Already started. */
	return 0;
}

static int fira_session_fsm_active_stop(struct fira_local *local,
					struct fira_session *session)
{
	const struct fira_session_params *params = &session->params;
	struct fira_report_info report_info = {
		.stopped = true,
	};

	switch (params->device_type) {
	default:
	case FIRA_DEVICE_TYPE_CONTROLLER:
		if (local->current_session == NULL) {
			session->stop_request = true;
			/*
			 * FIXME/BUG:
			 * In unit test, the stop_tx_frame_error (or rx),
			 * stop the current access and trig a broken event.
			 * Then the TearDown request a session_stop, but
			 * there is still more than one controlee running.
			 *
			 * Normally the controller must do an access to
			 * announce a stop of all controlees.
			 * But here, there is a missing mechanism, as:
			 *  - notify_stop is not called,
			 *  - error is only a boolean in access_done.
			 *    And the error boolean is True on -ETIME.
			 *
			 * And as the current_session equal to NULL is a
			 * normal behavior in multi-region. We have a bug.
			 */
			fira_session_report(local, session, &report_info);
			fira_session_fsm_change_state(local, session,
						      &fira_session_fsm_idle);
		} else if (session->n_current_controlees) {
			/*
			 * A ranging round to announced all controlee
			 * stopped is required.
			 */
			fira_session_stop_controlees(session);
			session->stop_request = true;
		} else if (local->current_session != session) {
			session->stop_request = true;
			fira_session_report(local, session, &report_info);
			fira_session_fsm_change_state(local, session,
						      &fira_session_fsm_idle);
		}
		break;
	case FIRA_DEVICE_TYPE_CONTROLEE:
		session->stop_request = true;
		if (local->current_session != session) {
			fira_session_report(local, session, &report_info);
			fira_session_fsm_change_state(local, session,
						      &fira_session_fsm_idle);
		}
		break;
	}
	mcps802154_reschedule(local->llhw);
	return 0;
}

static int
fira_session_fsm_active_get_demand(const struct fira_local *local,
				   const struct fira_session *session,
				   u32 next_timestamp_dtu, int max_duration_dtu,
				   struct fira_session_demand *session_demand)
{
	const struct fira_session_params *params = &session->params;
	int round_duration_dtu =
		params->round_duration_slots * params->slot_duration_dtu;
	u32 block_start_dtu;
	u32 timestamp_dtu;
	u32 duration_dtu;
	int round_index = 0;
	u32 block_index;
	int add_blocks = 0;
	int rx_timeout_dtu = 0;
	int slot_count;

	/* First, determine two dates: block_start_dtu and timestamp_dtu. */
	if (!is_before_dtu(session->next_access_timestamp_dtu,
			   next_timestamp_dtu)) {
		/*
		 * block_start_dtu is set in the future or present.
		 * It's happen mainly when initiation_time_ms is not zero.
		 */
		timestamp_dtu = block_start_dtu = session->block_start_dtu;
	} else {
		/*
		 * block start is in the past, we have to evaluate the
		 * new block start dtu.
		 * It's could be the same with a controlee not synchronized.
		 *
		 * Example of time graph of what's could happen:
		 *
		 * -------x----------------x----------------x-------
		 * #x - 1 | Block Index #x |    #x + 1      | #x + 2
		 * -------x----------------x------x---------x-------> Time
		 *        |<--------------------->|
		 *     Block         |            |
		 *     start         |            next_timestamp_dtu
		 *                   |
		 * duration_from_block_start_dtu
		 *
		 * In the graph example, one block is missed, but it's could be
		 * more or less(controlee).
		 */
		int duration_from_block_start_dtu =
			next_timestamp_dtu - session->block_start_dtu;

		if (params->device_type == FIRA_DEVICE_TYPE_CONTROLEE &&
		    !session->controlee.synchronised) {
			/*
			 * With a controlee not synchronized, consider the
			 * block as missed when there is no more left duration
			 * in the current block.
			 *
			 *      block
			 *      start       next_timestamp_dtu
			 *        |                 |
			 * -------x-----------------x---x------
			 * #x - 1 |       #x        :   | #x + 1
			 * -------x-----------------x---x-----> Time
			 *        |                 |
			 *        |<--------------->|
			 *                  |
			 *                  |
			 *   add_blocks = Time / block_duration
			 */
			add_blocks = duration_from_block_start_dtu /
				     params->block_duration_dtu;
		} else {
			int blocks_per_ranging = session->block_stride_len + 1;

			/*
			 * With a controller or a controlee synchronized,
			 * consider a block started as a missed block.
			 */
			add_blocks = (duration_from_block_start_dtu +
				      params->block_duration_dtu - 1) /
				     params->block_duration_dtu;
			/*
			 * Block stride feature announced/received in last
			 * access.
			 */
			if (session->block_stride_len) {
				int n = add_blocks % blocks_per_ranging;

				/*
				 * Add more block(s) to reach block stride
				 * modulo.
				 */
				if (n)
					add_blocks += blocks_per_ranging - n;
			}
		}

		/* Compute block start dtu. 'add_blocks' can be zero. */
		block_start_dtu = session->block_start_dtu +
				  add_blocks * params->block_duration_dtu;
		/* Determine the access timestamp. */
		if (is_before_dtu(block_start_dtu, next_timestamp_dtu))
			/*
			 * Only the controlee not synchronized can have its
			 * next access timestamp_dtu in the future of the
			 * block start.
			 *
			 * block_start_dtu
			 *        |
			 * -------x-----------------x----------
			 * #x - 1 | Block index #x  | #x + 1
			 * -------x------x----------x----------> Time
			 *               |
			 *      next_timestamp_dtu
			 */
			timestamp_dtu = next_timestamp_dtu;
		else
			timestamp_dtu = block_start_dtu;
	}

	/*
	 * As block_start_dtu is updated with new timestamp in the future,
	 * or still in the past (controlee), then other variables will be
	 * build to fill the session_demand output.
	 *
	 * In other words, locale variables can have a new values which
	 * represent the next(future) block/access/index/...
	 * Or keep +/- the same values.
	 */
	block_index = session->block_index + add_blocks;
	switch (params->device_type) {
	default:
	case FIRA_DEVICE_TYPE_CONTROLLER:
		slot_count = fira_session_get_slot_count(session);
		round_index = get_round_index(session, block_index);
		timestamp_dtu =
			block_start_dtu + round_index * round_duration_dtu;
		duration_dtu = slot_count * params->slot_duration_dtu;
		if (max_duration_dtu &&
		    is_before_dtu(next_timestamp_dtu + max_duration_dtu,
				  timestamp_dtu + duration_dtu))
			/* No way to start an access. */
			return 0;
		break;
	case FIRA_DEVICE_TYPE_CONTROLEE:
		if (session->controlee.synchronised) {
			int margin_less, margin_more;

			/*
			 * Time graph to illustrate the controlee access
			 * and its synchronization.
			 *
			 *    Next          Timestamp
			 *  timestamp     without margin
			 *      |             |
			 *  ----x--------x----x----x-----> Time
			 *               |<---|--->|
			 *      Rx enabled         Rx timeout
			 *    @timestamp_dtu
			 *
			 * rx_margin is the maximum margin accepted.
			 */
			round_index = get_round_index(session, block_index);
			timestamp_dtu += round_index * round_duration_dtu;
			margin_less = margin_more =
				get_rx_margin_duration_dtu(local, session);
			if (timestamp_dtu - next_timestamp_dtu < margin_less)
				/*
				 * Avoid to build a timestamp_dtu which is in
				 * the past of next_timestamp_dtu.
				 */
				margin_less =
					timestamp_dtu - next_timestamp_dtu;
			timestamp_dtu -= margin_less;
			rx_timeout_dtu = margin_less + margin_more;
			duration_dtu = round_duration_dtu + margin_less;
			if (max_duration_dtu &&
			    is_before_dtu(next_timestamp_dtu + max_duration_dtu,
					  timestamp_dtu + duration_dtu))
				/* No way to start an access. */
				return 0;
		} else {
			int unsync_max_duration_dtu =
				params->block_duration_dtu +
				params->slot_duration_dtu;

			/*
			 * A controlee not synchronized is allowed to start/end
			 * anywhere in the block to find the controller.
			 * But the session continue to work with block duration
			 * to provide:
			 *  - Regular reporting.
			 *  - Time-sharing in multi-session/multi-region.
			 *
			 * Time graph:
			 *
			 *           unsync_max_duration_dtu
			 *       |<----------------------------->|
			 *       |                               |
			 * --+---x-----------------------|-------x------>
			 *   |        Block #x           |  Block #x + 1
			 * --+---x-----------------------|---x---x------> Time
			 *       |<------------------------->|<->|
			 *             block duration         slot duration
			 *
			 * The unsync duration is bigger than the block, to
			 * listen the medium for one block min. But to avoid
			 * to be in late on the next access, we must add one
			 * slot.
			 */
			if (max_duration_dtu &&
			    is_before_dtu(next_timestamp_dtu + max_duration_dtu,
					  timestamp_dtu +
						  params->slot_duration_dtu))
				/* No way to start an access. */
				return 0;
			else if (!max_duration_dtu ||
				 is_before_dtu(timestamp_dtu +
						       unsync_max_duration_dtu,
					       next_timestamp_dtu +
						       max_duration_dtu))
				/* Maximum access granted. */
				duration_dtu = unsync_max_duration_dtu;
			else
				/* Adjusted access duration. */
				duration_dtu = next_timestamp_dtu +
					       max_duration_dtu - timestamp_dtu;

			/*
			 * 'rx_timeout_dtu' is set to allow the reception
			 * of the control frame close to the end of the
			 * access, and so be synchronized for next block.
			 *
			 * But if the control message is received
			 * at the end of access, the other frames
			 * will be dropped to respect the duration_dtu.
			 * See: rx control frame.
			 */
			rx_timeout_dtu =
				duration_dtu - params->slot_duration_dtu;
		}
		break;
	}

	/*
	 * Update the session demand (output):
	 * - rx_timeout_dtu: Used only by the controlee.
	 *
	 * On the get_access, the session_demand will be applied
	 * to the session. Otherwise the session_demand is dropped.
	 *
	 * In a way, session_demand represent the next access.
	 */
	*session_demand = (struct fira_session_demand){
		.block_start_dtu = block_start_dtu,
		.timestamp_dtu = timestamp_dtu,
		.max_duration_dtu = duration_dtu,
		.add_blocks = add_blocks,
		.rx_timeout_dtu = rx_timeout_dtu,
		.round_index = round_index,
	};
	trace_region_fira_session_fsm_active_get_demand_return(local, session,
							       session_demand);
	return 1;
}

static struct mcps802154_access *
fira_session_fsm_active_get_access(struct fira_local *local,
				   struct fira_session *session,
				   const struct fira_session_demand *fsd)
{
	const struct fira_session_params *params = &session->params;
	const struct mcps802154_hrp_uwb_params *hrp = &session->hrp_uwb_params;
	struct mcps802154_access *access = &local->access;
	int blocks_per_ranging;

	/*
	 *      ,     ,
	 *     (\____/)              Important:
	 *      (_oo_)
	 *        (O)        It's almost forbidden to update session
	 *      __||__    \) content for a controlee.
	 *   []/______\[] /
	 *   / \______/ \/   Because, the session can change on control
	 *  /    /__\        frame reception (static STS only).
	 * (\   /____\
	 */
	local->current_session = session;

	/*
	 * Update common access fields for controlee and controller.
	 * hrp must stay const, see 'Important' above.
	 */
	access->method = MCPS802154_ACCESS_METHOD_MULTI;
	access->frames = local->frames;
	access->n_frames = 0;
	access->channel = get_channel(local, session);
	access->hrp_uwb_params = hrp;

	/*
	 * For the ranging round failure counter, consider these rounds as
	 * failed. And reset the counter in the access_done if success.
	 */
	blocks_per_ranging = session->block_stride_len + 1;
	session->n_ranging_round_retry += fsd->add_blocks / blocks_per_ranging;

	/* Continue to 'device type' access. */
	if (params->device_type == FIRA_DEVICE_TYPE_CONTROLLER)
		return fira_get_access_controller(local, fsd);
	return fira_get_access_controlee(local, fsd);
}

static void fira_session_fsm_active_access_done(struct fira_local *local,
						struct fira_session *session,
						bool error)
{
	const struct fira_session_params *params = &session->params;
	const struct fira_measurement_sequence_step *step;
	struct fira_report_info report_info = {
		.ranging_data = local->ranging_info,
		.n_ranging_data = local->n_ranging_info,
		.stopped_controlees = local->stopped_controlees,
		.n_stopped_controlees = local->n_stopped_controlees,
		.diagnostics = local->diagnostics,
		.slots = local->slots,
		.n_slots = local->access.n_frames,
	};
	struct fira_ranging_info *ri;
	int i;

	/* Update local. */
	local->current_session = NULL;

	if (error) {
		/*
		 * FIXME:
		 * Why corrupt all status, the last slot_index is not
		 * enough?
		 * TODO: Proposal:
		 *  - Set INTERNAL_ERROR on status during the get_access.
		 *  - Update status on tx_return/rx_frame.
		 *  - Update testu which expect the wrong status.
		 */
		for (i = 0; i < local->n_ranging_info; i++) {
			ri = &local->ranging_info[i];
			ri->status = FIRA_STATUS_RANGING_INTERNAL_ERROR;
		}
	} else {
		for (i = 0; i < local->n_ranging_info; i++) {
			ri = &local->ranging_info[i];
			if (ri->status != FIRA_STATUS_RANGING_SUCCESS)
				break;
		}
		/* Reset ranging round failure counter. */
		if (i == local->n_ranging_info)
			session->n_ranging_round_retry = 0;
	}

	session->measurements.n_achieved++;
	session->measurements.n_total_achieved++;
	step = fira_session_get_meas_seq_step(session);
	if (session->measurements.reset) {
		/* Copy new measurement sequence. */
		session->measurements.sequence = params->meas_seq;
		session->measurements.index = 0;
		session->measurements.n_achieved = 0;
		session->measurements.reset = false;
	} else if (session->measurements.n_achieved >= step->n_measurements) {
		struct fira_measurement_sequence *seq =
			&session->measurements.sequence;

		session->measurements.n_achieved = 0;
		session->measurements.index++;
		session->measurements.index %= seq->n_steps;
	}
	/* Check max number of measurements. */
	if (params->max_number_of_measurements &&
	    session->measurements.n_total_achieved >=
		    params->max_number_of_measurements) {
		session->stop_request = true;
	}

	ranging_round_done(local, session, &report_info);
}

static void
fira_session_fsm_active_check_missed_ranging(struct fira_local *local,
					     struct fira_session *session,
					     u32 timestamp_dtu)
{
	const struct fira_session_params *params = &session->params;
	int next_block_start_dtu =
		session->block_start_dtu + params->block_duration_dtu;
	bool is_missed_ranging_round = false;

	/*
	 * Example of possible timings (without hopping):
	 *
	 *                          check(timestamp_dtu)
	 *          Ok        Miss      Miss  |
	 * Session: [--]      [--]      [--]  |   [--]
	 *    ------x---------x---------------x--------> Time
	 *          |         |
	 * block_start_dtu    next_access_timestamp_dtu
	 *
	 * Tips:
	 * - 'session->block_start_dtu' is the block start of the last access.
	 * - 'session->next_access_timestamp_dtu' value can be:
	 *   - Next block start when hopping is disabled.
	 *   - Beyond the next block start when hopping is enabled.
	 * - When the session haven't been check since a long time,
	 *   many blocks could be missed.
	 */

	/* First, determine if there is missed ranging round. */
	if (params->device_type == FIRA_DEVICE_TYPE_CONTROLEE &&
	    !session->controlee.synchronised) {
		/* Consider the block as missed when next block is reached. */
		if (!is_before_dtu(timestamp_dtu, next_block_start_dtu))
			is_missed_ranging_round = true;
	} else if (is_before_dtu(session->next_access_timestamp_dtu,
				 timestamp_dtu)) {
		/* A late is not accepted here. */
		is_missed_ranging_round = true;
	}

	/* Compute the number of missed ranging. */
	if (is_missed_ranging_round) {
		int blocks_per_ranging = session->block_stride_len + 1;
		int add_blocks = 0;

		/* Drift probably due to multi-session or multi-region. */
		if (is_before_dtu(next_block_start_dtu, timestamp_dtu))
			add_blocks = (timestamp_dtu - next_block_start_dtu) /
				     params->block_duration_dtu;
		if (add_blocks >= blocks_per_ranging) {
			int n_ranging_failed = add_blocks / blocks_per_ranging;

			if (params->max_rr_retry &&
			    session->n_ranging_round_retry + n_ranging_failed >
				    params->max_rr_retry) {
				/*
				 * Avoid to set a block index bigger than the
				 * max ranging round retry in the report.
				 */
				n_ranging_failed =
					params->max_rr_retry -
					session->n_ranging_round_retry;
			}
			forward_to_next_ranging(session, n_ranging_failed);
		}
	}

	/* Finally, do the missed ranging round report. */
	if (is_missed_ranging_round) {
		struct fira_report_info report_info = {};
		__le16 *pend_del;
		struct fira_ranging_info *ri;
		int j, k;
		struct fira_controlee *controlee;

		/*
		 *           \\\||||||////
		 *            \\  ~ ~  //
		 *             (  @ @  )
		 * _________ oOOo-(_)-oOOo________________________________
		 * WARN_RETURN_VOID_ON: Because the 'local' information will
		 * be used until the end of this bloc.
		 * So this function must not be called during an access,
		 * to avoid to use a shared memory already used by current
		 * session.
		 * ________________Oooo.__________________________________
		 *       .oooO     (   )
		 *        (   )     ) /
		 *         \ (     (_/
		 *          \_)
		 */
		WARN_RETURN_VOID_ON(local->current_session);
		/* Build a missed ranging round report. */
		report_info.ranging_data = local->ranging_info;
		switch (params->device_type) {
		default:
		case FIRA_DEVICE_TYPE_CONTROLLER:
			pend_del = local->stopped_controlees;
			j = k = 0;
			list_for_each_entry (controlee,
					     &session->current_controlees,
					     entry) {
				switch (controlee->state) {
				case FIRA_CONTROLEE_STATE_RUNNING:
				case FIRA_CONTROLEE_STATE_PENDING_STOP:
				case FIRA_CONTROLEE_STATE_PENDING_DEL:
					ri = &local->ranging_info[j];
					*ri = (struct fira_ranging_info){
						.short_addr =
							controlee->short_addr,
						.status =
							FIRA_STATUS_RANGING_TX_FAILED,
					};
					j++;
					break;
				default:
					pend_del[k++] = controlee->short_addr;
					break;
				}
			}
			report_info.stopped_controlees = pend_del;
			report_info.n_stopped_controlees = k,
			report_info.n_ranging_data = j;
			break;
		case FIRA_DEVICE_TYPE_CONTROLEE:
			ri = &local->ranging_info[0];
			*ri = (struct fira_ranging_info){
				.short_addr = params->controller_short_addr,
				.status = FIRA_STATUS_RANGING_RX_TIMEOUT,
			};
			report_info.n_ranging_data = 1;
			break;
		}
		ranging_round_done(local, session, &report_info);
	}
}

const struct fira_session_fsm_state fira_session_fsm_active = {
	.id = FIRA_SESSION_STATE_ID_ACTIVE,
	.enter = fira_session_fsm_active_enter,
	.leave = fira_session_fsm_active_leave,
	.check_parameters = fira_session_fsm_active_check_parameters,
	.parameters_updated = fira_session_fsm_active_parameters_updated,
	.start = fira_session_fsm_active_start,
	.stop = fira_session_fsm_active_stop,
	.get_demand = fira_session_fsm_active_get_demand,
	.get_access = fira_session_fsm_active_get_access,
	.access_done = fira_session_fsm_active_access_done,
	.check_missed_ranging = fira_session_fsm_active_check_missed_ranging,
};