-
Notifications
You must be signed in to change notification settings - Fork 43
/
vnx_utils.py
executable file
·930 lines (759 loc) · 32.2 KB
/
vnx_utils.py
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
# Copyright (c) 2020-2022, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
__author__ = "Mario Ruiz"
__copyright__ = "Copyright 2020-2022, Xilinx Inc."
__email__ = "[email protected]"
from pynq import DefaultIP
from pynq.utils import ReprDict
import numpy as np
import ipaddress
from enum import Enum
def _slice_word(value, index, width=1):
"""
Slices a width-word from an integer
Parameters
----------
value: int
input word
index : int
start bit index in the output word
width: int
number of bits of the output word
Returns
-------
An integer with the sliced word
"""
if not isinstance(value, int):
raise ValueError("value must be integer.")
if not isinstance(index, int):
raise ValueError("index must be integer.")
if not isinstance(width, int):
raise ValueError("width must be integer.")
elif width < 0:
raise ValueError("width cannot be negative.")
return (value >> index) & ((2 ** width) - 1)
_cmac_modes = {
0: 'CAUI10',
1: 'CAUI4',
2: 'Runtime Switchable CAUI10',
3: 'Runtime Switchable CAUI4'
}
class CMAC(DefaultIP):
"""This class wrapps the common function of the CMAC IP
"""
bindto = ["xilinx.com:kernel:cmac_0:1.0",
"xilinx.com:kernel:cmac_1:1.0"]
def __init__(self, description):
super().__init__(description=description)
self._fullpath = description['fullpath']
self.start = self.start_sw = self.start_none = \
self.start_ert = self.call
def _setup_packet_prototype(self):
pass
def call(self, *args, **kwargs):
raise RuntimeError("{} is a free running kernel and cannot be "
"starter or called".format(self._fullpath))
def link_status(self, debug: bool=False) -> dict:
"""Current CMAC link status
Parameters
----------
debug: bool
if enable provides more information
Returns
-------
A dictionary with link status, more status information
is returned if debug == True
"""
if not isinstance(debug, bool):
raise ValueError("debug must be a bool type")
# The first time these registers are not populated properly,
# read them twice to get real value
for _ in range(2):
rx_status = int(self.register_map.stat_rx_status)
tx_status = int(self.register_map.stat_tx_status)
status_dict = {}
status_dict["cmac_link"] = bool(_slice_word(rx_status, 0))
if debug:
status_dict["rx_status"] = bool(_slice_word(rx_status, 0))
status_dict["rx_aligned"] = bool(_slice_word(rx_status, 1))
status_dict["rx_misaligned"] = bool(_slice_word(rx_status, 2))
status_dict["rx_aligned_err"] = bool(_slice_word(rx_status, 3))
status_dict["rx_hi_ber"] = bool(_slice_word(rx_status, 4))
status_dict["rx_remote_fault"] = bool(_slice_word(rx_status, 5))
status_dict["rx_local_fault"] = bool(_slice_word(rx_status, 6))
status_dict["rx_got_signal_os"] = bool(_slice_word(rx_status, 14))
status_dict["tx_local_fault"] = bool(_slice_word(tx_status, 0))
return status_dict
def copy_stats(self) -> None:
"""Triggers a snapshot of CMAC Statistics
Triggers a snapshot of all the Statistics counters into their
readable register. The bit self-clears.
"""
self.register_map.stat_pm_tick = 1
def get_stats(self, update_reg: bool=True) -> dict:
""" Return a dictionary with the CMAC stats
Parameters
----------
debug: bool
if enabled, the CMAC registers are copied from internal counters
Returns
-------
A dictionary with the CMAC statistics
"""
if update_reg:
self.copy_stats()
rmap = self.register_map
stats_dict = dict()
stats_dict['tx'] = dict()
stats_dict['rx'] = dict()
stats_dict['cycle_count'] = int(rmap.stat_cycle_count)
# Tx
stats_dict['tx'] = {
"packets": int(rmap.stat_tx_total_packets),
"good_packets": int(rmap.stat_tx_total_good_packets),
"bytes": int(rmap.stat_tx_total_bytes),
"good_bytes": int(rmap.stat_tx_total_good_bytes),
"packets_64B": int(rmap.stat_tx_total_packets_64B),
"packets_65_127B": int(rmap.stat_tx_total_packets_65_127B),
"packets_128_255B": int(rmap.stat_tx_total_packets_128_255B),
"packets_256_511B": int(rmap.stat_tx_total_packets_256_511B),
"packets_512_1023B": int(rmap.stat_tx_total_packets_512_1023B),
"packets_1024_1518B": int(rmap.stat_tx_total_packets_1024_1518B),
"packets_1519_1522B": int(rmap.stat_tx_total_packets_1519_1522B),
"packets_1523_1548B": int(rmap.stat_tx_total_packets_1523_1548B),
"packets_1549_2047B": int(rmap.stat_tx_total_packets_1549_2047B),
"packets_2048_4095B": int(rmap.stat_tx_total_packets_2048_4095B),
"packets_4096_8191B": int(rmap.stat_tx_total_packets_4096_8191B),
"packets_8192_9215B": int(rmap.stat_tx_total_packets_8192_9215B),
"packets_large": int(rmap.stat_tx_total_packets_large),
"packets_small": int(rmap.stat_tx_total_packets_small),
"bad_fcs": int(rmap.stat_tx_total_bad_fcs),
"pause": int(rmap.stat_tx_pause),
"user_pause": int(rmap.stat_tx_user_pause),
}
stats_dict['rx'] = {
"packets": int(rmap.stat_rx_total_packets),
"good_packets": int(rmap.stat_rx_total_good_packets),
"bytes": int(rmap.stat_rx_total_bytes),
"good_bytes": int(rmap.stat_rx_total_good_bytes),
"packets_64B": int(rmap.stat_rx_total_packets_64B),
"packets_65_127B": int(rmap.stat_rx_total_packets_65_127B),
"packets_128_255B": int(rmap.stat_rx_total_packets_128_255B),
"packets_256_511B": int(rmap.stat_rx_total_packets_256_511B),
"packets_512_1023B": int(rmap.stat_rx_total_packets_512_1023B),
"packets_1024_1518B": int(rmap.stat_rx_total_packets_1024_1518B),
"packets_1519_1522B": int(rmap.stat_rx_total_packets_1519_1522B),
"packets_1523_1548B": int(rmap.stat_rx_total_packets_1523_1548B),
"packets_1549_2047B": int(rmap.stat_rx_total_packets_1549_2047B),
"packets_2048_4095B": int(rmap.stat_rx_total_packets_2048_4095B),
"packets_4096_8191B": int(rmap.stat_rx_total_packets_4096_8191B),
"packets_8192_9215B": int(rmap.stat_rx_total_packets_8192_9215B),
"packets_large": int(rmap.stat_rx_total_packets_large),
"packets_small": int(rmap.stat_rx_total_packets_small),
"packets_undersize": int(rmap.stat_rx_total_packets_undersize),
"packets_fragmented": int(rmap.stat_rx_total_packets_fragmented),
"packets_oversize": int(rmap.stat_rx_total_packets_oversize),
"packets_toolong": int(rmap.stat_rx_total_packets_toolong),
"packets_jabber": int(rmap.stat_rx_total_packets_jabber),
"bad_fcs": int(rmap.stat_rx_total_bad_fcs),
"packets_bad_fcs": int(rmap.stat_rx_packets_bad_fcs),
"stomped_fcs": int(rmap.stat_rx_stomped_fcs),
"pause": int(rmap.stat_rx_pause),
"user_pause": int(rmap.stat_rx_user_pause),
}
return ReprDict(stats_dict, rootname='cmac_stats')
@property
def version(self):
"""Returns the CMAC Core version
"""
version = int(self.register_map.version)
return str(_slice_word(version, 8, 8)) + '.' \
+ str(_slice_word(version, 0, 8))
@property
def mode(self):
"""Returns the CMAC Core mode
"""
mode = int(self.register_map.core_mode) & 0x3
return _cmac_modes[mode]
@property
def loopback(self):
""" GT Loopback
False: normal operation
True: GT internal loopback
"""
return bool(int(self.register_map.gt_loopback) & 0x1)
@loopback.setter
def loopback(self, operation):
if not isinstance(operation, (int, bool)):
raise ValueError("Operation must be int or bool")
self.register_map.gt_loopback = int(bool(operation))
@property
def rsfec(self):
""" RS-FEC
False: RS-FEC disabled
True: RS-FEC enabled
"""
return int(self.register_map.rsfec_config_enable) == 0x3
@rsfec.setter
def rsfec(self, operation):
if not isinstance(operation, (int, bool)):
raise ValueError("Operation must be int or bool")
# set RSFEC sub-mode 1 (correction and indication)
if operation:
self.register_map.rsfec_config_enable = 0x3
self.register_map.rsfec_config_ind_corr = 7
self.register_map.reset_reg = 0xC0000000
self.register_map.reset_reg = 0
else:
self.register_map.rsfec_config_enable = 0
self.register_map.rsfec_config_ind_corr = 0
self.register_map.reset_reg = 0xC0000000
self.register_map.reset_reg = 0
def _byte_ordering_endianess(num, length=4):
"""
Convert from little endian to big endian and vice versa
Parameters
----------
num: int
input number
length:
number of bytes of the input number
Returns
-------
An integer with the endianness changed with respect to input number
"""
if not isinstance(num, int):
raise ValueError("num must be an integer")
if not isinstance(length, int):
raise ValueError("length must be an positive integer")
elif length < 0:
raise ValueError("length cannot be negative")
aux = 0
for i in range(length):
byte_index = num >> ((length - 1 - i) * 8) & 0xFF
aux += byte_index << (i * 8)
return aux
class NetworkLayer(DefaultIP):
"""This class wraps the common function of the Network Layer IP
"""
bindto = ["xilinx.com:kernel:networklayer:1.0"]
_socketType = np.dtype(
[
("theirIP", np.unicode_, 16),
("theirPort", np.uint16),
("myPort", np.uint16),
("valid", bool),
]
)
def __init__(self, description):
super().__init__(description=description)
self._fullpath = description['fullpath']
self.start = self.start_sw = self.start_none = \
self.start_ert = self.call
self.sockets = np.zeros(16, dtype=self._socketType)
self.freq = None
def _setup_packet_prototype(self):
pass
def call(self, *args, **kwargs):
raise RuntimeError("{} is a free running kernel and cannot be "
"starter or called".format(self._fullpath))
def populate_socket_table(self, debug=False):
"""
Populate a socket table
Optionals
---------
debug: bool
If enables read the current status of the UDP Table
Returns
-------
If debug is enable read the current status of the UDP Table
"""
theirIP_offset = self.register_map.udp_theirIP_offset.address
theirPort_offset = self.register_map.udp_theirPort_offset.address
udp_myPort_offset = self.register_map.udp_myPort_offset.address
udp_valid_offset = self.register_map.udp_valid_offset.address
numSocketsHW = int(self.register_map.udp_number_sockets)
if numSocketsHW < len(self.sockets):
raise Exception(
"Socket list length ({}) is bigger than the \
number of sockets in hardware ({})".format(
len(self.sockets), numSocketsHW
)
)
# Iterate over the socket object
for i in range(numSocketsHW):
ti_offset = theirIP_offset + i * 8
tp_offset = theirPort_offset + i * 8
mp_offset = udp_myPort_offset + i * 8
v_offset = udp_valid_offset + i * 8
theirIP = 0
if self.sockets[i]["theirIP"]:
theirIP = int(ipaddress.IPv4Address(self.sockets[i]
["theirIP"]))
self.write(ti_offset, theirIP)
self.write(tp_offset, int(self.sockets[i]["theirPort"]))
self.write(mp_offset, int(self.sockets[i]["myPort"]))
self.write(v_offset, int(self.sockets[i]["valid"]))
if debug:
return self.get_socket_table()
def get_socket_table(self) -> dict:
""" Reads the socket table
Returns
-------
Returns socket table
"""
theirIP_offset = self.register_map.udp_theirIP_offset.address
theirPort_offset = self.register_map.udp_theirPort_offset.address
udp_myPort_offset = self.register_map.udp_myPort_offset.address
udp_valid_offset = self.register_map.udp_valid_offset.address
numSocketsHW = int(self.register_map.udp_number_sockets)
socket_dict = dict()
socket_dict['Number of Sockets'] = numSocketsHW
socket_dict['socket'] = dict()
# Iterate over all the UDP table
for i in range(numSocketsHW):
ti_offset = theirIP_offset + i * 8
tp_offset = theirPort_offset + i * 8
mp_offset = udp_myPort_offset + i * 8
v_offset = udp_valid_offset + i * 8
isvalid = self.read(v_offset)
if isvalid:
ti = self.read(ti_offset)
tp = self.read(tp_offset)
mp = self.read(mp_offset)
socket_dict['socket'][i] = dict()
socket_dict['socket'][i]['theirIP'] = \
str(ipaddress.IPv4Address(ti))
socket_dict['socket'][i]['theirPort'] = tp
socket_dict['socket'][i]['myPort'] = mp
return ReprDict(socket_dict, rootname='socket_table')
def invalidate_socket_table(self):
""" Clear the Socket table """
udp_valid_offset = self.register_map.udp_valid_offset.address
numSocketsHW = int(self.register_map.udp_number_sockets)
for i in range(numSocketsHW):
self.write(int(udp_valid_offset + i * 8), 0)
def get_arp_table(self, num_entries=256) -> dict:
"""Read the ARP table from the FPGA return a dict
Parameters
----------
Optionals
---------
num_entries: int
number of entries in the table to be consider when printing
Returns
-------
Prints the content of valid entries in the ARP in a friendly way
"""
if not isinstance(num_entries, int):
raise ValueError("Number of entries must be integer.")
elif num_entries < 0:
raise ValueError("Number of entries cannot be negative.")
elif num_entries > 256:
raise ValueError("Number of entries cannot be bigger than 256.")
mac_addr_offset = self.register_map.arp_mac_addr_offset.address
ip_addr_offset = self.register_map.arp_ip_addr_offset.address
valid_addr_offset = self.register_map.arp_valid_offset.address
table = dict()
valid_entry = None
for i in range(num_entries):
if (i % 4) == 0:
valid_entry = self.read(valid_addr_offset + (i // 4) * 4)
isvalid = (valid_entry >> ((i % 4) * 8)) & 0x1
if isvalid:
mac_lsb = self.read(mac_addr_offset + (i * 2 * 4))
mac_msb = self.read(mac_addr_offset + ((i * 2 + 1) * 4))
ip_addr = self.read(ip_addr_offset + (i * 4))
mac_addr = (2 ** 32) * mac_msb + mac_lsb
mac_hex = "{:012x}".format(
_byte_ordering_endianess(mac_addr, 6))
mac_str = ":".join(
mac_hex[i: i + 2] for i in range(0, len(mac_hex), 2)
)
ip_addr_print = _byte_ordering_endianess(ip_addr)
table[i] = {
"MAC address": mac_str,
"IP address": str(ipaddress.IPv4Address(ip_addr_print))
}
return ReprDict(table, rootname='ARP Table')
def write_arp_entry(self, mac: str, ip: str):
"""
Add an entry to the ARP table
Parameters
----------
mac: str
MAC address in the format XX:XX:XX:XX:XX:XX
ip: str
IP address in the format XXX.XXX.XXX.XXX
Note, VNx requires all IPs in the ARP table to be in the same
/24 subnet (mask 255.255.255.0) as the IP assigned to the FPGA port.
There are 256 entries in the ARP table, one for each possible IP
in the subnet, the least significant 8 bits of the IP are used to
index into the ARP table.
"""
if not isinstance(mac, str):
raise ValueError("MAC address must be a string.")
elif not isinstance(ip, str):
raise ValueError("IP address must be a string.")
mac_int = int("0x{}".format(mac.replace(":", "")), 16)
big_mac_int = _byte_ordering_endianess(mac_int, 6)
mac_msb = (big_mac_int >> 32) & 0xFFFFFFFF
mac_lsb = big_mac_int & 0xFFFFFFFF
ip_int = int(ipaddress.IPv4Address(ip))
big_ip_int = _byte_ordering_endianess(ip_int, 4)
mac_addr_offset = self.register_map.arp_mac_addr_offset.address
ip_addr_offset = self.register_map.arp_ip_addr_offset.address
valid_addr_offset = self.register_map.arp_valid_offset.address
i = ip_int % 256
self.write(ip_addr_offset + (i * 4), big_ip_int)
self.write(mac_addr_offset + (i * 2 * 4), mac_lsb)
self.write(mac_addr_offset + ((i * 2 + 1) * 4), mac_msb)
# Valid
old_valid_entry = self.read(valid_addr_offset + (i // 4) * 4)
this_valid = 1 << ((i % 4) * 8)
self.write(valid_addr_offset + (i // 4) * 4,
old_valid_entry | this_valid)
def invalidate_arp_table(self):
"""
Clear the ARP table
"""
valid_addr_offset = self.register_map.arp_valid_offset.address
for i in range(0, 256//4, 4):
self.write(valid_addr_offset + i, 0)
def arp_discovery(self):
"""
Launch ARP discovery
"""
# The ARP discovery is trigger with the rising edge
self.register_map.arp_discovery = 0
self.register_map.arp_discovery = 1
self.register_map.arp_discovery = 0
def get_network_info(self) -> dict:
"""Returns a dictionary with the current configuration
"""
mac_addr = int(self.register_map.mac_address)
ip_addr = int(self.register_map.ip_address)
ip_gw = int(self.register_map.gateway)
ip_mask = int(self.register_map.ip_mask)
mac_hex = "{:012x}".format(mac_addr)
mac_str = ":".join(mac_hex[i: i + 2]
for i in range(0, len(mac_hex), 2))
config = {
"HWaddr": mac_str,
"inet addr": str(ipaddress.IPv4Address(ip_addr)),
"gateway addr": str(ipaddress.IPv4Address(ip_gw)),
"Mask": str(ipaddress.IPv4Address(ip_mask)),
}
return ReprDict(config, rootname='Network Information')
def set_ip_address(self, ipaddrsrt, gwaddr="None", debug=False):
"""
Update IP address as well as least significant octet of the
MAC address with the least significant octet of the IP address
Parameters
----------
ipaddrsrt : string
New IP address
gwaddr : string
New IP gateway address, if not defined a default gateway is used
debug: bool
if enable it will return the current configuration
Returns
-------
Current interface configuration only if debug == True
"""
if not isinstance(ipaddrsrt, str):
raise ValueError("ipaddrsrt must be an string type")
if not isinstance(gwaddr, str):
raise ValueError("gwaddr must be an string type")
if not isinstance(debug, bool):
raise ValueError("debug must be a bool type")
ipaddr = int(ipaddress.IPv4Address(ipaddrsrt))
self.register_map.ip_address = ipaddr
if gwaddr == "None":
self.register_map.gateway = (ipaddr & 0xFFFFFF00) + 1
else:
self.register_map.gateway = int(ipaddress.IPv4Address(gwaddr))
currentMAC = int(self.register_map.mac_address)
newMAC = (currentMAC & 0xFFFFFFFFF00) + (ipaddr & 0xFF)
self.register_map.mac_address = newMAC
if debug:
return self.get_network_info()
def set_mac_address(self, mac_addr: str):
""" Update the MAC address of the interface
Parameters
----------
mac_addr : str
MAC address in the format XX:XX:XX:XX:XX:XX
"""
if not isinstance(mac_addr, str):
raise ValueError("MAC address must be a string.")
mac_int = int("0x{}".format(mac_addr.replace(":", "")), 16)
self.register_map.mac_address = mac_int
def reset_debug_stats(self) -> None:
"""Reset debug probes
"""
self.register_map.debug_reset_counters = 1
@property
def get_debug_stats(self) -> dict:
""" Return a dictionary with the value of the Network Layer probes
"""
rmap = self.register_map
probes = dict()
probes["tx_path"] = dict()
probes["rx_path"] = dict()
probes["rx_path"] = {
"ethernet": {
"packets": int(rmap.eth_in_packets),
"bytes": int(rmap.eth_in_bytes),
"cycles": int(rmap.eth_in_cycles)
},
"packet_handler": {
"packets": int(rmap.pkth_in_packets),
"bytes": int(rmap.pkth_in_bytes),
"cycles": int(rmap.pkth_in_cycles)
},
"arp": {
"packets": int(rmap.arp_in_packets),
"bytes": int(rmap.arp_in_bytes),
"cycles": int(rmap.arp_in_cycles)
},
"icmp": {
"packets": int(rmap.icmp_in_packets),
"bytes": int(rmap.icmp_in_bytes),
"cycles": int(rmap.icmp_in_cycles)
},
"udp": {
"packets": int(rmap.udp_in_packets),
"bytes": int(rmap.udp_in_bytes),
"cycles": int(rmap.udp_in_cycles)
},
"app": {
"packets": int(rmap.app_in_packets),
"bytes": int(rmap.app_in_bytes),
"cycles": int(rmap.app_in_cycles)
}
}
probes['tx_path'] = {
"arp": {
"packets": int(rmap.arp_out_packets),
"bytes": int(rmap.arp_out_bytes),
"cycles": int(rmap.arp_out_cycles)
},
"icmp": {
"packets": int(rmap.icmp_out_packets),
"bytes": int(rmap.icmp_out_bytes),
"cycles": int(rmap.icmp_out_cycles)
},
"ethernet_header_inserter": {
"packets": int(rmap.ethhi_out_packets),
"bytes": int(rmap.ethhi_out_bytes),
"cycles": int(rmap.ethhi_out_cycles)
},
"ethernet": {
"packets": int(rmap.eth_out_packets),
"bytes": int(rmap.eth_out_bytes),
"cycles": int(rmap.eth_out_cycles)
},
"udp": {
"packets": int(rmap.udp_out_packets),
"bytes": int(rmap.udp_out_bytes),
"cycles": int(rmap.udp_out_cycles)
},
"app": {
"packets": int(rmap.app_out_packets),
"bytes": int(rmap.app_out_bytes),
"cycles": int(rmap.app_out_cycles)
}
}
return ReprDict(probes, rootname='debug_probes')
class TgMode(Enum):
"""Supported Traffic generator Modes"""
PRODUCER = 0
LATENCY = 1
LOOPBACK = 2
CONSUMER = 3
class TrafficGenerator(DefaultIP):
""" This class wraps the common function of the Traffic Generator IP
"""
bindto = ["xilinx.com:kernel:traffic_generator:1.0"]
def __init__(self, description):
super().__init__(description=description)
self.start = self._call = self._start_sw = self.start_sw = self.call = self._start_ert
self.freq = None
def _setup_packet_prototype(self):
pass
def _start_ert(self, mode: TgMode, dest: int=0, packets: int=None,
beats: int=None, tbwp: int=None):
"""Starts the Traffic generator
Parameters
----------
mode: TgMode
Operation mode
dest: int
Index in the socket table
Optional
--------
packets: int
Number of packets
num_beats: int
Number of transactions per piece of payload
tbwp:
Clock ticks between two consecutive payload packets
"""
if mode == TgMode.PRODUCER or mode == TgMode.LATENCY:
if packets is None:
raise RuntimeError("packets must be specified when mode is {}"
.format(mode))
elif beats is None:
raise RuntimeError("beats must be specified when mode is {}"
.format(mode))
elif tbwp is None:
raise RuntimeError("tbwp must be specified when mode is {}"
.format(mode))
self.register_map.number_packets = packets
self.register_map.number_beats = beats
self.register_map.time_between_packets = tbwp
self.register_map.mode = int(mode.value)
self.register_map.dest_id = dest
self.register_map.CTRL.AP_START = 1
def reset_fsm(self):
"""Reset internal FSM"""
self.register_map.reset_fsm = 1
def compute_app_throughput(self, direction: str="rx") -> float:
"""
Read the application monitoring registers and compute
throughput, it also returns other useful information
Parameters
----------
direction: string
'rx' or 'tx'
Returns
-------
Total number of packets seen by the monitoring probe,
throughput and total time
"""
if direction not in ["rx", "tx"]:
raise ValueError(
"Only 'rx' and 'tx' strings are supported \
on direction argument"
)
if direction == "rx":
tot_bytes = int(self.register_map.in_traffic_bytes)
tot_cycles = int(self.register_map.in_traffic_cycles)
tot_pkts = int(self.register_map.in_traffic_packets)
else:
tot_bytes = int(self.register_map.out_traffic_bytes)
tot_cycles = int(self.register_map.out_traffic_cycles)
tot_pkts = int(self.register_map.out_traffic_packets)
tot_time = (1 / (self.freq * 10 ** 6)) * tot_cycles
thr_bs = (tot_bytes * 8) / tot_time
return tot_pkts, thr_bs / (10 ** 9), tot_time
def reset_stats(self):
"""
Reset embedded probes
"""
self.register_map.debug_reset = 1
class DataMover(DefaultIP):
"""This class is an enhancement to the DefaultIP class to verify that the
underlaying hardware can work properly based on the provided arguments
This driver is bind to:
xilinx.com:hls:krnl_mm2s:1.0
xilinx.com:hls:krnl_s2mm:1.0
"""
bindto = ['xilinx.com:hls:krnl_mm2s:1.0', 'xilinx.com:hls:krnl_s2mm:1.0']
def __init__(self, description):
super().__init__(description=description)
self.start = self._start
def _start(self, *args, **kwargs):
"""Start the accelerator
This function will configure the accelerator with the provided
arguments and start the accelerator. Use the `wait` function to
determine when execution has finished. Note that buffers should be
flushed prior to starting the accelerator and any result buffers
will need to be invalidated afterwards.
For details on the function's signature use the `signature` property.
The type annotations provide the C types that the accelerator
operates on. Any pointer types should be passed as `ContiguousArray`
objects created from the `pynq.allocate` class. Scalars should be
passed as a compatible python type as used by the `struct` library.
"""
for idx, i in enumerate(self.signature.parameters.items()):
if i[0] == 'size' and args[idx] < 64:
raise ValueError("size must be at least 64-Byte")
elif i[0] == 'dest' and args[idx] > 15:
raise ValueError("dest cannot be bigger than 15")
if self.device.has_capability("ERT"):
return self._start_ert(*args, **kwargs)
else:
return self._start_sw(*args, **kwargs)
class CounterIP(DefaultIP):
""" This class wraps the common function of counter IP
"""
bindto = ["xilinx.com:hls:krnl_counters:1.0"]
def __init__(self, description):
super().__init__(description=description)
self._fullpath = description['fullpath']
self.start = self.start_sw = self.start_none = \
self.start_ert = self.call
def _setup_packet_prototype(self):
pass
def call(self, *args, **kwargs):
raise RuntimeError("{} is a free running kernel and cannot be "
"starter or called".format(self._fullpath))
@property
def counters(self):
""" Return counters
"""
counters = {
'packets': int(self.register_map.packets),
'beats': int(self.register_map.beats),
'bytes': int(self.register_map.bytes),
}
return counters
def reset_counters(self):
""" Reset internal counters
"""
self.register_map.reset = 0
self.register_map.reset = 1
self.register_map.reset = 0
class CollectorIP(DefaultIP):
""" This class wraps the common function the collector Kernel
"""
bindto = ["xilinx.com:hls:collector:1.0"]
def __init__(self, description):
super().__init__(description=description)
@property
def received_packets(self):
# When a register is written by the kernel for non free running kernels
# the default offset refers to the value that the kernel reads
# the actual register where the kernel writes is not exposed in the
# signature, so we need to compute the offset and use mmio to read it
rx_pkts_offset = self.register_map.received_packets.address + \
self.register_map.received_packets.width//8 + 4
return self.read(rx_pkts_offset)