summaryrefslogtreecommitdiff
path: root/utilities/gdb/ovs_gdb.py
blob: 982395dd1d27a46ab69224b114beb59ecd970821 (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
#
#  Copyright (c) 2018 Eelco Chaudron
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version
#  2 of the License, or (at your option) any later version.
#
#  Files name:
#    ovs_gdb.py
#
#  Description:
#    GDB commands and functions for Open vSwitch debugging
#
#  Author:
#    Eelco Chaudron
#
#  Initial Created:
#    23 April 2018
#
#  Notes:
#    It implements the following GDB commands:
#    - ovs_dump_bridge {ports|wanted}
#    - ovs_dump_bridge_ports <struct bridge *>
#    - ovs_dump_dp_netdev [ports]
#    - ovs_dump_dp_netdev_poll_threads <struct dp_netdev *>
#    - ovs_dump_dp_netdev_ports <struct dp_netdev *>
#    - ovs_dump_dp_provider
#    - ovs_dump_netdev
#    - ovs_dump_netdev_provider
#    - ovs_dump_ovs_list <struct ovs_list *> {[<structure>] [<member>] {dump}]}
#    - ovs_dump_packets <struct dp_packet_batch|dp_packet> [tcpdump options]
#    - ovs_dump_cmap <struct cmap *> {[<structure>] [<member>] {dump}]}
#    - ovs_dump_hmap <struct hmap *> <structure> <member> {dump}
#    - ovs_dump_simap <struct simap *>
#    - ovs_dump_smap <struct smap *>
#    - ovs_dump_udpif_keys {<udpif_name>|<udpif_address>} {short}
#    - ovs_show_fdb {[<bridge_name>] {dbg} {hash}}
#    - ovs_show_upcall {dbg}
#
#  Example:
#    $ gdb $(which ovs-vswitchd) $(pidof ovs-vswitchd)
#    (gdb) source ./utilities/gdb/ovs_gdb.py
#
#    (gdb) ovs_dump_<TAB>
#    ovs_dump_bridge           ovs_dump_bridge_ports     ovs_dump_dp_netdev
#    ovs_dump_dp_netdev_ports  ovs_dump_netdev
#
#    (gdb) ovs_dump_bridge
#    (struct bridge *) 0x5615471ed2e0: name = br2, type = system
#    (struct bridge *) 0x561547166350: name = br0, type = system
#    (struct bridge *) 0x561547216de0: name = ovs_pvp_br0, type = netdev
#    (struct bridge *) 0x5615471d0420: name = br1, type = system
#
#    (gdb) p *(struct bridge *) 0x5615471d0420
#    $1 = {node = {hash = 24776443, next = 0x0}, name = 0x5615471cca90 "br1",
#    type = 0x561547163bb0 "system",
#    ...
#    ...
#
import gdb
import struct
import sys
import uuid
try:
    from scapy.layers.l2 import Ether
    from scapy.utils import tcpdump
except ModuleNotFoundError:
    Ether = None
    tcpdump = None


#
# Global #define's from OVS which might need updating based on a version.
#
N_UMAPS = 512


#
# The container_of code below is a copied from the Linux kernel project file,
# scripts/gdb/linux/utils.py. It has the following copyright header:
#
# # gdb helper commands and functions for Linux kernel debugging
# #
# #  common utilities
# #
# # Copyright (c) Siemens AG, 2011-2013
# #
# # Authors:
# #  Jan Kiszka <jan.kiszka@siemens.com>
# #
# # This work is licensed under the terms of the GNU GPL version 2.
#
class CachedType(object):
    def __init__(self, name):
        self._type = None
        self._name = name

    def _new_objfile_handler(self, event):
        self._type = None
        gdb.events.new_objfile.disconnect(self._new_objfile_handler)

    def get_type(self):
        if self._type is None:
            self._type = gdb.lookup_type(self._name)
            if self._type is None:
                raise gdb.GdbError(
                    "cannot resolve type '{0}'".format(self._name))
            if hasattr(gdb, 'events') and hasattr(gdb.events, 'new_objfile'):
                gdb.events.new_objfile.connect(self._new_objfile_handler)
        return self._type


long_type = CachedType("long")


def get_long_type():
    global long_type
    return long_type.get_type()


def offset_of(typeobj, field):
    element = gdb.Value(0).cast(typeobj)
    return int(str(element[field].address).split()[0], 16)


def container_of(ptr, typeobj, member):
    return (ptr.cast(get_long_type()) -
            offset_of(typeobj, member)).cast(typeobj)


def get_global_variable(name):
    var = gdb.lookup_symbol(name)[0]
    if var is None or not var.is_variable:
        print("Can't find {} global variable, are you sure "
              "you are debugging OVS?".format(name))
        return None
    return gdb.parse_and_eval(name)


def get_time_msec():
    # There is no variable that stores the current time each iteration,
    # to get a decent time time_now() value. For now we take the global
    # "coverage_run_time" value, which is the current time + max 5 seconds
    # (COVERAGE_RUN_INTERVAL)
    return int(get_global_variable("coverage_run_time")), -5000


def get_time_now():
    # See get_time_msec() above
    return int(get_global_variable("coverage_run_time")) / 1000, -5


def eth_addr_to_string(eth_addr):
    return "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(
        int(eth_addr['ea'][0]),
        int(eth_addr['ea'][1]),
        int(eth_addr['ea'][2]),
        int(eth_addr['ea'][3]),
        int(eth_addr['ea'][4]),
        int(eth_addr['ea'][5]))


#
# Simple class to print a spinner on the console
#
class ProgressIndicator(object):
    def __init__(self, message=None):
        self.spinner = "/-\\|"
        self.spinner_index = 0
        self.message = message

        if self.message is not None:
            print(self.message, end='')

    def update(self):
        print("{}\b".format(self.spinner[self.spinner_index]), end='')
        sys.stdout.flush()
        self.spinner_index += 1
        if self.spinner_index >= len(self.spinner):
            self.spinner_index = 0

    def pause(self):
        print("\r\033[K", end='')

    def resume(self):
        if self.message is not None:
            print(self.message, end='')
        self.update()

    def done(self):
        self.pause()


#
# Class that will provide an iterator over an OVS cmap.
#
class ForEachCMAP(object):
    def __init__(self, cmap, typeobj=None, member='node'):
        self.cmap = cmap
        self.first = True
        self.typeobj = typeobj
        self.member = member
        # Cursor values
        self.node = 0
        self.bucket_idx = 0
        self.entry_idx = 0

    def __iter__(self):
        return self

    def __get_CMAP_K(self):
        ptr_type = gdb.lookup_type("void").pointer()
        return (64 - 4) / (4 + ptr_type.sizeof)

    def __next(self):
        ipml = self.cmap['impl']['p']

        if self.node != 0:
            self.node = self.node['next']['p']
            if self.node != 0:
                return

        while self.bucket_idx <= ipml['mask']:
            buckets = ipml['buckets'][self.bucket_idx]
            while self.entry_idx < self.__get_CMAP_K():
                self.node = buckets['nodes'][self.entry_idx]['next']['p']
                self.entry_idx += 1
                if self.node != 0:
                    return

            self.bucket_idx += 1
            self.entry_idx = 0

        raise StopIteration

    def __next__(self):
        ipml = self.cmap['impl']['p']
        if ipml['n'] == 0:
            raise StopIteration

        self.__next()

        if self.typeobj is None:
            return self.node

        return container_of(self.node,
                            gdb.lookup_type(self.typeobj).pointer(),
                            self.member)

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OVS hmap.
#
class ForEachHMAP(object):
    def __init__(self, hmap, typeobj=None, member='node'):
        self.hmap = hmap
        self.node = None
        self.first = True
        self.typeobj = typeobj
        self.member = member

    def __iter__(self):
        return self

    def __next(self, start):
        for i in range(start, (self.hmap['mask'] + 1)):
            self.node = self.hmap['buckets'][i]
            if self.node != 0:
                return

        raise StopIteration

    def __next__(self):
        #
        # In the real implementation the n values is never checked,
        # however when debugging we do, as we might try to access
        # a hmap that has been cleared/hmap_destroy().
        #
        if self.hmap['n'] <= 0:
            raise StopIteration

        if self.first:
            self.first = False
            self.__next(0)
        elif self.node['next'] != 0:
            self.node = self.node['next']
        else:
            self.__next((self.node['hash'] & self.hmap['mask']) + 1)

        if self.typeobj is None:
            return self.node

        return container_of(self.node,
                            gdb.lookup_type(self.typeobj).pointer(),
                            self.member)

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an Netlink attributes
#
class ForEachNL(object):
    def __init__(self, nlattrs, nlattrs_len):
        self.attr = nlattrs.cast(gdb.lookup_type('struct nlattr').pointer())
        self.attr_len = int(nlattrs_len)

    def __iter__(self):
        return self

    def round_up(self, val, round_to):
        return int(val) + (round_to - int(val)) % round_to

    def __next__(self):
        if self.attr is None or \
           self.attr_len < 4 or self.attr['nla_len'] < 4 or  \
           self.attr['nla_len'] > self.attr_len:
            #
            # Invalid attr set, maybe we should raise an exception?
            #
            raise StopIteration

        attr = self.attr
        self.attr_len -= self.round_up(attr['nla_len'], 4)

        self.attr = self.attr.cast(gdb.lookup_type('void').pointer()) \
            + self.round_up(attr['nla_len'], 4)
        self.attr = self.attr.cast(gdb.lookup_type('struct nlattr').pointer())

        return attr

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OVS shash.
#
class ForEachSHASH(ForEachHMAP):
    def __init__(self, shash, typeobj=None):

        self.data_typeobj = typeobj

        super(ForEachSHASH, self).__init__(shash['map'],
                                           "struct shash_node", "node")

    def __next__(self):
        node = super(ForEachSHASH, self).__next__()

        if self.data_typeobj is None:
            return node

        return node['data'].cast(gdb.lookup_type(self.data_typeobj).pointer())

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OVS simap.
#
class ForEachSIMAP(ForEachHMAP):
    def __init__(self, shash):
        super(ForEachSIMAP, self).__init__(shash['map'],
                                           "struct simap_node", "node")

    def __next__(self):
        node = super(ForEachSIMAP, self).__next__()
        return node['name'], node['data']

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OVS smap.
#
class ForEachSMAP(ForEachHMAP):
    def __init__(self, shash):
        super(ForEachSMAP, self).__init__(shash['map'],
                                          "struct smap_node", "node")

    def __next__(self):
        node = super(ForEachSMAP, self).__next__()
        return node['key'], node['value']

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OVS list.
#
class ForEachLIST(object):
    def __init__(self, list, typeobj=None, member='node'):
        self.list = list
        self.node = list
        self.typeobj = typeobj
        self.member = member

    def __iter__(self):
        return self

    def __next__(self):
        if self.list.address == self.node['next']:
            raise StopIteration

        self.node = self.node['next']

        if self.typeobj is None:
            return self.node

        return container_of(self.node,
                            gdb.lookup_type(self.typeobj).pointer(),
                            self.member)

    def next(self):
        return self.__next__()


#
# Class that will provide an iterator over an OFPACTS.
#
class ForEachOFPACTS(object):
    def __init__(self, ofpacts, ofpacts_len):
        self.ofpact = ofpacts.cast(gdb.lookup_type('struct ofpact').pointer())
        self.length = int(ofpacts_len)

    def __round_up(self, val, round_to):
        return int(val) + (round_to - int(val)) % round_to

    def __iter__(self):
        return self

    def __next__(self):
        if self.ofpact is None or self.length <= 0:
            raise StopIteration

        ofpact = self.ofpact
        length = self.__round_up(ofpact['len'], 8)

        self.length -= length
        self.ofpact = self.ofpact.cast(
            gdb.lookup_type('void').pointer()) + length
        self.ofpact = self.ofpact.cast(
            gdb.lookup_type('struct ofpact').pointer())

        return ofpact

    def next(self):
        return self.__next__()


#
# Implements the GDB "ovs_dump_bridges" command
#
class CmdDumpBridge(gdb.Command):
    """Dump all configured bridges.
    Usage:
      ovs_dump_bridge {ports|wanted}
    """
    def __init__(self):
        super(CmdDumpBridge, self).__init__("ovs_dump_bridge",
                                            gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        ports = False
        wanted = False
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) > 1 or \
           (len(arg_list) == 1 and arg_list[0] != "ports" and
           arg_list[0] != "wanted"):
            print("usage: ovs_dump_bridge {ports|wanted}")
            return
        elif len(arg_list) == 1:
            if arg_list[0] == "ports":
                ports = True
            else:
                wanted = True

        all_bridges = get_global_variable('all_bridges')
        if all_bridges is None:
            return

        for node in ForEachHMAP(all_bridges,
                                "struct bridge", "node"):
            print("(struct bridge *) {}: name = {}, type = {}".
                  format(node, node['name'].string(),
                         node['type'].string()))

            if ports:
                for port in ForEachHMAP(node['ports'],
                                        "struct port", "hmap_node"):
                    CmdDumpBridgePorts.display_single_port(port, 4)

            if wanted:
                for port in ForEachSHASH(node['wanted_ports'],
                                         typeobj="struct ovsrec_port"):
                    print("    (struct ovsrec_port *) {}: name = {}".
                          format(port, port['name'].string()))
                    # print port.dereference()


#
# Implements the GDB "ovs_dump_bridge_ports" command
#
class CmdDumpBridgePorts(gdb.Command):
    """Dump all ports added to a specific struct bridge*.
    Usage:
      ovs_dump_bridge_ports <struct bridge *>
    """
    def __init__(self):
        super(CmdDumpBridgePorts, self).__init__("ovs_dump_bridge_ports",
                                                 gdb.COMMAND_DATA)

    @staticmethod
    def display_single_port(port, indent=0):
        indent = " " * indent
        port = port.cast(gdb.lookup_type('struct port').pointer())
        print("{}(struct port *) {}: name = {}, bridge = (struct bridge *) {}".
              format(indent, port, port['name'].string(),
                     port['bridge']))

        indent += " " * 4
        for iface in ForEachLIST(port['ifaces'], "struct iface", "port_elem"):
            print("{}(struct iface *) {}: name = {}, ofp_port = {}, "
                  "netdev = (struct netdev *) {}".
                  format(indent, iface, iface['name'],
                         iface['ofp_port'], iface['netdev']))

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) != 1:
            print("usage: ovs_dump_bridge_ports <struct bridge *>")
            return
        bridge = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct bridge').pointer())
        for node in ForEachHMAP(bridge['ports'],
                                "struct port", "hmap_node"):
            self.display_single_port(node)


#
# Implements the GDB "ovs_dump_dp_netdev" command
#
class CmdDumpDpNetdev(gdb.Command):
    """Dump all registered dp_netdev structures.
    Usage:
      ovs_dump_dp_netdev [ports]
    """
    def __init__(self):
        super(CmdDumpDpNetdev, self).__init__("ovs_dump_dp_netdev",
                                              gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        ports = False
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) > 1 or \
           (len(arg_list) == 1 and arg_list[0] != "ports"):
            print("usage: ovs_dump_dp_netdev [ports]")
            return
        elif len(arg_list) == 1:
            ports = True

        dp_netdevs = get_global_variable('dp_netdevs')
        if dp_netdevs is None:
            return

        for dp in ForEachSHASH(dp_netdevs, typeobj=('struct dp_netdev')):

            print("(struct dp_netdev *) {}: name = {}, class = "
                  "(struct dpif_class *) {}".
                  format(dp, dp['name'].string(), dp['class']))

            if ports:
                for node in ForEachHMAP(dp['ports'],
                                        "struct dp_netdev_port", "node"):
                    CmdDumpDpNetdevPorts.display_single_port(node, 4)


#
# Implements the GDB "ovs_dump_dp_netdev_poll_threads" command
#
class CmdDumpDpNetdevPollThreads(gdb.Command):
    """Dump all poll_thread info added to a specific struct dp_netdev*.
    Usage:
      ovs_dump_dp_netdev_poll_threads <struct dp_netdev *>
    """
    def __init__(self):
        super(CmdDumpDpNetdevPollThreads, self).__init__(
            "ovs_dump_dp_netdev_poll_threads",
            gdb.COMMAND_DATA)

    @staticmethod
    def display_single_poll_thread(pmd_thread, indent=0):
        indent = " " * indent
        print("{}(struct dp_netdev_pmd_thread *) {}: core_id = {}, "
              "numa_id {}".format(indent,
                                  pmd_thread, pmd_thread['core_id'],
                                  pmd_thread['numa_id']))

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) != 1:
            print("usage: ovs_dump_dp_netdev_poll_threads "
                  "<struct dp_netdev *>")
            return
        dp_netdev = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct dp_netdev').pointer())
        for node in ForEachCMAP(dp_netdev['poll_threads'],
                                "struct dp_netdev_pmd_thread", "node"):
            self.display_single_poll_thread(node)


#
# Implements the GDB "ovs_dump_dp_netdev_ports" command
#
class CmdDumpDpNetdevPorts(gdb.Command):
    """Dump all ports added to a specific struct dp_netdev*.
    Usage:
      ovs_dump_dp_netdev_ports <struct dp_netdev *>
    """
    def __init__(self):
        super(CmdDumpDpNetdevPorts, self).__init__("ovs_dump_dp_netdev_ports",
                                                   gdb.COMMAND_DATA)

    @staticmethod
    def display_single_port(port, indent=0):
        indent = " " * indent
        print("{}(struct dp_netdev_port *) {}:".format(indent, port))
        print("{}    port_no = {}, n_rxq = {}, type = {}".
              format(indent, port['port_no'], port['n_rxq'],
                     port['type'].string()))
        print("{}    netdev = (struct netdev *) {}: name = {}, "
              "n_txq/rxq = {}/{}".
              format(indent, port['netdev'],
                     port['netdev']['name'].string(),
                     port['netdev']['n_txq'],
                     port['netdev']['n_rxq']))

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) != 1:
            print("usage: ovs_dump_dp_netdev_ports <struct dp_netdev *>")
            return
        dp_netdev = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct dp_netdev').pointer())
        for node in ForEachHMAP(dp_netdev['ports'],
                                "struct dp_netdev_port", "node"):
            # print node.dereference()
            self.display_single_port(node)


#
# Implements the GDB "ovs_dump_dp_provider" command
#
class CmdDumpDpProvider(gdb.Command):
    """Dump all registered registered_dpif_class structures.
    Usage:
      ovs_dump_dp_provider
    """
    def __init__(self):
        super(CmdDumpDpProvider, self).__init__("ovs_dump_dp_provider",
                                                gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        dp_providers = get_global_variable('dpif_classes')
        if dp_providers is None:
            return

        for dp_class in ForEachSHASH(dp_providers,
                                     typeobj="struct registered_dpif_class"):

            print("(struct registered_dpif_class *) {}: "
                  "(struct dpif_class *) 0x{:x} = {{type = {}, ...}}, "
                  "refcount = {}".
                  format(dp_class,
                         int(dp_class['dpif_class']),
                         dp_class['dpif_class']['type'].string(),
                         dp_class['refcount']))


#
# Implements the GDB "ovs_dump_netdev" command
#
class CmdDumpNetdev(gdb.Command):
    """Dump all registered netdev structures.
    Usage:
      ovs_dump_netdev
    """
    def __init__(self):
        super(CmdDumpNetdev, self).__init__("ovs_dump_netdev",
                                            gdb.COMMAND_DATA)

    @staticmethod
    def display_single_netdev(netdev, indent=0):
        indent = " " * indent
        print("{}(struct netdev *) {}: name = {:15}, auto_classified = {}, "
              "netdev_class = {}".
              format(indent, netdev, netdev['name'].string(),
                     netdev['auto_classified'], netdev['netdev_class']))

    def invoke(self, arg, from_tty):
        netdev_shash = get_global_variable('netdev_shash')
        if netdev_shash is None:
            return

        for netdev in ForEachSHASH(netdev_shash, "struct netdev"):
            self.display_single_netdev(netdev)


#
# Implements the GDB "ovs_dump_netdev_provider" command
#
class CmdDumpNetdevProvider(gdb.Command):
    """Dump all registered netdev providers.
    Usage:
      ovs_dump_netdev_provider
    """
    def __init__(self):
        super(CmdDumpNetdevProvider, self).__init__("ovs_dump_netdev_provider",
                                                    gdb.COMMAND_DATA)

    @staticmethod
    def is_class_vport_class(netdev_class):
        netdev_class = netdev_class.cast(
            gdb.lookup_type('struct netdev_class').pointer())

        vport_construct = gdb.lookup_symbol('netdev_vport_construct')[0]

        if netdev_class['construct'] == vport_construct.value():
            return True
        return False

    @staticmethod
    def display_single_netdev_provider(reg_class, indent=0):
        indent = " " * indent
        print("{}(struct netdev_registered_class *) {}: refcnt = {},".
              format(indent, reg_class, reg_class['refcnt']))

        print("{}    (struct netdev_class *) 0x{:x} = {{type = {}, "
              "is_pmd = {}, ...}}, ".
              format(indent, int(reg_class['class']),
                     reg_class['class']['type'].string(),
                     reg_class['class']['is_pmd']))

        if CmdDumpNetdevProvider.is_class_vport_class(reg_class['class']):
            vport = container_of(
                reg_class['class'],
                gdb.lookup_type('struct vport_class').pointer(),
                'netdev_class')

            if vport['dpif_port'] != 0:
                dpif_port = vport['dpif_port'].string()
            else:
                dpif_port = "\"\""

            print("{}    (struct vport_class *) 0x{:x} = "
                  "{{ dpif_port = {}, ... }}".
                  format(indent, int(vport), dpif_port))

    def invoke(self, arg, from_tty):
        netdev_classes = get_global_variable('netdev_classes')
        if netdev_classes is None:
            return

        for reg_class in ForEachCMAP(netdev_classes,
                                     "struct netdev_registered_class",
                                     "cmap_node"):
            self.display_single_netdev_provider(reg_class)


#
# Implements the GDB "ovs_dump_ovs_list" command
#
class CmdDumpOvsList(gdb.Command):
    """Dump all nodes of an ovs_list give
    Usage:
      ovs_dump_ovs_list <struct ovs_list *> {[<structure>] [<member>] {dump}]}

    For example dump all the none quiescent OvS RCU threads:

      (gdb) ovs_dump_ovs_list &ovsrcu_threads
      (struct ovs_list *) 0x1400
      (struct ovs_list *) 0xcc00
      (struct ovs_list *) 0x6806

    This is not very useful, so please use this with the container_of mode:

      (gdb) set $threads = &ovsrcu_threads
      (gdb) ovs_dump_ovs_list $threads 'struct ovsrcu_perthread' list_node
      (struct ovsrcu_perthread *) 0x1400
      (struct ovsrcu_perthread *) 0xcc00
      (struct ovsrcu_perthread *) 0x6806

    Now you can manually use the print command to show the content, or use the
    dump option to dump the structure for all nodes:

      (gdb) ovs_dump_ovs_list $threads 'struct ovsrcu_perthread' list_node dump
      (struct ovsrcu_perthread *) 0x1400 =
        {list_node = {prev = 0x48e80 <ovsrcu_threads>, next = 0xcc00}, mutex...

      (struct ovsrcu_perthread *) 0xcc00 =
        {list_node = {prev = 0x1400, next = 0x6806}, mutex ...

      (struct ovsrcu_perthread *) 0x6806 =
        {list_node = {prev = 0xcc00, next = 0x48e80 <ovsrcu_threads>}, ...
    """
    def __init__(self):
        super(CmdDumpOvsList, self).__init__("ovs_dump_ovs_list",
                                             gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        typeobj = None
        member = None
        dump = False

        if len(arg_list) != 1 and len(arg_list) != 3 and len(arg_list) != 4:
            print("usage: ovs_dump_ovs_list <struct ovs_list *> "
                  "{[<structure>] [<member>] {dump}]}")
            return

        header = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct ovs_list').pointer())

        if len(arg_list) >= 3:
            typeobj = arg_list[1]
            member = arg_list[2]
            if len(arg_list) == 4 and arg_list[3] == "dump":
                dump = True

        for node in ForEachLIST(header.dereference()):
            if typeobj is None or member is None:
                print("(struct ovs_list *) {}".format(node))
            else:
                print("({} *) {} {}".format(
                    typeobj,
                    container_of(node,
                                 gdb.lookup_type(typeobj).pointer(), member),
                    "=" if dump else ""))
                if dump:
                    print("  {}\n".format(container_of(
                        node,
                        gdb.lookup_type(typeobj).pointer(),
                        member).dereference()))


#
# Implements the GDB "ovs_dump_cmap" command
#
class CmdDumpCmap(gdb.Command):
    """Dump all nodes of a given cmap
    Usage:
      ovs_dump_cmap <struct cmap *> {[<structure>] [<member>] {dump}]}

    For example dump all the rules in a dpcls_subtable:

    (gdb) ovs_dump_cmap &subtable->rules
    (struct cmap *) 0x3e02758

    This is not very useful, so please use this with the container_of mode:

    (gdb) ovs_dump_cmap &subtable->rules "struct dpcls_rule" cmap_node
    (struct dpcls_rule *) 0x3e02758

    Now you can manually use the print command to show the content, or use the
    dump option to dump the structure for all nodes:

    (gdb) ovs_dump_cmap &subtable->rules "struct dpcls_rule" cmap_node dump
    (struct dpcls_rule *) 0x3e02758 =
    {cmap_node = {next = {p = 0x0}}, mask = 0x3dfe100, flow = {hash = ...
    """
    def __init__(self):
        super(CmdDumpCmap, self).__init__("ovs_dump_cmap",
                                          gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        typeobj = None
        member = None
        dump = False

        if len(arg_list) != 1 and len(arg_list) != 3 and len(arg_list) != 4:
            print("usage: ovs_dump_cmap <struct cmap *> "
                  "{[<structure>] [<member>] {dump}]}")
            return

        cmap = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct cmap').pointer())

        if len(arg_list) >= 3:
            typeobj = arg_list[1]
            member = arg_list[2]
            if len(arg_list) == 4 and arg_list[3] == "dump":
                dump = True

        for node in ForEachCMAP(cmap.dereference()):
            if typeobj is None or member is None:
                print("(struct cmap *) {}".format(node))
            else:
                print("({} *) {} {}".format(
                    typeobj,
                    container_of(node,
                                 gdb.lookup_type(typeobj).pointer(), member),
                    "=" if dump else ""))
                if dump:
                    print("  {}\n".format(container_of(
                        node,
                        gdb.lookup_type(typeobj).pointer(),
                        member).dereference()))


#
# Implements the GDB "ovs_dump_hmap" command
#
class CmdDumpHmap(gdb.Command):
    """Dump all nodes of a given hmap
    Usage:
      ovs_dump_hmap <struct hmap *> <structure> <member> {dump}

    For example dump all the bridges when the all_bridges variable is
    optimized out due to LTO:

    (gdb) ovs_dump_hmap "&'all_bridges.lto_priv.0'" "struct bridge" "node"
    (struct bridge *) 0x55ec43069c70
    (struct bridge *) 0x55ec430428a0
    (struct bridge *) 0x55ec430a55f0

    The 'dump' option will also include the full structure content in the
    output.
    """
    def __init__(self):
        super(CmdDumpHmap, self).__init__("ovs_dump_hmap",
                                          gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        typeobj = None
        member = None
        dump = False

        if len(arg_list) != 3 and len(arg_list) != 4:
            print("usage: ovs_dump_hmap <struct hmap *> "
                  "<structure> <member> {dump}")
            return

        hmap = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct hmap').pointer())

        typeobj = arg_list[1]
        member = arg_list[2]
        if len(arg_list) == 4 and arg_list[3] == "dump":
            dump = True

        for node in ForEachHMAP(hmap.dereference(), typeobj, member):
            print("({} *) {} {}".format(typeobj, node, "=" if dump else ""))
            if dump:
                print("  {}\n".format(node.dereference()))


#
# Implements the GDB "ovs_dump_simap" command
#
class CmdDumpSimap(gdb.Command):
    """Dump all key, value entries of a simap
    Usage:
      ovs_dump_simap <struct simap *>
    """

    def __init__(self):
        super(CmdDumpSimap, self).__init__("ovs_dump_simap",
                                           gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        if len(arg_list) != 1:
            print("ERROR: Missing argument!\n")
            print(self.__doc__)
            return

        simap = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct simap').pointer())

        values = dict()
        max_name_len = 0
        for name, value in ForEachSIMAP(simap.dereference()):
            values[name.string()] = int(value)
            if len(name.string()) > max_name_len:
                max_name_len = len(name.string())

        for name in sorted(values.keys()):
            print("{}: {} / 0x{:x}".format(name.ljust(max_name_len),
                                           values[name], values[name]))


#
# Implements the GDB "ovs_dump_smap" command
#
class CmdDumpSmap(gdb.Command):
    """Dump all key, value pairs of a smap
    Usage:
      ovs_dump_smap <struct smap *>
    """

    def __init__(self):
        super(CmdDumpSmap, self).__init__("ovs_dump_smap",
                                          gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        if len(arg_list) != 1:
            print("ERROR: Missing argument!\n")
            print(self.__doc__)
            return

        smap = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct smap').pointer())

        values = dict()
        max_key_len = 0
        for key, value in ForEachSMAP(smap.dereference()):
            values[key.string()] = value.string()
            if len(key.string()) > max_key_len:
                max_key_len = len(key.string())

        for key in sorted(values.keys()):
            print("{}: {}".format(key.ljust(max_key_len),
                                  values[key]))


#
# Implements the GDB "ovs_dump_udpif_keys" command
#
class CmdDumpUdpifKeys(gdb.Command):
    """Dump all nodes of an ovs_list give
    Usage:
      ovs_dump_udpif_keys {<udpif_name>|<udpif_address>} {short}

      <udpif_name>    : Full name of the udpif's dpif to dump
      <udpif_address> : Address of the udpif structure to dump. If both the
                        <udpif_name> and <udpif_address> are omitted the
                        available udpif structures are displayed.
      short           : Only dump ukey structure addresses, no content details
      no_count        : Do not count the number of ukeys, as it might be slow
    """

    def __init__(self):
        super(CmdDumpUdpifKeys, self).__init__("ovs_dump_udpif_keys",
                                               gdb.COMMAND_DATA)

    def count_all_ukeys(self, udpif):
        count = 0
        spinner = ProgressIndicator("Counting all ukeys: ")

        for j in range(0, N_UMAPS):
            spinner.update()
            count += udpif['ukeys'][j]['cmap']['impl']['p']['n']

        spinner.done()
        return count

    def dump_all_ukeys(self, udpif, indent=0, short=False):
        indent = " " * indent
        spinner = ProgressIndicator("Walking ukeys: ")
        for j in range(0, N_UMAPS):
            spinner.update()
            if udpif['ukeys'][j]['cmap']['impl']['p']['n'] != 0:
                spinner.pause()
                print("{}(struct umap *) {}:".
                      format(indent, udpif['ukeys'][j].address))
                for ukey in ForEachCMAP(udpif['ukeys'][j]['cmap'],
                                        "struct udpif_key", "cmap_node"):

                    base_str = "{}  (struct udpif_key *) {}: ". \
                        format(indent, ukey)
                    if short:
                        print(base_str)
                        continue

                    print("{}key_len = {}, mask_len = {}".
                          format(base_str, ukey['key_len'], ukey['mask_len']))

                    indent_b = " " * len(base_str)
                    if ukey['ufid_present']:
                        print("{}ufid = {}".
                              format(
                                  indent_b, str(uuid.UUID(
                                      "{:08x}{:08x}{:08x}{:08x}".
                                      format(int(ukey['ufid']['u32'][3]),
                                             int(ukey['ufid']['u32'][2]),
                                             int(ukey['ufid']['u32'][1]),
                                             int(ukey['ufid']['u32'][0]))))))

                    print("{}hash = 0x{:8x}, pmd_id = {}".
                          format(indent_b, int(ukey['hash']), ukey['pmd_id']))
                    print("{}state = {}".format(indent_b, ukey['state']))
                    print("{}n_packets = {}, n_bytes = {}".
                          format(indent_b,
                                 ukey['stats']['n_packets'],
                                 ukey['stats']['n_bytes']))
                    print("{}used = {}, tcp_flags = 0x{:04x}".
                          format(indent_b,
                                 ukey['stats']['used'],
                                 int(ukey['stats']['tcp_flags'])))

                    #
                    # TODO: Would like to add support for dumping key, mask
                    #       actions, and xlate_cache
                    #
                    # key = ""
                    # for nlattr in ForEachNL(ukey['key'], ukey['key_len']):
                    #     key += "{}{}".format(
                    #         "" if len(key) == 0 else ", ",
                    #         nlattr['nla_type'].cast(
                    #             gdb.lookup_type('enum ovs_key_attr')))
                    # print("{}key attributes = {}".format(indent_b, key))
                spinner.resume()
        spinner.done()

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)
        all_udpifs = get_global_variable('all_udpifs')
        no_count = "no_count" in arg_list

        if all_udpifs is None:
            return

        udpifs = dict()
        for udpif in ForEachLIST(all_udpifs, "struct udpif", "list_node"):
            udpifs[udpif['dpif']['full_name'].string()] = udpif

            if len(arg_list) == 0 or (
                    len(arg_list) == 1 and arg_list[0] == "no_count"):
                print("(struct udpif *) {}: name = {}, total keys = {}".
                      format(udpif, udpif['dpif']['full_name'].string(),
                             self.count_all_ukeys(udpif) if not no_count
                             else "<not counted!>"))

        if len(arg_list) == 0 or (
                len(arg_list) == 1 and arg_list[0] == "no_count"):
            return

        if arg_list[0] in udpifs:
            udpif = udpifs[arg_list[0]]
        else:
            try:
                udpif = gdb.parse_and_eval(arg_list[0]).cast(
                    gdb.lookup_type('struct udpif').pointer())
            except Exception:
                udpif = None

        if udpif is None:
            print("Can't find provided udpif address!")
            return

        self.dump_all_ukeys(udpif, 0, "short" in arg_list[1:])


#
# Implements the GDB "ovs_show_fdb" command
#
class CmdShowFDB(gdb.Command):
    """Show FDB information
    Usage:
      ovs_show_fdb {<bridge_name> {dbg} {hash}}

       <bridge_name> : Optional bridge name, if not supplied FDB summary
                       information is displayed for all bridges.
       dbg           : Will show structure address information
       hash          : Will display the forwarding table using the hash
                       table, rather than the rlu list.
    """

    def __init__(self):
        super(CmdShowFDB, self).__init__("ovs_show_fdb",
                                         gdb.COMMAND_DATA)

    @staticmethod
    def __get_port_name_num(mac_entry):
        if mac_entry['mlport'] is not None:
            port = mac_entry['mlport']['port'].cast(
                gdb.lookup_type('struct ofbundle').pointer())

            port_name = port['name'].string()
            port_no = int(container_of(
                port['ports']['next'],
                gdb.lookup_type('struct ofport_dpif').pointer(),
                'bundle_node')['up']['ofp_port'])

            if port_no == 0xfff7:
                port_no = "UNSET"
            elif port_no == 0xfff8:
                port_no = "IN_PORT"
            elif port_no == 0xfff9:
                port_no = "TABLE"
            elif port_no == 0xfffa:
                port_no = "NORMAL"
            elif port_no == 0xfffb:
                port_no = "FLOOD"
            elif port_no == 0xfffc:
                port_no = "ALL"
            elif port_no == 0xfffd:
                port_no = "CONTROLLER"
            elif port_no == 0xfffe:
                port_no = "LOCAL"
            elif port_no == 0xffff:
                port_no = "NONE"
            else:
                port_no = str(port_no)
        else:
            port_name = "-"
            port_no = "?"

        return port_name, port_no

    @staticmethod
    def display_ml_summary(ml, indent=0, dbg=False):
        indent = " " * indent
        if ml is None:
            return

        if dbg:
            print("[(struct mac_learning *) {}]".format(ml))

        print("{}table.n         : {}".format(indent, ml['table']['n']))
        print("{}secret          : 0x{:x}".format(indent, int(ml['secret'])))
        print("{}idle_time       : {}".format(indent, ml['idle_time']))
        print("{}max_entries     : {}".format(indent, ml['max_entries']))
        print("{}ref_count       : {}".format(indent, ml['ref_cnt']['count']))
        print("{}need_revalidate : {}".format(indent, ml['need_revalidate']))
        print("{}ports_by_ptr.n  : {}".format(indent, ml['ports_by_ptr']['n']))
        print("{}ports_by_usage.n: {}".format(indent,
                                              ml['ports_by_usage']['n']))
        print("{}total_learned   : {}".format(indent, ml['total_learned']))
        print("{}total_expired   : {}".format(indent, ml['total_expired']))
        print("{}total_evicted   : {}".format(indent, ml['total_evicted']))
        print("{}total_moved     : {}".format(indent, ml['total_moved']))

    @staticmethod
    def display_mac_entry(mac_entry, indent=0, dbg=False):
        port_name, port_no = CmdShowFDB.__get_port_name_num(mac_entry)

        line = "{}{:16.16}  {:-4}  {}  {:-9}".format(
            indent,
            "{}[{}]".format(port_no, port_name),
            int(mac_entry['vlan']),
            eth_addr_to_string(mac_entry['mac']),
            int(mac_entry['expires']))

        if dbg:
            line += " [(struct mac_entry *) {}]".format(mac_entry)

        print(line)

    @staticmethod
    def display_ml_entries(ml, indent=0, hash=False, dbg=False):
        indent = " " * indent
        if ml is None:
            return

        print("\n{}FDB \"{}\" table:".format(indent,
                                             "lrus" if not hash else "hash"))
        print("{}port               VLAN  MAC                Age out @".
              format(indent))
        print("{}-----------------  ----  -----------------  ---------".
              format(indent))

        mac_entries = 0

        if hash:
            for mac_entry in ForEachHMAP(ml['table'],
                                         "struct mac_entry",
                                         "hmap_node"):
                CmdShowFDB.display_mac_entry(mac_entry, len(indent), dbg)
                mac_entries += 1
        else:
            for mac_entry in ForEachLIST(ml['lrus'],
                                         "struct mac_entry",
                                         "lru_node"):
                CmdShowFDB.display_mac_entry(mac_entry, len(indent), dbg)
                mac_entries += 1

        print("\nTotal MAC entries: {}".format(mac_entries))
        time_now = list(get_time_now())
        time_now[1] = time_now[0] + time_now[1]
        print("\n{}Current time is between {} and {} seconds.\n".
              format(indent, min(time_now[0], time_now[1]),
                     max(time_now[0], time_now[1])))

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        all_ofproto_dpifs_by_name = get_global_variable(
            'all_ofproto_dpifs_by_name')
        if all_ofproto_dpifs_by_name is None:
            return

        all_name = dict()
        max_name_len = 0
        for node in ForEachHMAP(all_ofproto_dpifs_by_name,
                                "struct ofproto_dpif",
                                "all_ofproto_dpifs_by_name_node"):

            all_name[node['up']['name'].string()] = node
            if len(node['up']['name'].string()) > max_name_len:
                max_name_len = len(node['up']['name'].string())

        if len(arg_list) == 0:
            for name in sorted(all_name.keys()):
                print("{}: (struct mac_learning *) {}".
                      format(name.ljust(max_name_len),
                             all_name[name]['ml']))

                self.display_ml_summary(all_name[name]['ml'], 4)
        else:
            if not arg_list[0] in all_name:
                print("ERROR: Given bridge name is not known!")
                return

            ml = all_name[arg_list[0]]['ml']
            self.display_ml_summary(ml, 0, "dbg" in arg_list[1:])
            self.display_ml_entries(ml, 0, "hash" in arg_list[1:],
                                    "dbg" in arg_list[1:])


#
# Implements the GDB "ovs_show_fdb" command
#
class CmdShowUpcall(gdb.Command):
    """Show upcall information
    Usage:
      ovs_show_upcall {dbg}

      dbg  : Will show structure address information
    """

    def __init__(self):
        super(CmdShowUpcall, self).__init__("ovs_show_upcall",
                                            gdb.COMMAND_DATA)

    @staticmethod
    def display_udpif_upcall(udpif, indent=0, dbg=False):
        indent = " " * indent

        enable_ufid = get_global_variable('enable_ufid')
        if enable_ufid is None:
            return

        dbg_str = ""
        if dbg:
            dbg_str = ", ((struct udpif *) {})".format(udpif)

        print("{}{}{}:".format(
            indent, udpif['dpif']['full_name'].string(),
            dbg_str))

        print("{}  flows         : (current {}) (avg {}) (max {}) (limit {})".
              format(indent, udpif['n_flows'], udpif['avg_n_flows'],
                     udpif['max_n_flows'], udpif['flow_limit']))
        print("{}  dump duration : {}ms".
              format(indent, udpif['dump_duration']))
        print("{}  ufid enabled  : {}\n".
              format(indent, enable_ufid &
                     udpif['backer']['rt_support']['ufid']))

        for i in range(0, int(udpif['n_revalidators'])):
            revalidator = udpif['revalidators'][i]

            dbg_str = ""
            if dbg:
                dbg_str = ", ((struct revalidator *) {})".\
                    format(revalidator.address)

            count = 0
            j = i
            spinner = ProgressIndicator("Counting all ukeys: ")
            while j < N_UMAPS:
                spinner.update()
                count += udpif['ukeys'][j]['cmap']['impl']['p']['n']
                j += int(udpif['n_revalidators'])

            spinner.done()
            print("{}  {}: (keys {}){}".
                  format(indent, revalidator['id'], count, dbg_str))

        print("")

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        all_udpifs = get_global_variable('all_udpifs')
        if all_udpifs is None:
            return

        for udpif in ForEachLIST(all_udpifs, "struct udpif", "list_node"):
            self.display_udpif_upcall(udpif, 0, "dbg" in arg_list)


#
# Implements the GDB "ovs_dump_ofpacts" command
#
class CmdDumpOfpacts(gdb.Command):
    """Dump all actions in an ofpacts set
    Usage:
      ovs_dump_ofpacts <struct ofpact *> <ofpacts_len>

       <struct ofpact *> : Pointer to set of ofpact structures.
       <ofpacts_len>     : Total length of the set.

    Example dumping all actions when in the clone_xlate_actions() function:

    (gdb) ovs_dump_ofpacts actions actions_len
    (struct ofpact *) 0x87c8: {type = OFPACT_SET_FIELD, raw = 255 '', len = 24}
    (struct ofpact *) 0x87e0: {type = OFPACT_SET_FIELD, raw = 255 '', len = 24}
    (struct ofpact *) 0x87f8: {type = OFPACT_SET_FIELD, raw = 255 '', len = 24}
    (struct ofpact *) 0x8810: {type = OFPACT_SET_FIELD, raw = 255 '', len = 32}
    (struct ofpact *) 0x8830: {type = OFPACT_SET_FIELD, raw = 255 '', len = 24}
    (struct ofpact *) 0x8848: {type = OFPACT_RESUBMIT, raw = 38 '&', len = 16}
    """
    def __init__(self):
        super(CmdDumpOfpacts, self).__init__("ovs_dump_ofpacts",
                                             gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        arg_list = gdb.string_to_argv(arg)

        if len(arg_list) != 2:
            print("usage: ovs_dump_ofpacts <struct ofpact *> <ofpacts_len>")
            return

        ofpacts = gdb.parse_and_eval(arg_list[0]).cast(
            gdb.lookup_type('struct ofpact').pointer())

        length = gdb.parse_and_eval(arg_list[1])

        for node in ForEachOFPACTS(ofpacts, length):
            print("(struct ofpact *) {}: {}".format(node, node.dereference()))


#
# Implements the GDB "ovs_dump_packets" command
#
class CmdDumpPackets(gdb.Command):
    """Dump metadata about dp_packets
    Usage:
      ovs_dump_packets <struct dp_packet_batch|dp_packet> [tcpdump options]

    This command can take either a dp_packet_batch struct and print out
    metadata about all packets in this batch, or a single dp_packet struct and
    print out metadata about a single packet.

    Everything after the struct reference is passed into tcpdump. If nothing
    is passed in as a tcpdump option, the default is "-n".

    (gdb) ovs_dump_packets packets_
    12:01:05.981214 ARP, Ethernet (len 6), IPv4 (len 4), Reply 10.1.1.1 is-at
        a6:0f:c3:f0:5f:bd (oui Unknown), length 28
    """
    def __init__(self):
        super().__init__("ovs_dump_packets", gdb.COMMAND_DATA)

    def invoke(self, arg, from_tty):
        if Ether is None:
            print("ERROR: This command requires scapy to be installed.")
            return

        arg_list = gdb.string_to_argv(arg)
        if len(arg_list) == 0:
            print("Usage: ovs_dump_packets <struct dp_packet_batch|"
                  "dp_packet> [tcpdump options]")
            return

        symb_name = arg_list[0]
        tcpdump_args = arg_list[1:]

        if not tcpdump_args:
            # Add a sane default
            tcpdump_args = ["-n"]

        val = gdb.parse_and_eval(symb_name)
        while val.type.code == gdb.TYPE_CODE_PTR:
            val = val.dereference()

        pkt_list = []
        if str(val.type).startswith("struct dp_packet_batch"):
            for idx in range(val['count']):
                pkt_struct = val['packets'][idx].dereference()
                pkt = self.extract_pkt(pkt_struct)
                if pkt is None:
                    continue
                pkt_list.append(pkt)
        elif str(val.type) == "struct dp_packet":
            pkt = self.extract_pkt(val)
            if pkt is None:
                return
            pkt_list.append(pkt)
        else:
            print("Error, unsupported argument type: {}".format(str(val.type)))
            return

        stdout = tcpdump(pkt_list, args=tcpdump_args, getfd=True, quiet=True)
        gdb.write(stdout.read().decode("utf8", "replace"))

    def extract_pkt(self, pkt):
        pkt_fields = pkt.type.keys()
        if pkt['packet_type'] != 0:
            return
        if pkt['l3_ofs'] == 0xFFFF:
            return

        if "mbuf" in pkt_fields:
            if pkt['mbuf']['data_off'] == 0xFFFF:
                return
            eth_ptr = pkt['mbuf']['buf_addr']
            eth_off = int(pkt['mbuf']['data_off'])
            eth_len = int(pkt['mbuf']['pkt_len'])
        else:
            if pkt['data_ofs'] == 0xFFFF:
                return
            eth_ptr = pkt['base_']
            eth_off = int(pkt['data_ofs'])
            eth_len = int(pkt['size_'])

        if eth_ptr == 0 or eth_len < 1:
            return

        # Extract packet
        pkt_ptr = eth_ptr.cast(
                gdb.lookup_type('uint8_t').pointer()
            )
        pkt_ptr += eth_off

        pkt_data = []
        for idx in range(eth_len):
            pkt_data.append(int(pkt_ptr[idx]))

        pkt_data = struct.pack("{}B".format(eth_len), *pkt_data)

        packet = Ether(pkt_data)
        packet.len = int(eth_len)

        return packet


#
# Initialize all GDB commands
#
CmdDumpBridge()
CmdDumpBridgePorts()
CmdDumpDpNetdev()
CmdDumpDpNetdevPollThreads()
CmdDumpDpNetdevPorts()
CmdDumpDpProvider()
CmdDumpNetdev()
CmdDumpNetdevProvider()
CmdDumpOfpacts()
CmdDumpOvsList()
CmdDumpPackets()
CmdDumpCmap()
CmdDumpHmap()
CmdDumpSimap()
CmdDumpSmap()
CmdDumpUdpifKeys()
CmdShowFDB()
CmdShowUpcall()