summaryrefslogtreecommitdiff
path: root/drivers/event/dsw/dsw_event.c
blob: 33f741990f5bc45cf5494d7106423a34b752d6cf (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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
/* SPDX-License-Identifier: BSD-3-Clause
 * Copyright(c) 2018 Ericsson AB
 */

#include "dsw_evdev.h"

#ifdef DSW_SORT_DEQUEUED
#include "dsw_sort.h"
#endif

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include <rte_cycles.h>
#include <rte_memcpy.h>
#include <rte_random.h>

static bool
dsw_port_acquire_credits(struct dsw_evdev *dsw, struct dsw_port *port,
			 int32_t credits)
{
	int32_t inflight_credits = port->inflight_credits;
	int32_t missing_credits = credits - inflight_credits;
	int32_t total_on_loan;
	int32_t available;
	int32_t acquired_credits;
	int32_t new_total_on_loan;

	if (likely(missing_credits <= 0)) {
		port->inflight_credits -= credits;
		return true;
	}

	total_on_loan =
		rte_atomic_load_explicit(&dsw->credits_on_loan,
					 rte_memory_order_relaxed);
	available = dsw->max_inflight - total_on_loan;
	acquired_credits = RTE_MAX(missing_credits, DSW_PORT_MIN_CREDITS);

	if (available < acquired_credits)
		return false;

	/* This is a race, no locks are involved, and thus some other
	 * thread can allocate tokens in between the check and the
	 * allocation.
	 */
	new_total_on_loan =
	    rte_atomic_fetch_add_explicit(&dsw->credits_on_loan,
					  acquired_credits,
					  rte_memory_order_relaxed) +
					  acquired_credits;

	if (unlikely(new_total_on_loan > dsw->max_inflight)) {
		/* Some other port took the last credits */
		rte_atomic_fetch_sub_explicit(&dsw->credits_on_loan,
					      acquired_credits,
					      rte_memory_order_relaxed);
		return false;
	}

	DSW_LOG_DP_PORT(DEBUG, port->id, "Acquired %d tokens from pool.\n",
			acquired_credits);

	port->inflight_credits += acquired_credits;
	port->inflight_credits -= credits;

	return true;
}

static void
dsw_port_return_credits(struct dsw_evdev *dsw, struct dsw_port *port,
			int32_t credits)
{
	port->inflight_credits += credits;

	if (unlikely(port->inflight_credits > DSW_PORT_MAX_CREDITS)) {
		int32_t leave_credits = DSW_PORT_MIN_CREDITS;
		int32_t return_credits =
			port->inflight_credits - leave_credits;

		port->inflight_credits = leave_credits;

		rte_atomic_fetch_sub_explicit(&dsw->credits_on_loan,
					      return_credits,
					      rte_memory_order_relaxed);

		DSW_LOG_DP_PORT(DEBUG, port->id,
				"Returned %d tokens to pool.\n",
				return_credits);
	}
}

static void
dsw_port_enqueue_stats(struct dsw_port *port, uint16_t num_new,
		       uint16_t num_forward, uint16_t num_release)
{
	port->new_enqueued += num_new;
	port->forward_enqueued += num_forward;
	port->release_enqueued += num_release;
}

static void
dsw_port_queue_enqueue_stats(struct dsw_port *source_port, uint8_t queue_id)
{
	source_port->queue_enqueued[queue_id]++;
}

static void
dsw_port_dequeue_stats(struct dsw_port *port, uint16_t num)
{
	port->dequeued += num;
}

static void
dsw_port_queue_dequeued_stats(struct dsw_port *source_port, uint8_t queue_id)
{
	source_port->queue_dequeued[queue_id]++;
}

static void
dsw_port_load_record(struct dsw_port *port, unsigned int dequeued)
{
	if (dequeued > 0 && port->busy_start == 0)
		/* work period begins */
		port->busy_start = rte_get_timer_cycles();
	else if (dequeued == 0 && port->busy_start > 0) {
		/* work period ends */
		uint64_t work_period =
			rte_get_timer_cycles() - port->busy_start;
		port->busy_cycles += work_period;
		port->busy_start = 0;
	}
}

static int16_t
dsw_port_load_close_period(struct dsw_port *port, uint64_t now)
{
	uint64_t passed = now - port->measurement_start;
	uint64_t busy_cycles = port->busy_cycles;

	if (port->busy_start > 0) {
		busy_cycles += (now - port->busy_start);
		port->busy_start = now;
	}

	int16_t load = (DSW_MAX_LOAD * busy_cycles) / passed;

	port->measurement_start = now;
	port->busy_cycles = 0;

	port->total_busy_cycles += busy_cycles;

	return load;
}

static void
dsw_port_load_update(struct dsw_port *port, uint64_t now)
{
	int16_t old_load;
	int16_t period_load;
	int16_t new_load;

	old_load = rte_atomic_load_explicit(&port->load,
					    rte_memory_order_relaxed);

	period_load = dsw_port_load_close_period(port, now);

	new_load = (period_load + old_load*DSW_OLD_LOAD_WEIGHT) /
		(DSW_OLD_LOAD_WEIGHT+1);

	rte_atomic_store_explicit(&port->load, new_load,
				  rte_memory_order_relaxed);

	/* The load of the recently immigrated flows should hopefully
	 * be reflected the load estimate by now.
	 */
	rte_atomic_store_explicit(&port->immigration_load, 0,
				  rte_memory_order_relaxed);
}

static void
dsw_port_consider_load_update(struct dsw_port *port, uint64_t now)
{
	if (now < port->next_load_update)
		return;

	port->next_load_update = now + port->load_update_interval;

	dsw_port_load_update(port, now);
}

static void
dsw_port_ctl_enqueue(struct dsw_port *port, struct dsw_ctl_msg *msg)
{
	/* there's always room on the ring */
	while (rte_ring_enqueue_elem(port->ctl_in_ring, msg, sizeof(*msg)) != 0)
		rte_pause();
}

static int
dsw_port_ctl_dequeue(struct dsw_port *port, struct dsw_ctl_msg *msg)
{
	return rte_ring_dequeue_elem(port->ctl_in_ring, msg, sizeof(*msg));
}

static void
dsw_port_ctl_broadcast(struct dsw_evdev *dsw, struct dsw_port *source_port,
		       uint8_t type, struct dsw_queue_flow *qfs,
		       uint8_t qfs_len)
{
	uint16_t port_id;
	struct dsw_ctl_msg msg = {
		.type = type,
		.originating_port_id = source_port->id,
		.qfs_len = qfs_len
	};

	memcpy(msg.qfs, qfs, sizeof(struct dsw_queue_flow) * qfs_len);

	for (port_id = 0; port_id < dsw->num_ports; port_id++)
		if (port_id != source_port->id)
			dsw_port_ctl_enqueue(&dsw->ports[port_id], &msg);
}

static __rte_always_inline bool
dsw_is_queue_flow_in_ary(const struct dsw_queue_flow *qfs, uint16_t qfs_len,
			 uint8_t queue_id, uint16_t flow_hash)
{
	uint16_t i;

	for (i = 0; i < qfs_len; i++)
		if (qfs[i].queue_id == queue_id &&
		    qfs[i].flow_hash == flow_hash)
			return true;

	return false;
}

static __rte_always_inline bool
dsw_port_is_flow_paused(struct dsw_port *port, uint8_t queue_id,
			uint16_t flow_hash)
{
	return dsw_is_queue_flow_in_ary(port->paused_flows,
					port->paused_flows_len,
					queue_id, flow_hash);
}

static __rte_always_inline bool
dsw_port_is_flow_migrating(struct dsw_port *port, uint8_t queue_id,
			   uint16_t flow_hash)
{
	return dsw_is_queue_flow_in_ary(port->emigration_target_qfs,
					port->emigration_targets_len,
					queue_id, flow_hash);
}

static void
dsw_port_add_paused_flows(struct dsw_port *port, struct dsw_queue_flow *qfs,
			  uint8_t qfs_len)
{
	uint8_t i;

	for (i = 0; i < qfs_len; i++) {
		struct dsw_queue_flow *qf = &qfs[i];

		DSW_LOG_DP_PORT(DEBUG, port->id,
				"Pausing queue_id %d flow_hash %d.\n",
				qf->queue_id, qf->flow_hash);

		port->paused_flows[port->paused_flows_len] = *qf;
		port->paused_flows_len++;
	};
}

static void
dsw_port_remove_paused_flow(struct dsw_port *port,
			    const struct dsw_queue_flow *target_qf)
{
	uint16_t i;

	for (i = 0; i < port->paused_flows_len; i++) {
		struct dsw_queue_flow *qf = &port->paused_flows[i];

		if (qf->queue_id == target_qf->queue_id &&
		    qf->flow_hash == target_qf->flow_hash) {
			uint16_t last_idx = port->paused_flows_len-1;
			if (i != last_idx)
				port->paused_flows[i] =
					port->paused_flows[last_idx];
			port->paused_flows_len--;

			DSW_LOG_DP_PORT(DEBUG, port->id,
					"Unpausing queue_id %d flow_hash %d.\n",
					target_qf->queue_id,
					target_qf->flow_hash);

			return;
		}
	}

	DSW_LOG_DP_PORT(ERR, port->id,
			"Failed to unpause queue_id %d flow_hash %d.\n",
			target_qf->queue_id, target_qf->flow_hash);
	RTE_VERIFY(0);
}

static void
dsw_port_remove_paused_flows(struct dsw_port *port,
			     struct dsw_queue_flow *qfs, uint8_t qfs_len)
{
	uint8_t i;

	for (i = 0; i < qfs_len; i++)
		dsw_port_remove_paused_flow(port, &qfs[i]);
}

static void
dsw_port_flush_out_buffers(struct dsw_evdev *dsw, struct dsw_port *source_port);

static void
dsw_port_handle_pause_flows(struct dsw_evdev *dsw, struct dsw_port *port,
			    uint8_t originating_port_id,
			    struct dsw_queue_flow *paused_qfs,
			    uint8_t qfs_len)
{
	struct dsw_ctl_msg cfm = {
		.type = DSW_CTL_CFM,
		.originating_port_id = port->id
	};

	/* There might be already-scheduled events belonging to the
	 * paused flow in the output buffers.
	 */
	dsw_port_flush_out_buffers(dsw, port);

	dsw_port_add_paused_flows(port, paused_qfs, qfs_len);

	/* Make sure any stores to the original port's in_ring is seen
	 * before the ctl message.
	 */
	rte_smp_wmb();

	dsw_port_ctl_enqueue(&dsw->ports[originating_port_id], &cfm);
}

struct dsw_queue_flow_burst {
	struct dsw_queue_flow queue_flow;
	uint16_t count;
};

#define DSW_QF_TO_INT(_qf)					\
	((int)((((_qf)->queue_id)<<16)|((_qf)->flow_hash)))

static inline int
dsw_cmp_qf(const void *v_qf_a, const void *v_qf_b)
{
	const struct dsw_queue_flow *qf_a = v_qf_a;
	const struct dsw_queue_flow *qf_b = v_qf_b;

	return DSW_QF_TO_INT(qf_a) - DSW_QF_TO_INT(qf_b);
}

static uint16_t
dsw_sort_qfs_to_bursts(struct dsw_queue_flow *qfs, uint16_t qfs_len,
		       struct dsw_queue_flow_burst *bursts)
{
	uint16_t i;
	struct dsw_queue_flow_burst *current_burst = NULL;
	uint16_t num_bursts = 0;

	/* We don't need the stable property, and the list is likely
	 * large enough for qsort() to outperform dsw_stable_sort(),
	 * so we use qsort() here.
	 */
	qsort(qfs, qfs_len, sizeof(qfs[0]), dsw_cmp_qf);

	/* arrange the (now-consecutive) events into bursts */
	for (i = 0; i < qfs_len; i++) {
		if (i == 0 ||
		    dsw_cmp_qf(&qfs[i], &current_burst->queue_flow) != 0) {
			current_burst = &bursts[num_bursts];
			current_burst->queue_flow = qfs[i];
			current_burst->count = 0;
			num_bursts++;
		}
		current_burst->count++;
	}

	return num_bursts;
}

static bool
dsw_retrieve_port_loads(struct dsw_evdev *dsw, int16_t *port_loads,
			int16_t load_limit)
{
	bool below_limit = false;
	uint16_t i;

	for (i = 0; i < dsw->num_ports; i++) {
		int16_t measured_load =
			rte_atomic_load_explicit(&dsw->ports[i].load,
						 rte_memory_order_relaxed);
		int32_t immigration_load =
			rte_atomic_load_explicit(&dsw->ports[i].immigration_load,
					         rte_memory_order_relaxed);
		int32_t load = measured_load + immigration_load;

		load = RTE_MIN(load, DSW_MAX_LOAD);

		if (load < load_limit)
			below_limit = true;
		port_loads[i] = load;
	}
	return below_limit;
}

static int16_t
dsw_flow_load(uint16_t num_events, int16_t port_load)
{
	return ((int32_t)port_load * (int32_t)num_events) /
		DSW_MAX_EVENTS_RECORDED;
}

static int16_t
dsw_evaluate_migration(int16_t source_load, int16_t target_load,
		       int16_t flow_load)
{
	int32_t res_target_load;
	int32_t imbalance;

	if (target_load > DSW_MAX_TARGET_LOAD_FOR_MIGRATION)
		return -1;

	imbalance = source_load - target_load;

	if (imbalance < DSW_REBALANCE_THRESHOLD)
		return -1;

	res_target_load = target_load + flow_load;

	/* If the estimated load of the target port will be higher
	 * than the source port's load, it doesn't make sense to move
	 * the flow.
	 */
	if (res_target_load > source_load)
		return -1;

	/* The more idle the target will be, the better. This will
	 * make migration prefer moving smaller flows, and flows to
	 * lightly loaded ports.
	 */
	return DSW_MAX_LOAD - res_target_load;
}

static bool
dsw_is_serving_port(struct dsw_evdev *dsw, uint8_t port_id, uint8_t queue_id)
{
	struct dsw_queue *queue = &dsw->queues[queue_id];
	uint64_t port_mask = UINT64_C(1) << port_id;

	return queue->serving_ports & port_mask;
}

static bool
dsw_select_emigration_target(struct dsw_evdev *dsw,
			     struct dsw_port *source_port,
			     struct dsw_queue_flow_burst *bursts,
			     uint16_t num_bursts,
			     int16_t *port_loads, uint16_t num_ports,
			     uint8_t *target_port_ids,
			     struct dsw_queue_flow *target_qfs,
			     uint8_t *targets_len)
{
	int16_t source_port_load = port_loads[source_port->id];
	struct dsw_queue_flow *candidate_qf = NULL;
	uint8_t candidate_port_id = 0;
	int16_t candidate_weight = -1;
	int16_t candidate_flow_load = -1;
	uint16_t i;

	if (source_port_load < DSW_MIN_SOURCE_LOAD_FOR_MIGRATION)
		return false;

	for (i = 0; i < num_bursts; i++) {
		struct dsw_queue_flow_burst *burst = &bursts[i];
		struct dsw_queue_flow *qf = &burst->queue_flow;
		int16_t flow_load;
		uint16_t port_id;

		if (dsw_is_queue_flow_in_ary(target_qfs, *targets_len,
					     qf->queue_id, qf->flow_hash))
			continue;

		flow_load = dsw_flow_load(burst->count, source_port_load);

		for (port_id = 0; port_id < num_ports; port_id++) {
			int16_t weight;

			if (port_id == source_port->id)
				continue;

			if (!dsw_is_serving_port(dsw, port_id, qf->queue_id))
				continue;

			weight = dsw_evaluate_migration(source_port_load,
							port_loads[port_id],
							flow_load);

			if (weight > candidate_weight) {
				candidate_qf = qf;
				candidate_port_id = port_id;
				candidate_weight = weight;
				candidate_flow_load = flow_load;
			}
		}
	}

	if (candidate_weight < 0)
		return false;

	DSW_LOG_DP_PORT(DEBUG, source_port->id, "Selected queue_id %d "
			"flow_hash %d (with flow load %d) for migration "
			"to port %d.\n", candidate_qf->queue_id,
			candidate_qf->flow_hash,
			DSW_LOAD_TO_PERCENT(candidate_flow_load),
			candidate_port_id);

	port_loads[candidate_port_id] += candidate_flow_load;
	port_loads[source_port->id] -= candidate_flow_load;

	target_port_ids[*targets_len] = candidate_port_id;
	target_qfs[*targets_len] = *candidate_qf;
	(*targets_len)++;

	rte_atomic_fetch_add_explicit(
				&dsw->ports[candidate_port_id].immigration_load,
				      candidate_flow_load,
				      rte_memory_order_relaxed);

	return true;
}

static void
dsw_select_emigration_targets(struct dsw_evdev *dsw,
			      struct dsw_port *source_port,
			      struct dsw_queue_flow_burst *bursts,
			      uint16_t num_bursts, int16_t *port_loads)
{
	struct dsw_queue_flow *target_qfs = source_port->emigration_target_qfs;
	uint8_t *target_port_ids = source_port->emigration_target_port_ids;
	uint8_t *targets_len = &source_port->emigration_targets_len;
	uint16_t i;

	for (i = 0; i < DSW_MAX_FLOWS_PER_MIGRATION; i++) {
		bool found;

		found = dsw_select_emigration_target(dsw, source_port,
						     bursts, num_bursts,
						     port_loads, dsw->num_ports,
						     target_port_ids,
						     target_qfs,
						     targets_len);
		if (!found)
			break;
	}

	if (*targets_len == 0)
		DSW_LOG_DP_PORT(DEBUG, source_port->id,
				"For the %d flows considered, no target port "
				"was found.\n", num_bursts);
}

static uint8_t
dsw_schedule(struct dsw_evdev *dsw, uint8_t queue_id, uint16_t flow_hash)
{
	struct dsw_queue *queue = &dsw->queues[queue_id];
	uint8_t port_id;

	if (queue->num_serving_ports > 1)
		port_id = queue->flow_to_port_map[flow_hash];
	else
		/* A single-link queue, or atomic/ordered/parallel but
		 * with just a single serving port.
		 */
		port_id = rte_bsf64(queue->serving_ports);

	DSW_LOG_DP(DEBUG, "Event with queue_id %d flow_hash %d is scheduled "
		   "to port %d.\n", queue_id, flow_hash, port_id);

	return port_id;
}

static void
dsw_port_transmit_buffered(struct dsw_evdev *dsw, struct dsw_port *source_port,
			   uint8_t dest_port_id)
{
	struct dsw_port *dest_port = &(dsw->ports[dest_port_id]);
	uint16_t *buffer_len = &source_port->out_buffer_len[dest_port_id];
	struct rte_event *buffer = source_port->out_buffer[dest_port_id];

	if (*buffer_len == 0)
		return;

	/* The rings are dimensioned to fit all in-flight events (even
	 * on a single ring).
	 */
	rte_event_ring_enqueue_bulk(dest_port->in_ring, buffer, *buffer_len,
				    NULL);

	(*buffer_len) = 0;
}

static uint16_t
dsw_port_get_parallel_flow_id(struct dsw_port *port)
{
	uint16_t flow_id = port->next_parallel_flow_id;

	port->next_parallel_flow_id =
		(port->next_parallel_flow_id + 1) % DSW_PARALLEL_FLOWS;

	return flow_id;
}

static void
dsw_port_buffer_paused(struct dsw_port *port,
		       const struct rte_event *paused_event)
{
	port->paused_events[port->paused_events_len] = *paused_event;
	port->paused_events_len++;
}


static void
dsw_port_buffer_non_paused(struct dsw_evdev *dsw, struct dsw_port *source_port,
			   uint8_t dest_port_id, const struct rte_event *event)
{
	struct rte_event *buffer = source_port->out_buffer[dest_port_id];
	uint16_t *buffer_len = &source_port->out_buffer_len[dest_port_id];

	if (*buffer_len == DSW_MAX_PORT_OUT_BUFFER)
		dsw_port_transmit_buffered(dsw, source_port, dest_port_id);

	buffer[*buffer_len] = *event;

	(*buffer_len)++;
}

#define DSW_FLOW_ID_BITS (24)
static uint16_t
dsw_flow_id_hash(uint32_t flow_id)
{
	uint16_t hash = 0;
	uint16_t offset = 0;

	do {
		hash ^= ((flow_id >> offset) & DSW_MAX_FLOWS_MASK);
		offset += DSW_MAX_FLOWS_BITS;
	} while (offset < DSW_FLOW_ID_BITS);

	return hash;
}

static void
dsw_port_buffer_parallel(struct dsw_evdev *dsw, struct dsw_port *source_port,
			 struct rte_event event)
{
	uint8_t dest_port_id;

	event.flow_id = dsw_port_get_parallel_flow_id(source_port);

	dest_port_id = dsw_schedule(dsw, event.queue_id,
				    dsw_flow_id_hash(event.flow_id));

	dsw_port_buffer_non_paused(dsw, source_port, dest_port_id, &event);
}

static void
dsw_port_buffer_event(struct dsw_evdev *dsw, struct dsw_port *source_port,
		      const struct rte_event *event)
{
	uint16_t flow_hash;
	uint8_t dest_port_id;

	if (unlikely(dsw->queues[event->queue_id].schedule_type ==
		     RTE_SCHED_TYPE_PARALLEL)) {
		dsw_port_buffer_parallel(dsw, source_port, *event);
		return;
	}

	flow_hash = dsw_flow_id_hash(event->flow_id);

	if (unlikely(dsw_port_is_flow_paused(source_port, event->queue_id,
					     flow_hash))) {
		dsw_port_buffer_paused(source_port, event);
		return;
	}

	dest_port_id = dsw_schedule(dsw, event->queue_id, flow_hash);

	dsw_port_buffer_non_paused(dsw, source_port, dest_port_id, event);
}

static void
dsw_port_flush_no_longer_paused_events(struct dsw_evdev *dsw,
				       struct dsw_port *source_port)
{
	uint16_t paused_events_len = source_port->paused_events_len;
	struct rte_event paused_events[paused_events_len];
	uint16_t i;

	if (paused_events_len == 0)
		return;

	rte_memcpy(paused_events, source_port->paused_events,
		   paused_events_len * sizeof(struct rte_event));

	source_port->paused_events_len = 0;

	for (i = 0; i < paused_events_len; i++) {
		struct rte_event *event = &paused_events[i];
		uint16_t flow_hash;

		flow_hash = dsw_flow_id_hash(event->flow_id);

		if (dsw_port_is_flow_paused(source_port, event->queue_id,
					    flow_hash))
			dsw_port_buffer_paused(source_port, event);
		else {
			uint8_t dest_port_id;

			dest_port_id = dsw_schedule(dsw, event->queue_id,
						    flow_hash);

			dsw_port_buffer_non_paused(dsw, source_port,
						   dest_port_id, event);
		}
	}
}

static void
dsw_port_emigration_stats(struct dsw_port *port, uint8_t finished)
{
	uint64_t flow_migration_latency;

	flow_migration_latency =
		(rte_get_timer_cycles() - port->emigration_start);
	port->emigration_latency += (flow_migration_latency * finished);
	port->emigrations += finished;
}

static void
dsw_port_end_emigration(struct dsw_evdev *dsw, struct dsw_port *port,
			uint8_t schedule_type)
{
	uint8_t i;
	struct dsw_queue_flow left_qfs[DSW_MAX_FLOWS_PER_MIGRATION];
	uint8_t left_port_ids[DSW_MAX_FLOWS_PER_MIGRATION];
	uint8_t left_qfs_len = 0;
	uint8_t finished;

	for (i = 0; i < port->emigration_targets_len; i++) {
		struct dsw_queue_flow *qf = &port->emigration_target_qfs[i];
		uint8_t queue_id = qf->queue_id;
		uint8_t queue_schedule_type =
			dsw->queues[queue_id].schedule_type;
		uint16_t flow_hash = qf->flow_hash;

		if (queue_schedule_type != schedule_type) {
			left_port_ids[left_qfs_len] =
				port->emigration_target_port_ids[i];
			left_qfs[left_qfs_len] = *qf;
			left_qfs_len++;
			continue;
		}

		DSW_LOG_DP_PORT(DEBUG, port->id, "Migration completed for "
				"queue_id %d flow_hash %d.\n", queue_id,
				flow_hash);
	}

	finished = port->emigration_targets_len - left_qfs_len;

	if (finished > 0)
		dsw_port_emigration_stats(port, finished);

	for (i = 0; i < left_qfs_len; i++) {
		port->emigration_target_port_ids[i] = left_port_ids[i];
		port->emigration_target_qfs[i] = left_qfs[i];
	}
	port->emigration_targets_len = left_qfs_len;

	if (port->emigration_targets_len == 0) {
		port->migration_state = DSW_MIGRATION_STATE_IDLE;
		port->emigration_targets_len = 0;
		port->seen_events_len = 0;
	}
}

static void
dsw_port_move_parallel_flows(struct dsw_evdev *dsw,
			     struct dsw_port *source_port)
{
	uint8_t i;

	for (i = 0; i < source_port->emigration_targets_len; i++) {
		struct dsw_queue_flow *qf =
			&source_port->emigration_target_qfs[i];
		uint8_t queue_id = qf->queue_id;

		if (dsw->queues[queue_id].schedule_type ==
		    RTE_SCHED_TYPE_PARALLEL) {
			uint8_t dest_port_id =
				source_port->emigration_target_port_ids[i];
			uint16_t flow_hash = qf->flow_hash;

			/* Single byte-sized stores are always atomic. */
			dsw->queues[queue_id].flow_to_port_map[flow_hash] =
				dest_port_id;
		}
	}

	rte_smp_wmb();

	dsw_port_end_emigration(dsw, source_port, RTE_SCHED_TYPE_PARALLEL);
}

static void
dsw_port_consider_emigration(struct dsw_evdev *dsw,
			     struct dsw_port *source_port,
			     uint64_t now)
{
	bool any_port_below_limit;
	struct dsw_queue_flow *seen_events = source_port->seen_events;
	uint16_t seen_events_len = source_port->seen_events_len;
	struct dsw_queue_flow_burst bursts[DSW_MAX_EVENTS_RECORDED];
	uint16_t num_bursts;
	int16_t source_port_load;
	int16_t port_loads[dsw->num_ports];

	if (now < source_port->next_emigration)
		return;

	if (dsw->num_ports == 1)
		return;

	DSW_LOG_DP_PORT(DEBUG, source_port->id, "Considering emigration.\n");

	/* For simplicity, postpone migration if there are still
	 * events to consume in the in_buffer (from the last
	 * emigration).
	 */
	if (source_port->in_buffer_len > 0) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "There are still "
				"events in the input buffer.\n");
		return;
	}

	if (source_port->migration_state != DSW_MIGRATION_STATE_IDLE) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id,
				"Emigration already in progress.\n");
		return;
	}

	if (seen_events_len < DSW_MAX_EVENTS_RECORDED) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "Not enough events "
				"are recorded to allow for a migration.\n");
		return;
	}

	/* Postpone migration considering in case paused events exists, since
	 * such events may prevent the migration procedure from completing,
	 * leading to wasted CPU cycles (e.g., sorting queue flows).
	 */
	if (source_port->paused_events_len > 0) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "Paused events on "
				"port. Postponing any migrations.\n");
		return;
	}

	/* Randomize interval to avoid having all threads considering
	 * emigration at the same in point in time, which might lead
	 * to all choosing the same target port.
	 */
	source_port->next_emigration = now +
		source_port->migration_interval / 2 +
		rte_rand_max(source_port->migration_interval);

	source_port_load =
		rte_atomic_load_explicit(&source_port->load,
					 rte_memory_order_relaxed);
	if (source_port_load < DSW_MIN_SOURCE_LOAD_FOR_MIGRATION) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id,
		      "Load %d is below threshold level %d.\n",
		      DSW_LOAD_TO_PERCENT(source_port_load),
		      DSW_LOAD_TO_PERCENT(DSW_MIN_SOURCE_LOAD_FOR_MIGRATION));
		return;
	}

	/* Avoid starting any expensive operations (sorting etc), in
	 * case of a scenario with all ports above the load limit.
	 */
	any_port_below_limit =
		dsw_retrieve_port_loads(dsw, port_loads,
					DSW_MAX_TARGET_LOAD_FOR_MIGRATION);
	if (!any_port_below_limit) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id,
				"Candidate target ports are all too highly "
				"loaded.\n");
		return;
	}

	num_bursts = dsw_sort_qfs_to_bursts(seen_events, seen_events_len,
					    bursts);

	/* For non-big-little systems, there's no point in moving the
	 * only (known) flow.
	 */
	if (num_bursts < 2) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "Only a single flow "
				"queue_id %d flow_hash %d has been seen.\n",
				bursts[0].queue_flow.queue_id,
				bursts[0].queue_flow.flow_hash);
		return;
	}

	dsw_select_emigration_targets(dsw, source_port, bursts, num_bursts,
				      port_loads);

	if (source_port->emigration_targets_len == 0)
		return;

	source_port->migration_state = DSW_MIGRATION_STATE_FINISH_PENDING;
	source_port->emigration_start = rte_get_timer_cycles();

	/* No need to go through the whole pause procedure for
	 * parallel queues, since atomic/ordered semantics need not to
	 * be maintained.
	 */
	dsw_port_move_parallel_flows(dsw, source_port);
}

static void
dsw_port_abort_migration(struct dsw_port *source_port)
{
	RTE_ASSERT(source_port->in_buffer_start == 0);
	RTE_ASSERT(source_port->in_buffer_len == 0);

	/* Putting the stashed events in the in_buffer makes sure they
	 * are processed before any events on the in_ring, to avoid
	 * reordering.
	 */
	rte_memcpy(source_port->in_buffer, source_port->emigrating_events,
		 source_port->emigrating_events_len * sizeof(struct rte_event));
	source_port->in_buffer_len = source_port->emigrating_events_len;
	source_port->emigrating_events_len = 0;

	source_port->emigration_targets_len = 0;

	source_port->migration_state = DSW_MIGRATION_STATE_IDLE;
}

static void
dsw_port_continue_emigration(struct dsw_evdev *dsw,
			     struct dsw_port *source_port)
{
	/* A flow migration cannot be completed if there are paused
	 * events, since some/all of those events may be have been
	 * produced as a result of processing the flow(s) selected for
	 * migration. Moving such a flow would potentially introduced
	 * reordering, since processing the migrated flow on the
	 * receiving flow may commence before the to-be-enqueued-to
	 * flows are unpaused, leading to paused events on the second
	 * port as well, destined for the same paused flow(s). When
	 * those flows are unpaused, the resulting events are
	 * delivered the owning port in an undefined order.
	 *
	 * Waiting for the events to be unpaused could lead to a
	 * deadlock, where two ports are both waiting for the other to
	 * unpause.
	 */
	if (source_port->paused_events_len > 0) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "There are events in "
				"the pause buffer. Aborting migration.\n");
		dsw_port_abort_migration(source_port);
		return;
	}

	dsw_port_add_paused_flows(source_port,
				  source_port->emigration_target_qfs,
				  source_port->emigration_targets_len);

	dsw_port_ctl_broadcast(dsw, source_port, DSW_CTL_PAUSE_REQ,
			       source_port->emigration_target_qfs,
			       source_port->emigration_targets_len);
	source_port->cfm_cnt = 0;

	source_port->migration_state = DSW_MIGRATION_STATE_PAUSING;
}

static void
dsw_port_try_finish_pending(struct dsw_evdev *dsw, struct dsw_port *source_port)
{
	if (unlikely(source_port->migration_state ==
		     DSW_MIGRATION_STATE_FINISH_PENDING &&
		     source_port->pending_releases == 0))
		dsw_port_continue_emigration(dsw, source_port);
}

static void
dsw_port_flush_no_longer_paused_events(struct dsw_evdev *dsw,
				       struct dsw_port *source_port);

static void
dsw_port_handle_unpause_flows(struct dsw_evdev *dsw, struct dsw_port *port,
			      uint8_t originating_port_id,
			      struct dsw_queue_flow *paused_qfs,
			      uint8_t qfs_len)
{
	uint16_t i;
	struct dsw_ctl_msg cfm = {
		.type = DSW_CTL_CFM,
		.originating_port_id = port->id
	};

	dsw_port_remove_paused_flows(port, paused_qfs, qfs_len);

	dsw_port_ctl_enqueue(&dsw->ports[originating_port_id], &cfm);

	for (i = 0; i < qfs_len; i++) {
		struct dsw_queue_flow *qf = &paused_qfs[i];

		if (dsw_schedule(dsw, qf->queue_id, qf->flow_hash) == port->id)
			port->immigrations++;
	}

	dsw_port_flush_no_longer_paused_events(dsw, port);
}

static void
dsw_port_buffer_in_buffer(struct dsw_port *port,
			  const struct rte_event *event)

{
	RTE_ASSERT(port->in_buffer_start == 0);

	port->in_buffer[port->in_buffer_len] = *event;
	port->in_buffer_len++;
}

static void
dsw_port_stash_migrating_event(struct dsw_port *port,
			       const struct rte_event *event)
{
	port->emigrating_events[port->emigrating_events_len] = *event;
	port->emigrating_events_len++;
}

static void
dsw_port_stash_any_migrating_events(struct dsw_port *port,
				    struct rte_event *events,
				    uint16_t *num)
{
	uint16_t i;
	uint16_t offset = 0;

	for (i = 0; i < *num; i++) {
		uint16_t flow_hash;
		struct rte_event *in_event = &events[i];

		flow_hash = dsw_flow_id_hash(in_event->flow_id);

		if (unlikely(dsw_port_is_flow_migrating(port,
							in_event->queue_id,
							flow_hash))) {
			dsw_port_stash_migrating_event(port, in_event);
			offset++;
		} else if (offset > 0) {
			struct rte_event *out_event = &events[i - offset];
			rte_memcpy(out_event, in_event,
				   sizeof(struct rte_event));
		}
	}

	*num -= offset;
}

#define DRAIN_DEQUEUE_BURST_SIZE (32)

static void
dsw_port_drain_in_ring(struct dsw_port *source_port)
{
	for (;;) {
		struct rte_event events[DRAIN_DEQUEUE_BURST_SIZE];
		uint16_t n;
		uint16_t i;
		uint16_t available;

		n = rte_event_ring_dequeue_burst(source_port->in_ring,
						 events,
						 DRAIN_DEQUEUE_BURST_SIZE,
						 &available);

		if (n == 0 && available == 0)
			break;

		for (i = 0; i < n; i++) {
			struct rte_event *event = &events[i];
			uint16_t flow_hash;

			flow_hash = dsw_flow_id_hash(event->flow_id);

			if (unlikely(dsw_port_is_flow_migrating(source_port,
								event->queue_id,
								flow_hash)))
				dsw_port_stash_migrating_event(source_port,
							       event);
			else
				dsw_port_buffer_in_buffer(source_port, event);
		}
	}
}

static void
dsw_port_forward_emigrated_event(struct dsw_evdev *dsw,
				 struct dsw_port *source_port,
				 struct rte_event *event)
{
	uint16_t i;

	for (i = 0; i < source_port->emigration_targets_len; i++) {
		struct dsw_queue_flow *qf =
			&source_port->emigration_target_qfs[i];
		uint8_t dest_port_id =
			source_port->emigration_target_port_ids[i];
		struct dsw_port *dest_port = &dsw->ports[dest_port_id];

		if (event->queue_id == qf->queue_id &&
		    dsw_flow_id_hash(event->flow_id) == qf->flow_hash) {
			/* No need to care about bursting forwarded
			 * events (to the destination port's in_ring),
			 * since migration doesn't happen very often,
			 * and also the majority of the dequeued
			 * events will likely *not* be forwarded.
			 */
			while (rte_event_ring_enqueue_burst(dest_port->in_ring,
							    event, 1,
							    NULL) != 1)
				rte_pause();
			return;
		}
	}

	/* Event did not belong to the emigrated flows */
	dsw_port_buffer_in_buffer(source_port, event);
}

static void
dsw_port_forward_emigrated_flows(struct dsw_evdev *dsw,
				 struct dsw_port *source_port)
{
	uint16_t i;

	for (i = 0; i < source_port->emigrating_events_len; i++) {
		struct rte_event *event = &source_port->emigrating_events[i];

		dsw_port_forward_emigrated_event(dsw, source_port, event);
	}
	source_port->emigrating_events_len = 0;
}

static void
dsw_port_move_emigrating_flows(struct dsw_evdev *dsw,
			       struct dsw_port *source_port)
{
	uint8_t i;

	/* There may be events lingering in the output buffer from
	 * prior to the pause took effect.
	 */
	dsw_port_flush_out_buffers(dsw, source_port);

	for (i = 0; i < source_port->emigration_targets_len; i++) {
		struct dsw_queue_flow *qf =
			&source_port->emigration_target_qfs[i];
		uint8_t dest_port_id =
			source_port->emigration_target_port_ids[i];

		dsw->queues[qf->queue_id].flow_to_port_map[qf->flow_hash] =
		    dest_port_id;
	}

	rte_smp_wmb();

	dsw_port_drain_in_ring(source_port);
	dsw_port_forward_emigrated_flows(dsw, source_port);

	dsw_port_remove_paused_flows(source_port,
				     source_port->emigration_target_qfs,
				     source_port->emigration_targets_len);

	dsw_port_flush_no_longer_paused_events(dsw, source_port);

	/* Processing migrating flows during migration may have
	 * produced events to paused flows, including the flows which
	 * were being migrated. Flushing the output buffers before
	 * unpausing the flows on other ports assures that such events
	 * are seen *before* any events produced by processing the
	 * migrating flows on the new port.
	 */
	dsw_port_flush_out_buffers(dsw, source_port);

	/* Flow table update and migration destination port's enqueues
	 * must be seen before the control message.
	 */
	rte_smp_wmb();

	dsw_port_ctl_broadcast(dsw, source_port, DSW_CTL_UNPAUSE_REQ,
			       source_port->emigration_target_qfs,
			       source_port->emigration_targets_len);
	source_port->cfm_cnt = 0;
	source_port->migration_state = DSW_MIGRATION_STATE_UNPAUSING;
}

static void
dsw_port_handle_confirm(struct dsw_evdev *dsw, struct dsw_port *port)
{
	port->cfm_cnt++;

	if (port->cfm_cnt == (dsw->num_ports - 1)) {
		switch (port->migration_state) {
		case DSW_MIGRATION_STATE_PAUSING:
			dsw_port_move_emigrating_flows(dsw, port);
			break;
		case DSW_MIGRATION_STATE_UNPAUSING:
			dsw_port_end_emigration(dsw, port,
						RTE_SCHED_TYPE_ATOMIC);
			break;
		default:
			RTE_VERIFY(0);
			break;
		}
	}
}

static void
dsw_port_ctl_process(struct dsw_evdev *dsw, struct dsw_port *port)
{
	struct dsw_ctl_msg msg;

	if (dsw_port_ctl_dequeue(port, &msg) == 0) {
		switch (msg.type) {
		case DSW_CTL_PAUSE_REQ:
			dsw_port_handle_pause_flows(dsw, port,
						    msg.originating_port_id,
						    msg.qfs, msg.qfs_len);
			break;
		case DSW_CTL_UNPAUSE_REQ:
			dsw_port_handle_unpause_flows(dsw, port,
						      msg.originating_port_id,
						      msg.qfs, msg.qfs_len);
			break;
		case DSW_CTL_CFM:
			dsw_port_handle_confirm(dsw, port);
			break;
		}
	}
}

static void
dsw_port_note_op(struct dsw_port *port, uint16_t num_events)
{
	port->ops_since_bg_task += (num_events+1);
}

static void
dsw_port_bg_process(struct dsw_evdev *dsw, struct dsw_port *port)
{
	/* Polling the control ring is relatively inexpensive, and
	 * polling it often helps bringing down migration latency, so
	 * do this for every iteration.
	 */
	dsw_port_ctl_process(dsw, port);

	/* Always check if a migration is waiting for pending releases
	 * to arrive, to minimize the amount of time dequeuing events
	 * from the port is disabled.
	 */
	dsw_port_try_finish_pending(dsw, port);

	/* To avoid considering migration and flushing output buffers
	 * on every dequeue/enqueue call, the scheduler only performs
	 * such 'background' tasks every nth
	 * (i.e. DSW_MAX_PORT_OPS_PER_BG_TASK) operation.
	 */
	if (unlikely(port->ops_since_bg_task >= DSW_MAX_PORT_OPS_PER_BG_TASK)) {
		uint64_t now;

		now = rte_get_timer_cycles();

		port->last_bg = now;

		/* Logic to avoid having events linger in the output
		 * buffer too long.
		 */
		dsw_port_flush_out_buffers(dsw, port);

		dsw_port_consider_load_update(port, now);

		dsw_port_consider_emigration(dsw, port, now);

		port->ops_since_bg_task = 0;
	}
}

static void
dsw_port_flush_out_buffers(struct dsw_evdev *dsw, struct dsw_port *source_port)
{
	uint16_t dest_port_id;

	for (dest_port_id = 0; dest_port_id < dsw->num_ports; dest_port_id++)
		dsw_port_transmit_buffered(dsw, source_port, dest_port_id);
}

uint16_t
dsw_event_enqueue(void *port, const struct rte_event *ev)
{
	return dsw_event_enqueue_burst(port, ev, unlikely(ev == NULL) ? 0 : 1);
}

static __rte_always_inline uint16_t
dsw_event_enqueue_burst_generic(struct dsw_port *source_port,
				const struct rte_event events[],
				uint16_t events_len, bool op_types_known,
				uint16_t num_new, uint16_t num_forward,
				uint16_t num_release)
{
	struct dsw_evdev *dsw = source_port->dsw;
	bool enough_credits;
	uint16_t i;

	DSW_LOG_DP_PORT(DEBUG, source_port->id, "Attempting to enqueue %d "
			"events.\n", events_len);

	dsw_port_bg_process(dsw, source_port);

	/* XXX: For performance (=ring efficiency) reasons, the
	 * scheduler relies on internal non-ring buffers instead of
	 * immediately sending the event to the destination ring. For
	 * a producer that doesn't intend to produce or consume any
	 * more events, the scheduler provides a way to flush the
	 * buffer, by means of doing an enqueue of zero events. In
	 * addition, a port cannot be left "unattended" (e.g. unused)
	 * for long periods of time, since that would stall
	 * migration. Eventdev API extensions to provide a cleaner way
	 * to archive both of these functions should be
	 * considered.
	 */
	if (unlikely(events_len == 0)) {
		dsw_port_note_op(source_port, DSW_MAX_PORT_OPS_PER_BG_TASK);
		dsw_port_flush_out_buffers(dsw, source_port);
		return 0;
	}

	dsw_port_note_op(source_port, events_len);

	if (!op_types_known)
		for (i = 0; i < events_len; i++) {
			switch (events[i].op) {
			case RTE_EVENT_OP_NEW:
				num_new++;
				break;
			case RTE_EVENT_OP_FORWARD:
				num_forward++;
				break;
			case RTE_EVENT_OP_RELEASE:
				num_release++;
				break;
			}
		}

	/* Technically, we could allow the non-new events up to the
	 * first new event in the array into the system, but for
	 * simplicity reasons, we deny the whole burst if the port is
	 * above the water mark.
	 */
	if (unlikely(num_new > 0 &&
		     rte_atomic_load_explicit(&dsw->credits_on_loan,
					      rte_memory_order_relaxed) >
		     source_port->new_event_threshold))
		return 0;

	enough_credits = dsw_port_acquire_credits(dsw, source_port, num_new);
	if (unlikely(!enough_credits))
		return 0;

	dsw_port_return_credits(dsw, source_port, num_release);

	/* This may seem harsh, but it's important for an application
	 * to get early feedback for cases where it fails to stick to
	 * the API contract.
	 */
	RTE_VERIFY(num_forward + num_release <= source_port->pending_releases);
	source_port->pending_releases -= (num_forward + num_release);

	dsw_port_enqueue_stats(source_port, num_new, num_forward, num_release);

	for (i = 0; i < events_len; i++) {
		const struct rte_event *event = &events[i];

		if (likely(num_release == 0 ||
			   event->op != RTE_EVENT_OP_RELEASE))
			dsw_port_buffer_event(dsw, source_port, event);
		dsw_port_queue_enqueue_stats(source_port, event->queue_id);
	}

	DSW_LOG_DP_PORT(DEBUG, source_port->id, "%d non-release events "
			"accepted.\n", num_new + num_forward);

	return (num_new + num_forward + num_release);
}

uint16_t
dsw_event_enqueue_burst(void *port, const struct rte_event events[],
			uint16_t events_len)
{
	struct dsw_port *source_port = port;

	if (unlikely(events_len > source_port->enqueue_depth))
		events_len = source_port->enqueue_depth;

	return dsw_event_enqueue_burst_generic(source_port, events,
					       events_len, false, 0, 0, 0);
}

uint16_t
dsw_event_enqueue_new_burst(void *port, const struct rte_event events[],
			    uint16_t events_len)
{
	struct dsw_port *source_port = port;

	if (unlikely(events_len > source_port->enqueue_depth))
		events_len = source_port->enqueue_depth;

	return dsw_event_enqueue_burst_generic(source_port, events,
					       events_len, true, events_len,
					       0, 0);
}

uint16_t
dsw_event_enqueue_forward_burst(void *port, const struct rte_event events[],
				uint16_t events_len)
{
	struct dsw_port *source_port = port;

	if (unlikely(events_len > source_port->enqueue_depth))
		events_len = source_port->enqueue_depth;

	return dsw_event_enqueue_burst_generic(source_port, events,
					       events_len, true, 0,
					       events_len, 0);
}

uint16_t
dsw_event_dequeue(void *port, struct rte_event *events, uint64_t wait)
{
	return dsw_event_dequeue_burst(port, events, 1, wait);
}

static void
dsw_port_record_seen_events(struct dsw_port *port, struct rte_event *events,
			    uint16_t num)
{
	uint16_t i;

	dsw_port_dequeue_stats(port, num);

	for (i = 0; i < num; i++) {
		uint16_t l_idx = port->seen_events_idx;
		struct dsw_queue_flow *qf = &port->seen_events[l_idx];
		struct rte_event *event = &events[i];
		qf->queue_id = event->queue_id;
		qf->flow_hash = dsw_flow_id_hash(event->flow_id);

		port->seen_events_idx = (l_idx+1) % DSW_MAX_EVENTS_RECORDED;

		dsw_port_queue_dequeued_stats(port, event->queue_id);
	}

	if (unlikely(port->seen_events_len != DSW_MAX_EVENTS_RECORDED))
		port->seen_events_len =
			RTE_MIN(port->seen_events_len + num,
				DSW_MAX_EVENTS_RECORDED);
}

#ifdef DSW_SORT_DEQUEUED

#define DSW_EVENT_TO_INT(_event)				\
	((int)((((_event)->queue_id)<<16)|((_event)->flow_id)))

static inline int
dsw_cmp_event(const void *v_event_a, const void *v_event_b)
{
	const struct rte_event *event_a = v_event_a;
	const struct rte_event *event_b = v_event_b;

	return DSW_EVENT_TO_INT(event_a) - DSW_EVENT_TO_INT(event_b);
}
#endif

static uint16_t
dsw_port_dequeue_burst(struct dsw_port *port, struct rte_event *events,
		       uint16_t num)
{
	enum dsw_migration_state state = port->migration_state;
	uint16_t dequeued;

	if (unlikely(state == DSW_MIGRATION_STATE_FINISH_PENDING))
		/* Do not produce new items of work - only finish
		 * outstanding (unreleased) events, to allow the
		 * migration procedure to continue.
		 */
		dequeued = 0;
	else if (unlikely(port->in_buffer_len > 0)) {
		dequeued = RTE_MIN(num, port->in_buffer_len);

		rte_memcpy(events, &port->in_buffer[port->in_buffer_start],
			   dequeued * sizeof(struct rte_event));

		port->in_buffer_start += dequeued;
		port->in_buffer_len -= dequeued;

		if (port->in_buffer_len == 0)
			port->in_buffer_start = 0;
	} else {
		dequeued = rte_event_ring_dequeue_burst(port->in_ring,
							events, num, NULL);

		/* Stash incoming events belonging to migrating flows,
		 * to avoid having to deal with forwarded events to
		 * flows which are also in the process of being
		 * migrated. A failure to do so leads to reordering,
		 * since paused events on the source port may be
		 * flushed after paused events on the migration
		 * destination port.
		 */
		if (unlikely(state == DSW_MIGRATION_STATE_PAUSING))
			dsw_port_stash_any_migrating_events(port, events,
							    &dequeued);
	}

	return dequeued;
}

uint16_t
dsw_event_dequeue_burst(void *port, struct rte_event *events, uint16_t num,
			uint64_t wait __rte_unused)
{
	struct dsw_port *source_port = port;
	struct dsw_evdev *dsw = source_port->dsw;
	uint16_t dequeued;

	if (source_port->implicit_release) {
		dsw_port_return_credits(dsw, port,
					source_port->pending_releases);

		source_port->pending_releases = 0;
	}

	dsw_port_bg_process(dsw, source_port);

	if (unlikely(num > source_port->dequeue_depth))
		num = source_port->dequeue_depth;

	dequeued = dsw_port_dequeue_burst(source_port, events, num);

	source_port->pending_releases += dequeued;

	dsw_port_load_record(source_port, dequeued);

	dsw_port_note_op(source_port, dequeued);

	if (dequeued > 0) {
		DSW_LOG_DP_PORT(DEBUG, source_port->id, "Dequeued %d events.\n",
				dequeued);

		/* One potential optimization one might think of is to
		 * add a migration state (prior to 'pausing'), and
		 * only record seen events when the port is in this
		 * state (and transit to 'pausing' when enough events
		 * have been gathered). However, that schema doesn't
		 * seem to improve performance.
		 */
		dsw_port_record_seen_events(port, events, dequeued);
	} else /* Zero-size dequeue means a likely idle port, and thus
		* we can afford trading some efficiency for a slightly
		* reduced event wall-time latency.
		*/
		dsw_port_flush_out_buffers(dsw, port);

#ifdef DSW_SORT_DEQUEUED
	dsw_stable_sort(events, dequeued, sizeof(events[0]), dsw_cmp_event);
#endif

	return dequeued;
}

void dsw_event_maintain(void *port, int op)
{
	struct dsw_port *source_port = port;
	struct dsw_evdev *dsw = source_port->dsw;

	dsw_port_note_op(source_port, 0);
	dsw_port_bg_process(dsw, source_port);

	if (op & RTE_EVENT_DEV_MAINT_OP_FLUSH)
		dsw_port_flush_out_buffers(dsw, source_port);
}