Welcome to hwtLib’s generated documentation!

This documentation is automatically generated from source code on every push into master which pass testing. hwtLib is package of hardware components (like vhld/verilog library) for HWToolkit (hwt python3 package) it also contains commonly used helpers and types like uint64_t, UDP header etc. Library is structuralized mostly by main interface. Note that many compoments are parametrizable and do work with multiple interfaces.

The compoment is a class which inherits from Unit class. Interfaces are added in _declr() method and parameters in _config() method of unit class. For component there is usually the schematic, which can be opened from link under the name of the component in this documentation.

hwtLib package

Subpackages

hwtLib.abstract package

A package of abstract components (components which needs to have some methods implemented before use) and other utilities.

Subpackages
hwtLib.abstract.frame_utils package
Subpackages
hwtLib.abstract.frame_utils.join package
Submodules
hwtLib.abstract.frame_utils.join.fsm module
hwtLib.abstract.frame_utils.join.fsm.input_B_dst_to_fsm(word_bytes: int, input_cnt: int, input_B_dst: List[List[Set[Tuple[Tuple[int, int], int, int, int]]]], can_be_zero_len_frame: List[bool])[source]
Parameters
  • word_bytes – number of bytes in output word

  • input_cnt – number of input streams

  • input_B_dst – list with mapping of input bytes to a output bytes in each state

Format of input_B_dst is: List for each input
    in this list there are lists for each input byte
        in this list there are sets of byte destinations for each input byte
            byte destination is a tuple:
                state label, input index, time index, output byte index, input last flag
Note

input_B_dst is produced by hwtLib.amba.axis_comp.frame_utils.join.FrameJoinUtils.resolve_input_bytes_destinations()

hwtLib.abstract.frame_utils.join.fsm.is_from_different_input(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int])[source]
hwtLib.abstract.frame_utils.join.fsm.is_next_byte_from_same_input(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int])[source]
hwtLib.abstract.frame_utils.join.input_reg_val module
class hwtLib.abstract.frame_utils.join.input_reg_val.InputRegInputVal(parent_state_trans: StateTransItem)[source]

Bases: object

Container of values for FrameJoin input register

Variables
  • ~.parent – the StateTransItem instance which is owning this object

  • ~.keep – list of keep bits

  • ~.relict – flag for word which was partially consumed

  • ~.last – flag for end of frame

__init__(parent_state_trans: StateTransItem)[source]
__repr__()[source]

Return repr(self).

as_tuple()[source]
classmethod from_dict(parent_state_trans, d: Dict)[source]
is_exactly_different(other)[source]
hwtLib.abstract.frame_utils.join.input_reg_val.val__repr__None_as_X(v)[source]
hwtLib.abstract.frame_utils.join.input_reg_val.val_replace_X_with_None(v)[source]
hwtLib.abstract.frame_utils.join.state_trans_info module
class hwtLib.abstract.frame_utils.join.state_trans_info.StateTransInfo(label, word_bytes, input_cnt)[source]

Bases: object

Variables
  • ~.label – tuple(frame id, word id)

  • ~.outputs – list of tuples (input index, input time, input byte index)

  • ~.last_per_input – last flags for each input if last=1 the the input word is end of the actual frame (None = don’t care value)

__eq__(other)[source]

Return self==value.

__hash__ = None
__init__(label, word_bytes, input_cnt)[source]
__repr__()[source]

Return repr(self).

get_next_substate(sub_states: Dict[Tuple[int, int], StateTransInfo]) Optional[StateTransInfo][source]
get_state_i() int[source]
Returns

source state index for this state transition, min input index used when this state transition can happen

set_output(out_B_i, in_i, time, in_B_i, B_from_last_input_word)[source]
hwtLib.abstract.frame_utils.join.state_trans_item module
class hwtLib.abstract.frame_utils.join.state_trans_item.StateTransItem(parent_table: StateTransTable, st_i: int, state_next_i: int, out_last: int)[source]

Bases: object

Variables
  • state – state label

  • input – specifies the input to a state transition

  • input_keep_mask – mask which will be applied to keep signal on input to the register

  • input_rd – ready for a input channel (if 1 the input stream will be shifted in)

  • output_keep – output keep values

  • out_byte_mux_sel – list of

Note

input_keep_mask[0][0] = [1, 0] means reg0.in.keep = reg0.out.keep & 0b01

__deepcopy__(memo)[source]

Deepcopy, but do not copy the parent

__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__init__(parent_table: StateTransTable, st_i: int, state_next_i: int, out_last: int)[source]
__lt__(other)[source]

Return self<value.

__repr__(as_dict=False)[source]

Return repr(self).

as_tuple()[source]
classmethod from_dict(parent, d: Dict)[source]
inputs_exactly_different(other: StateTransItem) bool[source]
hwtLib.abstract.frame_utils.join.state_trans_item._cmp_with_None_as_2(o0, o1)[source]
Returns

0 if o0 == o1, -1 if o0 < o1, 1 if o0 > o1

hwtLib.abstract.frame_utils.join.state_trans_table module
class hwtLib.abstract.frame_utils.join.state_trans_table.StateTransTable(word_bytes: int, max_lookahead_for_input: List[int], state_cnt: int)[source]

Bases: object

__init__(word_bytes: int, max_lookahead_for_input: List[int], state_cnt: int)[source]
assert_transitions_deterministic()[source]
filter_unique_state_trans()[source]
Submodules
hwtLib.abstract.frame_utils.alignment_utils module
class hwtLib.abstract.frame_utils.alignment_utils.FrameAlignmentUtils(word_bytes: int, out_offset=0)[source]

Bases: object

Variables

~.word_bytes – number of bytes in 1 output word

__init__(word_bytes: int, out_offset=0)[source]
_resolve_input_bytes_destinations(frames, input_cnt)[source]
Parameters
  • frames – list of all possible frame formats generated from streams_to_all_possible_frame_formats

  • input_cnt – number of input streams

static can_produce_zero_len_frame(streams: List[HStream])[source]
create_frame(stream_i: int, byte_cnt: int, offset_out: int, offset_in: int) Tuple[Tuple[ByteSrcInfo]][source]
Parameters
  • byte_cnt – number of bytes in this frame

  • offset_out – how many empty bytes should be put before data in frame

  • offset_in – how many bytes skip from imput stream

get_bytes_in_frame_info(offset_out, offset_in, chunk_size, chunk_cnt, already_has_body_words)[source]
get_important_byte_cnts(offset_out: int, offset_in: int, chunk_size: int, chunk_cnt_min: Union[int, float], chunk_cnt_max: Union[int, float])[source]

Filter chunk cnt range, let only those values which affect the number of valid bytes in first/last word of frame and presence of words in body frame

join_streams(stream_data: Tuple[Tuple[Tuple[ByteSrcInfo, ...], ...], ...], offset)[source]

Create output frame with specified offset from input stream

Parameters
  • stream_data – list of data for each stream input (stream data is list of data words, data word is a tuple of ByteSrcInfo)

  • offset – offset of output stream

resolve_input_bytes_destinations(streams: List[HStream])[source]
stream_to_all_possible_frame_formats(t: HStream, stream_i: int, offset_out: int)[source]

Generate all possible frame formats with unique features (related to masks, last and data mux)

streams_to_all_possible_frame_formats(streams: List[HStream], offset: int)[source]
See

FrameJoinUtils.stream_to_all_possible_frame_formats() for multiple input streams

hwtLib.abstract.frame_utils.alignment_utils.count_not_none(items: List[Optional[ByteSrcInfo]])[source]
hwtLib.abstract.frame_utils.alignment_utils.freeze_frame(f: List[List[ByteSrcInfo]]) Tuple[Tuple[ByteSrcInfo, ...], ...][source]
hwtLib.abstract.frame_utils.alignment_utils.next_frame_offsets(f0_t: HStream, data_width: int)[source]
hwtLib.abstract.frame_utils.byte_src_info module
class hwtLib.abstract.frame_utils.byte_src_info.ByteSrcInfo(stream_i: int, word_i: int, byte_i: int, is_from_last_input_word: bool)[source]

Bases: object

Container for informations about byte in stream data

Variables
  • ~.stream_i – index of stream

  • ~.word_i – index of word in frame

  • ~.byte_i – index of byte in word

  • ~.is_from_last_input_word – true if this byte comes from last word in input frame

__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__init__(stream_i: int, word_i: int, byte_i: int, is_from_last_input_word: bool)[source]
__lt__(other)[source]

Return self<value.

__repr__()[source]

Return repr(self).

as_tuple()[source]
Submodules
hwtLib.abstract.addressStepTranslation module
class hwtLib.abstract.addressStepTranslation.AddressStepTranslation(src_addr_step: int = 8, dst_addr_step: int = 8)[source]

Bases: object

Variables
  • align_bits – number of bits on source/destination address which are addressing in a single word or other address

  • src_addr_step – how many bits is addressing one unit of src_addr_sig

  • dst_addr_step – how many bits is addressing one unit of dst_addr_sig

__init__(src_addr_step: int = 8, dst_addr_step: int = 8)[source]
propagate(src_addr_sig, dst_addr_sig, dst_offset: int = 0)[source]
Parameters
  • src_addr_sig – input signal with address

  • dst_addr_sig – output signal for address

hwtLib.abstract.busBridge module
class hwtLib.abstract.busBridge.BusBridge(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

Abstract class for bridges between two interface (not necesary different) types

Variables
  • ~.s – slave interface of source interface class

  • ~.m – master interface of destination interface class

hwtLib.abstract.busEndpoint module
class hwtLib.abstract.busEndpoint.BusEndpoint(structTemplate, intfCls=None, shouldEnterFn=None)[source]

Bases: Unit

Abstract unit

Delegate request from bus to fields of structure (fields are represented by various interfaces) write has higher priority

Note

implementation is usually address decoder

_images/BusEndpoint.png
__init__(structTemplate, intfCls=None, shouldEnterFn=None)[source]
Parameters
  • structTemplate – instance of HStruct which describes address space of this endpoint

  • intfCls – class of bus interface which should be used

  • shouldEnterFn – function(root_t, structFieldPath) return (shouldEnter, shouldUse) where shouldEnter is flag that means iterator over this interface should look inside of this actual object and shouldUse flag means that this field should be used (to create interface)

static _defaultShouldEnterFn(root: HdlType, field_path: Tuple[Union[str, int]])[source]

Default method which resolves how the parts of input data type should be represented on interface level.

_getAddrStep() int[source]
Returns

how many bits does 1 address unit addresses, (e.g. AXI -> 8b, index to uint32_t[N] -> 32)

_getWordAddrStep() int[source]
Returns

how many address units is one word on bus (e.g. 32b AXI -> 4)

_mkFieldInterface(structIntf: StructIntf, field: HStructField)[source]

Instantiate field interface for fields in structure template of this endpoint

Returns

interface for specified field

_parseTemplate()[source]
_suggestedAddrWidth()[source]

Based on struct template resolve how many bits for address is needed

connectByInterfaceMap(interfaceMap: IntfMap)[source]

Connect “decoded” struct interface to interfaces specified in interface map

connect_directly_mapped_read(ar_addr: RtlSignal, r_data: RtlSignal, default_r_data_drive)[source]

Connect the RegCntrl.din interfaces to a bus

connect_directly_mapped_write(aw_addr: RtlSignal, w_data: RtlSignal, en: RtlSignal)[source]

Connect the RegCntrl.dout interfaces to a bus

classmethod fromInterfaceMap(interfaceMap)[source]

Generate converter by struct data type specified by interface map

Parameters

interfaceMaphwt.interfaces.intf_map.HTypeFromIntfMap()

getPort(transTmpl: TransTmpl)[source]
static intf_for_Bits(t)[source]
isInMyAddrRange(addr_sig)[source]
propagateAddr(src_addr_sig: RtlSignal, src_addr_step: int, dst_addr_sig: RtlSignal, dst_addr_step: int, transTmpl: TransTmpl)[source]
Parameters
  • src_addr_sig – input signal with address

  • src_addr_step – how many bits is addressing one unit of src_addr_sig

  • dst_addr_sig – output signal for address

  • dst_addr_step – how many bits is addressing one unit of dst_addr_sig

  • transTmpl – TransTmpl which has meta-informations about this address space transition

hwtLib.abstract.busEndpoint.TransTmpl_get_max_addr(t: TransTmpl)[source]
hwtLib.abstract.busEndpoint.TransTmpl_get_min_addr(t: TransTmpl)[source]
hwtLib.abstract.busInterconnect module
class hwtLib.abstract.busInterconnect.AUTO_ADDR[source]

Bases: object

constant which means that address should be picked automatically

class hwtLib.abstract.busInterconnect.BusInterconnect(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

Abstract class of bus interconnects

Variables
  • ~.m – HObjList of master interfaces

  • ~.s – HObjList of slave interfaces

_normalize_config()[source]
getOptimalAddrSize()[source]
class hwtLib.abstract.busInterconnect.BusInterconnectUtils[source]

Bases: object

classmethod _assert_non_overlapping(slaves)[source]
classmethod _extract_separable_group(mi: int, seen_m: Set[int], masters_connected_to: List[Set[int]], slaves_connected_to: List[Set[int]])[source]

Transitive enclosure of master/stalave ports on connected relation (Extract a group of all ports which are somehow connected to each other)

classmethod _extract_separable_groups(MASTERS, SLAVES, access_type)[source]

Try to find independent subgraphs in conected master-slave ports on R/W channel separately

Parameters

access_type – READ or WRITE

classmethod _normalize_master_configs(MASTERS, SLAVES)[source]
_normalize_slave_configs(SLAVES, data_width=None)[source]
hwtLib.abstract.busStaticRemap module
class hwtLib.abstract.busStaticRemap.BusStaticRemap(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

Abstract class for component which remaps memory regions on bus interfaces

Variables
  • ~.MEM_MAP – list of tuples (addr_from, size, addr_to) for each memory region on second interface

  • ~.m – slave interface of first interface class where master should be connected

  • ~.s – slave interface of second interface class where master slave be connected

_normalize_mem_map(mem_map)[source]
translate_addr_signal(mem_map, sig_in, sig_out)[source]
translate_addr_val(mem_map, addr: int)[source]
hwtLib.abstract.componentBuilder module
class hwtLib.abstract.componentBuilder.AbstractComponentBuilder(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]

Bases: object

Helper class which simplifies instantiation of commonly used components with configuration based on input/output interface

Variables
  • ~.compId – used for sequential number of components

  • ~.lastComp – last builded component

  • ~.end – last interface of data-path

Attention

input port is taken from self.end

__init__(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]
Parameters
  • parent – unit in which will be all units created by this builder instantiated

  • name – prefix for all instantiated units

  • srcInterface – start of data-path

  • master_to_slave – if True the circuit is build in natural direction (master to slave, input to output) othervise it is build in reverse direction

_findSuitableName(name: str, firstWithoutCntrSuffix=False)[source]

Find a suitable name for component (= name without collisions), add suffix with counter to solve name collisions

Parameters

firstWithoutCntrSuffix – if True name is used as is if possible if False counter suffix is always added

_getIntfCls(intf: Union[Interface, HObjList])[source]

Get real interface class of interface

_propagateClkRstn(u)[source]

Connect clock and reset to unit “u”

getClk()[source]

lookup clock signal on parent

getInfCls()[source]

Get class of interface which this builder is currently using.

getRstn()[source]

lookup reset(n) signal on parent

hwtLib.abstract.debug_bus_monitor module
class hwtLib.abstract.debug_bus_monitor.DebugBusMonitor(bus_cls, bus_endpoint_cls)[source]

Bases: Unit

This component is similar to ILA/ChipScope/SignalTAP but it is not connected to internal JTAG, but to a specified interface. This component generates an address decoder and connect all specified interfaces to a service bus. It also stores the names and bit widths of original interfaces in a ROM in order to display them later in test application. This component also supports for snapshots of values by a generic trigger method, transaction counters etc.

Note

addressspace size depends on how much data is actually monitored. But it has fixed structure.

Example of meta_memory JSON format:

__init__(bus_cls, bus_endpoint_cls)[source]
classmethod _build_meta_memory(intf: Interface, offset: int)[source]
apply_connections()[source]

Connect a monitored interface to monitor ports of this component

build_meta_memory(monitored_data: List[DebugBusMonitorDataRecord])[source]
build_meta_memory_json(monitored_data: List[DebugBusMonitorDataRecord], data_ids: Dict[DebugBusMonitorDataRecord, int], offset: int)[source]
iter_monitor_interface()[source]
register(intf: Interface, name: Optional[str] = None, cdc: bool = False, trigger: Optional[RtlSignal] = None, add_reg: bool = False)[source]
Parameters
  • intf – an interface to monitor

  • name – name override

  • cdc – if True instantiate Clock domain crossing to synchronize input data to clock domain of this component

  • trigger – an optional signal which triggers the snapshot of this interface

  • add_reg – if True an register is added between input and bus interface

Note

if cdc is set to True the trigger has to be synchonezed to a clock clock domain of intf

class hwtLib.abstract.debug_bus_monitor.DebugBusMonitorDataRecord(intf: Interface, name: str, cdc: bool, trigger: RtlSignal, add_reg: bool)[source]

Bases: object

__init__(intf: Interface, name: str, cdc: bool, trigger: RtlSignal, add_reg: bool)[source]
add_children(c: DebugBusMonitorDataRecord)[source]
is_visual_only()[source]
hwtLib.abstract.discoverAddressSpace module
class hwtLib.abstract.discoverAddressSpace.AddressSpaceProbe(topIntf, getMainSigFn, offset=0)[source]

Bases: object

An object which can be used to discover an address space of an interface. Discovery is made by walking on address signal.

__init__(topIntf, getMainSigFn, offset=0)[source]
Parameters
  • topIntf – interface on which should discovery start

  • getMainSigFn – function which gets the main signal form interface which should this code care about usually address

_discoverAddressSpace(topIntf, offset)[source]
_extractStruct(converter, offset)[source]
_getMainSigFn(intf)[source]
walkToConverter(mainSig, offset)[source]

walk mainSig down to endpoints and search for any bus converter instances

Returns

generator of typles (offset, converter instance)

hwtLib.abstract.discoverAddressSpace.getEpSignal(sig, op)[source]
Parameters
  • sig – main signal

  • op – operator on this signal

Returns

signal modified by this operator or none if this operator is creating new datapath

hwtLib.abstract.discoverAddressSpace.getParentUnit(sig)[source]
hwtLib.abstract.hwExceptionCtx module
class hwtLib.abstract.hwExceptionCtx.ExceptionHandleInterface(exception: InHwError, masterDir=DIRECTION.OUT, loadConfig=True)[source]

Bases: HandshakeSync

__copy__()[source]

Create new instance of interface of same type and configuration

__init__(exception: InHwError, masterDir=DIRECTION.OUT, loadConfig=True)[source]

This constructor is called when constructing new interface, it is usually done manually while creating hwt.synthesizer.unit.Unit or automatically while extracting interfaces from UnitWithSoure

Parameters
  • masterDir – direction which this interface should have for master

  • multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size

  • loadConfig – do load config in __init__

class hwtLib.abstract.hwExceptionCtx.HwExceptionCtx(parent: Unit, name='raise')[source]

Bases: object

An object which handles hardware exceptions.

Attention

exception handling requires a clock and reset signal to be present on parent hwt.synthesizer.unit.Unit instance.

_Unit_makePublicIntfPrivateInImpl(intf: ExceptionHandleInterface)[source]
_Unit_registerPublicIntfInImpl(intf: ExceptionHandleInterface, name: str)[source]
__init__(parent: Unit, name='raise')[source]
hw_catch(exception_cls: Optional[Union[Type[InHwError], Tuple[Type[InHwError], ...]]] = None) List[Tuple[InHwError, ExceptionHandleInterface]][source]

Catch all uncatched exceptions by exception class.

Parameters

exception_cls – An class on exceptions which should be catched (An exception is catched if its class is a subclass of exception_cls).

Note

Catching exception means getting IO for exception handling in this context. You need to drive all interfaces and possibly re-raise for those which should not be catched.

Returns

List of tuples (exception, interface) for every uncatched exception in current scope (includes children). (Due to parallel nature of hardware it is a list and exceptions may be raised simulately.)

hw_raise(exception: InHwError, pending_flag: Optional[RtlSignalBase] = None, raising_flag: Optional[RtlSignalBase] = None)[source]

Construct a logic to raise an exception in generated hardware. This creates a flag and IO for exception handling status.

Parameters
  • pending_flag – An optional flag which should be set to 1 if exception was raised in some previous clock cycle an it has not beed catched yet.

  • raising_flag – An optional flag which should be set to 1 if exception exception is beeing raised in this clock cycle.

Attention

The arguments specified in the exception has to remain stable until the excetion is handled.

Returns

An expression which triggers the exception handling.

propagate()[source]

Propagate uncatched exceptions from this hwt.synthesizer.unit.Unit instance and its children to IO of this hwt.synthesizer.unit.Unit instance.

Note

The exception is considered uncached if its rd signal is not driven.

exception hwtLib.abstract.hwExceptionCtx.InHwError(hw_args=None, *args, **kwargs)[source]

Bases: Exception

A base class for exceptions which are translated to hardware and handle in runtime of the hardware.

Variables

hw_traceback (Deque[Unit]) – traceback

__init__(hw_args=None, *args, **kwargs)[source]
hwtLib.abstract.monitorIntf module
class hwtLib.abstract.monitorIntf.MonitorIntf(template_interface)[source]

Bases: Interface

Interfaces same as template interface, but with all signals as an input

__init__(template_interface)[source]

This constructor is called when constructing new interface, it is usually done manually while creating hwt.synthesizer.unit.Unit or automatically while extracting interfaces from UnitWithSoure

Parameters
  • masterDir – direction which this interface should have for master

  • multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size

  • loadConfig – do load config in __init__

static _bound_intf(template_interface, cls=None)[source]
_config()[source]

Copy config from template interface

_declr()[source]

Create interfaces same as on template interface, but make them always input

class hwtLib.abstract.monitorIntf.MonitorIntfReg(intfCls: Type[MonitorIntf])[source]

Bases: Unit

__init__(intfCls: Type[MonitorIntf])[source]
class hwtLib.abstract.monitorIntf.MonitorIntfVldSynced(template_interface)[source]

Bases: VldSynced

__init__(template_interface)[source]

This constructor is called when constructing new interface, it is usually done manually while creating hwt.synthesizer.unit.Unit or automatically while extracting interfaces from UnitWithSoure

Parameters
  • masterDir – direction which this interface should have for master

  • multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size

  • loadConfig – do load config in __init__

class hwtLib.abstract.monitorIntf.MonitorIntfVldSyncedCdc(template_interface)[source]

Bases: VldSyncedCdc

__init__(template_interface)[source]
Parameters

template_interface – an Interface instance which will be monitored, used as template for this interface

hwtLib.abstract.monitorIntf._connect_MonitorIntf(src: MonitorIntf, dst)[source]
hwtLib.abstract.monitorIntf._connect_to_MonitorIntf(src, dst: MonitorIntf)[source]
hwtLib.abstract.monitorIntf.connect_MonitorIntf(src: MonitorIntf, dst)[source]

Connect signal by signal and ignore the directions of struct interface (check only direction of low level signals)

hwtLib.abstract.monitorIntf.connect_to_MonitorIntf(src, dst: MonitorIntf)[source]

Connect signal by signal and ignore the directions of struct interface (check only direction of low level signals)

hwtLib.abstract.monitorIntf.monitor_of(intf: Union[Interface, RtlSignal])[source]

Create a monitor interface for specified interface (monitor interface is an interface which reads all signals of choosen interface)

hwtLib.abstract.sim_ram module
exception hwtLib.abstract.sim_ram.AllocationError[source]

Bases: Exception

Exception which says that requested allocation can not be performed

class hwtLib.abstract.sim_ram.SimRam(cellSize, parent=None)[source]

Bases: object

Dense memory for simulation purposes with data pump interfaces

Variables

~.data – memory dict

__init__(cellSize, parent=None)[source]
Parameters
  • cellWidth – width of items in memory

  • clk – clk signal for synchronization

  • parent – parent instance of SimRam (memory will be shared with this instance)

_getArray(offset, transTmpl)[source]
Parameters
  • offset – global offset of this transTmpl (and struct)

  • transTmpl – instance of TransTmpl which specifies items in array

_getStruct(offset, transTmpl)[source]
Parameters
  • offset – global offset of this transTmpl (and struct)

  • transTmpl – instance of TransTmpl which specifies items in struct

calloc(num, size, keepOut=None, initValues=None) int[source]

Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

Parameters
  • num – Number of elements to allocate.

  • size – Size of each element.

  • keepOut – optional memory spacing between this memory region and lastly allocated (number of bit between last allocated segment to avoid)

  • initValues – iterable of word values to init memory with

Returns

address (byte step) of allocated memory

getArray(addr: int, item_size: int, item_cnt: int)[source]

Get array stored in memory

getBits(start, end, sign)[source]

Gets value of bits between selected range from memory

Parameters
  • start – bit address of start of bit of bits

  • end – bit address of first bit behind bits

Returns

instance of BitsVal (derived from SimBits type) which contains copy of selected bits

getStruct(addr, structT, bitAddr=None)[source]

Get HStruct from memory

Parameters
  • addr – address where get struct from

  • structT – instance of HStruct or FrameTmpl generated from it to resolve structure of data

  • bitAddr – optional bit precise address is is not None param addr has to be None

malloc(size, keepOut=None)[source]

Allocates a block of memory of size and initialize it with None (invalid value)

Parameters
  • size – Size of memory block to allocate.

  • keepOut – optional memory spacing between this memory region and lastly allocated

Returns

address of allocated memory

hwtLib.abstract.sim_ram.reshapedInitItems(actualCellSize, requestedCellSize, values)[source]

Convert array item size and items cnt while size of array remains unchanged

Parameters
  • actualCellSize – actual size of item in array

  • requestedCellSize – requested size of item in array

  • values – input array

Returns

generator of new items of specified characteristic

hwtLib.abstract.streamBuilder module
class hwtLib.abstract.streamBuilder.AbstractStreamBuilder(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]

Bases: AbstractComponentBuilder

Note

see AbstractComponentBuilder

Attention

this is just abstract class unit classes has to be specified in concrete implementation

Variables
  • ~.FifoCls – FIFO unit class

  • ~.FifoAsyncCls – asynchronous FIFO (FIFO with separate clock per port) unit class

  • ~.JoinSelectCls – select order based join unit class

  • ~.JoinFairCls – round robin based join unit class

  • ~.JoinPrioritizedCls – priority based join unit class

  • ~.RegCls – register unit class

  • ~.RegCdcCls – Clock domain crossing register unit class

  • ~.ResizerCls – resizer unit class (used to change data width of an interface)

  • ~.SplitCopyCls – copy based split unit class

  • ~.SplitSelectCls – select order based split unit class (demultiplexer)

  • ~.SplitFairCls – round robin based split unit class

  • ~.SplitPrioritizedCls – priority based split unit class

FifoAsyncCls = NotImplemented
FifoCls = NotImplemented
JoinFairCls = NotImplemented
JoinPrioritizedCls = NotImplemented
JoinSelectCls = NotImplemented
RegCls = NotImplemented
ResizerCls = NotImplemented
SplitCopyCls = NotImplemented
SplitFairCls = NotImplemented
SplitPrioritizedCls = NotImplemented
SplitSelectCls = NotImplemented
_genericInstance(unit_cls, name, set_params=<function AbstractStreamBuilder.<lambda>>, update_params=True, propagate_clk_rst=True)[source]

Instantiate generic component and connect basics

Parameters
  • unit_cls – class of unit which is being created

  • name – name for unit_cls instance

  • set_params – function which updates parameters as is required (parameters are already shared with self.end interface)

classmethod _join(joinCls, parent, srcInterfaces, name, configAs, extraConfigFn)[source]

Create builder from many interfaces by joining them together

Parameters
  • joinCls – join component class which should be used

  • parent – unit where builder should place components

  • srcInterfacecs – sequence of interfaces which should be joined together (lower index = higher priority)

  • configureAs – interface or another object which configuration should be applied

  • extraConfigFn – function which is applied on join unit in configuration phase (can be None)

buff(items: int = 1, latency: Union[None, int, Tuple[int, int]] = None, delay: Optional[int] = None, init_data: tuple = ())[source]

Use registers and FIFOs to create buffer of specified parameters :note: if items <= latency registers are used else FIFO is used

Parameters
  • items – number of items in buffer

  • latency – latency of buffer (number of clk ticks required to get data from input to input)

  • delay – delay of buffer (number of clk ticks required to get data to buffer)

  • init_data – a reset value of buffer (data is transfered after reset) if items=1 and interface has just data:uint8_t signal the init_data will be in format ((0,),)

Note

delay can be used as synchronization method or to solve timing related problems because it will split valid signal path

Note

if latency or delay is None the most optimal value is used

buff_cdc(clk, rst, items=1)[source]

Instantiate a CDC (Clock Domain Crossing) buffer or AsyncFifo on selected interface

Note

if items==1 CDC clock synchronization register is used if items>1 asynchronous FIFO is used

classmethod join_fair(parent, srcInterfaces, name=None, configAs=None, exportSelected=False)[source]

create builder from fairly joined interfaces (round robin for input select)

Parameters

exportSelected – if True join component will have handshaked interface with index of selected input

Note

other parameters same as in .AbstractStreamBuilder._join

classmethod join_prioritized(parent, srcInterfaces, name=None, configAs=None, extraConfigFn=None)[source]

create builder from fairly joined interfaces (round robin for input select)

Note

other parameters same as in .AbstractStreamBuilder._join

split_copy(noOfOutputs)[source]

Clone input data to all outputs

Parameters

noOfOutputs – number of output interfaces of the split

split_copy_to(*outputs)[source]

Same like split_copy, but outputs are automatically connected

Parameters

outputs – ports on which should be outputs of split component connected to

split_fair(noOfOutputs, exportSelected=False)[source]

Create a round robin selector with number of outputs specified by noOfOutputs

Parameters
  • noOfOutputs – number of outputs of multiplexer

  • exportSelected – if is True split component will have interface “selectedOneHot” of type VldSynced wich will have one hot index of selected item

split_fair_to(*outputs, exportSelected=False)[source]

Same like split_fair, but outputs are automatically connected

Parameters
  • outputs – ports on which should be outputs of split component connected to

  • exportSelected – if is True split component will have interface “selectedOneHot” of type VldSynced which will have one hot index of selected item

split_prioritized(noOfOutputs)[source]

data from input is send to output which is ready and has highest priority from all ready outputs

Parameters

noOfOutputs – number of output interfaces of the fork

split_prioritized_to(*outputs)[source]

Same like split_prioritized, but outputs are automatically connected

Parameters

outputs – ports on which should be outputs of split component connected to

split_select(outputSelSignalOrSequence, noOfOutputs)[source]

Create a demultiplexer with number of outputs specified by noOfOutputs

Parameters
  • noOfOutputs – number of outputs of multiplexer

  • outputSelSignalOrSequence – handshaked interface (onehot encoded) to control selected output or sequence of output indexes which should be used (will be repeated)

split_select_to(outputSelSignalOrSequence, *outputs)[source]

Same like split_select, but outputs are automatically connected

Parameters

outputs – ports on which should be outputs of split component connected to

hwtLib.abstract.template_configured module
hwtLib.abstract.template_configured.HdlType_separate(t: HdlType, do_separate_query: Callable[[HdlType], bool]) Generator[Tuple[bool, HdlType], None, None][source]

Split HStruct type hierachy on the specified fields to multiple type definitions.

class hwtLib.abstract.template_configured.TemplateConfigured(structT: HdlType, tmpl: Optional[TransTmpl] = None, frames: Optional[List[FrameTmpl]] = None)[source]

Bases: object

Class with functions for extracting metadata from frame template/HdlType. Used for resolving of data mapping between abstract type and physical interface.

__init__(structT: HdlType, tmpl: Optional[TransTmpl] = None, frames: Optional[List[FrameTmpl]] = None)[source]
Parameters
  • structT – instance of HStruct used as template for this frame If name is None no input port is generated and space is filled with invalid values, little-endian encoding, supported types of interfaces are: Handshaked, Signal can be also instance of FrameTmpl

  • tmpl – instance of TransTmpl for this structT

  • frames – list of FrameTmpl instances for this tmpl

Note

if tmpl and frames are None they are resolved from structT parseTemplate

chainFrameWords() Generator[Tuple[int, List[Union[TransPart, ChoicesOfFrameParts]], bool], None, None][source]
parseTemplate()[source]
hwtLib.abstract.template_configured.separate_streams(t: HdlType)[source]

Split HStruct type hierarchy on the fields of HStream type.

Note

e.g. in HStruct( (HStream(Bits(8)), “data”), (Bits(32), “fcs”), ) is split to HStruct((HStream(Bits(8)), “data”),) and HStruct((Bits(32), “fcs”),)

hwtLib.abstract.template_configured.to_primitive_stream_t(t: HdlType)[source]

Convert type to a HStream of Bits With proper frame len, offset etc.

hwtLib.cesnet package

https://www.cesnet.cz related components, interfaces and utilities.

Subpackages

hwtLib.peripheral package

Subpackages
hwtLib.peripheral.usb package

This package contains components, interfaces, data types and other utils related to Universal Serial Bus (USB) protocol.

The USB bus is composed of Host (the main device which controls the bus), Hub(s) (a port extender) and a Device(s). The USB protocol stack (v3.2) is composed of multiple layers as depicted in:

_images/USB-Protocol-Stack-V3.png
  • Functional Layer:

    • This layer generates requests which are converted into transactions containing different packets. It also manages end to end data flow between host and device.

Protocol Layer:

  • Packets originates at transmit part of protocol layer and terminates at receive part of protocol layer. It has various functions which include following.

    • Ensure end to end reliability of packets.

    • Ensure effective management of power.

    • Ensure effective use of Bandwidth.

Link Layer:

  • This layer manages port to port flow of data between USB host and device. Link layer commands ensure link level data integrity, flow control and power management. This layer handles packet acknowledgement and takes care of error recovery. The Link Layer also handles Header Packet Framing. Its functions are similar to MAC layer of OSI model.

Physical Layer:

  • This layer offers actual physical connection between two ports. The connection uses a single differential pair (<= USB 2.0) or two differential data pairs (>= USB 3.0) (one transmit path and one receive path). The USB <=2.0 physical layer performs NRZI (Non Return to Zero Invert) encoding and bit stuffing. In the USB >=3.0 and <3.2 physical layer the transmit part of physical layer performs data scrambling, 8b10b encoding, and serialization functions. And the receive part of physical Layer performs de-serialization, 8b10b decoding, data descrambling, and receiver clock and data recovery. In USB >=3.2 it may have additional RX and TX lane.

  • https://electronics.stackexchange.com/questions/409912/usb-softcore-for-fpga-extra-resistor-on-fpga-transmitter-pin

note

USB Documentation, Christopher D. Leary and Devrin TalenDecember 17, 2007

Bus Enumeration

  1. Host waits for at least 100 ms to account for the insertion process.

  2. Host resets the device. Device should now be at address 0 and the defaultcontrol pipe will be open (default state).

  3. Host queries the device descriptor from the devices default control pipe.

  4. The host controller assigns a unique address to the device.

  5. Host queries all configuration descriptors from the device, then sets one.At this point, the device will begin to draw the amount of power requestedby the assigned interface.

  6. Host queries all other remaining descriptors (interface, endpoint, etc.) andsets up any requested interrupt transfers.

USB Endpoints

In the USB specification, a device endpoint is a uniquely addressable portion of a USB device that is the source or sink of information in a communication flow between the host and device. The Ep0 has is dedicated to control and and it provides descriptors for other endpoints.

The Endpoints may support following types of transfer:

  • Control

  • Interrupt

  • Bulk

  • Isochronous

_images/usb_transaction_example.png

Similar projects: * https://github.com/WangXuan95/FPGA-USB-Device

Subpackages
hwtLib.peripheral.usb.descriptors package
Submodules
hwtLib.peripheral.usb.descriptors.bundle module
class hwtLib.peripheral.usb.descriptors.bundle.UsbDescriptorBundle(*args, **kwargs)[source]

Bases: list

Container of USB descriptors.

Variables
  • compiled_rom – list of bytes for descriptor rom generated from this descriptor bundle

  • compiled_type_to_addr_and_size – a dictionary mapping the descriptor type to list of tuples address size for a localization of the descriptor in compiled rom

static HValue_to_byte_list(d: HValue)[source]
__init__(*args, **kwargs)[source]
compile_rom() List[int][source]
get_descr_bytes(start_descr_i: int, wLength: int) List[int][source]

Start at the beginning of the descriptor on index start_descr_i and copy specified number of bytes from that location (may overlap to other descriptors as well)

get_descriptor(descr_t, descr_i: int) Tuple[int, HValue][source]

Get an index of descriptor of a specific type

Parameters
  • descr_t – specific type of descriptor

  • descr_i – index of this descriptor of this specific type (excluding any descriptors of different type)

get_descriptor_index(descr_t, descr_i: int) int[source]
get_descriptors_from_rom(descr_t: USB_DESCRIPTOR_TYPE) Tuple[int, int][source]

Get the address and size of descriptor in comiled rom memory

Parameters

i – index of the decriptor in a list of descriptors of this type to get

Returns

tuple address, size

get_endpoint_meta() Tuple[Tuple[Optional[UsbEndpointMeta], Optional[UsbEndpointMeta]]][source]
static pack_descriptor(d: HValue) List[int][source]
class hwtLib.peripheral.usb.descriptors.bundle.UsbEndpointMeta(index: int, dir_: USB_ENDPOINT_DIR, supports_setup: bool = False, supports_bulk: bool = False, supports_interrupt: bool = False, supports_isochronoust: bool = False, max_packet_size: int = 0, buffer_size: Optional[int] = None)[source]

Bases: object

Information about USB endpoint extracted from UsbDescriptorBundle

__init__(index: int, dir_: USB_ENDPOINT_DIR, supports_setup: bool = False, supports_bulk: bool = False, supports_interrupt: bool = False, supports_isochronoust: bool = False, max_packet_size: int = 0, buffer_size: Optional[int] = None)[source]
__repr__()[source]

Return repr(self).

exception hwtLib.peripheral.usb.descriptors.bundle.UsbNoSuchDescriptor[source]

Bases: Exception

Raised when the device responded with STALL to GET_DESCRIPTOR which means that it does not have such a descriptor.

hwtLib.peripheral.usb.descriptors.cdc module

This file contains a data structures used for communication and configuration of USB CDC UART device. Based on: https://www.silabs.com/documents/public/application-notes/AN758.pdf

class hwtLib.peripheral.usb.descriptors.cdc.CHAR_FORMAT[source]

Bases: object

STOP_BIT_1 = 0
STOP_BIT_1_5 = 1
STOP_BIT_2 = 2
class hwtLib.peripheral.usb.descriptors.cdc.CLASS_REQUEST[source]

Bases: object

GET_LINE_CODING = 33
SET_CONTROL_LINE_STATE = 34
SET_LINE_CODING = 32
class hwtLib.peripheral.usb.descriptors.cdc.PARITY_TYPE[source]

Bases: object

EVEN = 2
MARK = 3
NONE = 0
ODD = 1
SPACE = 4
class hwtLib.peripheral.usb.descriptors.cdc.USB_CDC_DESCRIPTOR_SUBTYPE[source]

Bases: object

ABSTRACT_CONTROL_MANAGEMENT = 2
ATM_NETWORKING_FUNCTIONAL = 16
CALL_MANAGEMENT_FUNCTIONAL = 1
CAPI_CONTROL_MANAGEMENT = 14
COUNTRY_SELECTION_FUNCTIONAL = 7
DIRECT_LINE_MANAGEMENT = 3
ETHERNET_NETWORKING_FUNCTIONAL = 15
EXTENSION_UNIT_FUNCTIONAL = 12
HEADER = 0
MULTI_CHANNEL_MANAGEMENT = 13
NETWORK_CHANNEL_TERMINAL = 10
PROTOCOL_UNIT_FUNCTIONAL = 11
TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPABILITIES = 5
TELEPHONE_OPERATIONAL_MODES = 8
TELEPHONE_RINGER_FUNCTIONAL = 4
UNION = 6
USB_TERMINAL_FUNCTIONAL = 9
hwtLib.peripheral.usb.descriptors.cdc.get_default_usb_cdc_vcp_descriptors(usbVer='2.0', bMaxPacketSize=64, manufacturerStr: Optional[str] = None, productStr: Optional[str] = None, deviceVer: str = '0.0') UsbDescriptorBundle[source]

Generates USB descriptors for USB CDC device which works as a UART (serial)

Note

based on https://github.com/tinyfpga/TinyFPGA-Bootloader/blob/master/common/usb_serial_ctrl_ep.v#L344

hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_abstract_control_management(capability_commFeature: bool, capability_lineCodingAndSerialState: bool, capability_sendBreak: bool, capability_networkConnection: bool)[source]
hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_call_management(supportHandlesCallManagementItself: bool, supportManagementOverDataClassInterface: bool, bDataInterface: int)[source]
hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_header(cdcVer: str)[source]
hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_union(bMasterInterface: int, bSlaveInterface: List[int])[source]
hwtLib.peripheral.usb.descriptors.cdc.make_usb_line_coding_default(dwDTERate=115200, bCharFormat=0, bParityType=0, bDataBits=8)[source]
hwtLib.peripheral.usb.descriptors.cdc.usb_define_descriptor_functional_union_body_t(SLAVE_INTERFACE_CNT: int)[source]
hwtLib.peripheral.usb.descriptors.cdc.usb_define_descriptor_functional_union_t(SLAVE_INTERFACE_CNT: int)[source]
hwtLib.peripheral.usb.descriptors.cdc_ncm module
hwtLib.peripheral.usb.descriptors.hid module
class hwtLib.peripheral.usb.descriptors.hid.USB_HID_COUNTRY_CODE[source]

Bases: object

ARABIC = 1
BELGIAN = 2
CANADIAN_BILINGUAL = 3
CANADIAN_FRENCH = 4
CZECH_REPUBLIC = 5
DANISH = 6
FINNISH = 7
FRENCH = 8
GERMAN = 9
GREEK = 10
HEBREW = 11
HUNGARY = 12
INTERNATIONAL_ISO = 13
ITALIAN = 14
JAPAN_KATAKANA = 15
KOREAN = 16
LATIN_AMERICAN = 17
NETHERLANDS_DUTCH = 18
NORWEGIAN = 19
NOT_SUPPORTED = 0
PERSIAN_FARSI = 20
POLAND = 21
PORTUGUESE = 22
RUSSIA = 23
SLOVAKIA = 24
SPANISH = 25
SWEDISH = 26
SWISS_FRENCH = 27
SWISS_GERMAN = 28
SWITZERLAND = 29
TAIWAN = 30
TURKISH_F = 35
TURKISH_Q = 31
UK = 32
US = 33
YUGOSLAVIA = 34
class hwtLib.peripheral.usb.descriptors.hid.USB_HID_PROTOCOL[source]

Bases: object

KEYBOARD = 1
MOUSE = 2
NONE = 0
class hwtLib.peripheral.usb.descriptors.hid.USB_HID_SUBLCASS[source]

Bases: object

BOOT_INTERFACE = 1
NONE = 0
hwtLib.peripheral.usb.descriptors.hid.get_default_usb_hid_mouse_descriptors()[source]

based on https://www.usbmadesimple.co.uk/ums_5.htm

hwtLib.peripheral.usb.descriptors.hid.make_usb_descriptor_hid(hidVer: str, bCountryCode: USB_HID_COUNTRY_CODE, bNumDescriptors: int, bDescriptorType: USB_DESCRIPTOR_TYPE, wDescriptorLength: int)[source]
hwtLib.peripheral.usb.descriptors.std module
class hwtLib.peripheral.usb.descriptors.std.USB_DESCRIPTOR_TYPE[source]

Bases: object

CONFIGURATION = 2
DEVICE = 1
DEVICE_QUALIFIER = 6
ENDPOINT = 5
FUNCTIONAL = 36
HID = 33
INTERFACE = 4
INTERFACE_POWER = 8
OTHER_SPEED_CONFIGURATION = 7
REPORT = 34
STRING = 3
class hwtLib.peripheral.usb.descriptors.std.USB_DEVICE_CLASS[source]

Bases: object

https://www.usb.org/defined-class-codes

APPLICATION_SPECIFIC = 254
AUDIO = 1
AUDIO_VIDEO_DEVICE = 16
BILBOARD_DEVICE = 17
CDC_CONTROL = 2
CDC_DATA = 10
CONTENT_SECURITY = 13
DIAGNOSTIC_DEVICE = 220
HID = 3
IMAGE = 6
MASS_STORAGE = 8
MISCELLANEOUS = 239
PERSONAL_HEALTHCARE = 15
PRINTER = 7
SMART_CARD = 11
UNSPECIFIED = 0
USB_HUB = 9
USB_PID = 5
USB_TYPE_C_BRIDGE = 18
VENDOR_SPECIFIC = 255
VIDEO = 14
WIRELESS_CONTROLLER = 224
class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_SYNCHRONISATION_TYPE[source]

Bases: object

Note only apply to isochronous endpoints.

ADAPTIVE = 2
ASYNCHRONOUS = 1
NONE = 0
SYNCHRONOUS = 3
class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_TRANSFER_TYPE[source]

Bases: object

BULK = 2
CONTROL = 0
INTERRUPT = 3
ISOCHRONOUS = 1
class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_USAGE_TYPE[source]

Bases: object

DATA = 0
FEEDBACK = 1
IMPLICIT_FEEDBACK_DATA = 2
RESERVED = 3
class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_DIR[source]

Bases: object

IN = 1
OUT = 0
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_configuration(wTotalLength: int, bNumInterfaces: int, bConfigurationValue: int, iConfiguration: int, remoteWakeup: int = 0, selfPowered: int = 0, bMaxPower: int = 250)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_device(bDeviceClass: USB_DEVICE_CLASS, bDeviceSubClass=0, bDeviceProtocol=255, usbVer: USB_VER = '2.0', bMaxPacketSize=64, idVendor=4660, idProduct=22136, bcdDevice='0.1', iManufacturer=1, iProduct=2, iSerialNumber=0, bNumConfigurations=1)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_device_qualifier(bDeviceClass: USB_DEVICE_CLASS, bDeviceSubClass=0, bDeviceProtocol=255, usbVer: USB_VER = '2.0', bMaxPacketSize=64, bNumConfigurations=1)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_endpoint(bEndpointAddressDir: USB_ENDPOINT_DIR, bEndpointAddress: int, attr_transferType: USB_ENDPOINT_ATTRIBUTES_TRANSFER_TYPE, attr_synchronisationType: USB_ENDPOINT_ATTRIBUTES_SYNCHRONISATION_TYPE, attr_usageType: USB_ENDPOINT_ATTRIBUTES_USAGE_TYPE, wMaxPacketSize: int, bInterval: int)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_interface(bInterfaceNumber: int, bAlternateSetting: int, bNumEndpoints: int, bInterfaceClass: USB_DEVICE_CLASS, bInterfaceSubClass: int, bInterfaceProtocol: int, iInterface: int)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_string(s: str)[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_string0(langIds: List[int])[source]
hwtLib.peripheral.usb.descriptors.std.make_usb_device_request_get_descr(descr_t, i: int, wIndex=0, wLength: ~typing.Optional[int] = <class 'hwt.synthesizer.rtlLevel.constants.NOT_SPECIFIED'>)[source]
hwtLib.peripheral.usb.descriptors.std.usb_define_descriptor_string(utf16_char_cnt)[source]
hwtLib.peripheral.usb.descriptors.std.usb_define_descriptor_string0(lang_cnt: int)[source]
hwtLib.peripheral.usb.descriptors.std.usb_format_bMaxPower(mA)[source]
hwtLib.peripheral.usb.sim package
Subpackages
hwtLib.peripheral.usb.sim.usbip package
Submodules
hwtLib.peripheral.usb.sim.usbip.connection module
class hwtLib.peripheral.usb.sim.usbip.connection.USBIPConnection(server: UsbipServer, reader: StreamReader, writer: StreamWriter)[source]

Bases: object

Server container of informations about USBIP client connection

OP_COMMON = '>HIIII'
OP_COMMON_SIZE = 18
OP_SUBMIT = '>IiIIi8s'
OP_SUBMIT_SIZE = 28
__init__(server: UsbipServer, reader: StreamReader, writer: StreamWriter)[source]
async connection()[source]
debug_log(t)[source]
async getDeviceList()[source]

usbctx like function

async handle_op_devlist()[source]
async handle_op_import(busid)[source]
async handle_packet()[source]

Handle a USBIP packet.

async handle_urb_submit(seqnum: int, dev: USBIPDevice, direction, ep)[source]
classmethod make_usbip_header_basic(command: int, seqnum: int, devid: int, direction: int, ep: int)[source]
pack_device_desc(dev: USBIPSimDevice, interfaces=True)[source]

Pack a device descriptors into bytes for stransport to client

classmethod usbip_ret_submit(seqnum, devid, direction, ep, status: int, actual_length: int, error_count: int, transfer_buffer: bytes, iso_start_frame=0, iso_number_of_packets=4294967295, iso_packet_descriptor: bytes = b'')[source]
exception hwtLib.peripheral.usb.sim.usbip.connection.USBIPProtocolErrorException(message)[source]

Bases: Exception

__init__(message)[source]
hwtLib.peripheral.usb.sim.usbip.constants module
hwtLib.peripheral.usb.sim.usbip.device module
class hwtLib.peripheral.usb.sim.usbip.device.LIBUSB_TRANSFER_STATUS[source]

Bases: object

TRANSFER_CANCELLED = 3
TRANSFER_COMPLETED = 0
TRANSFER_ERROR = 1
TRANSFER_NO_DEVICE = 5
TRANSFER_OVERFLOW = 6
TRANSFER_STALL = 4
TRANSFER_TIMED_OUT = 2
class hwtLib.peripheral.usb.sim.usbip.device.USBIPDevice(devid: Tuple[int, int], hnd: USBIPSimDevice)[source]

Bases: object

__init__(devid: Tuple[int, int], hnd: USBIPSimDevice)[source]
packDevid()[source]
class hwtLib.peripheral.usb.sim.usbip.device.USBIPOperationPromise(operation_process, sim, clk)[source]

Bases: object

__init__(operation_process, sim, clk)[source]
_continue_with_clk_triggering()[source]
_pool_process()[source]
fulfill(data)[source]
async pool_sleep_until_fulfil(t)[source]
schedule()[source]
class hwtLib.peripheral.usb.sim.usbip.device.USBIPPending(seqnum, device, xfer)[source]

Bases: object

__init__(seqnum, device, xfer)[source]
class hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice(usb_agent, addr: int, descriptors: UsbDescriptorBundle)[source]

Bases: object

Attention

API of this component should be same as the device from library usb1 if possible because we want to just swap the device object in sim and test the real device as well

__init__(usb_agent, addr: int, descriptors: UsbDescriptorBundle)[source]
close()[source]
async controlRead(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest, wValue, wIndex, wLength)[source]
async controlWrite(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest: int, wValue: int, wIndex: int, data)[source]
Returns

The number of bytes actually sent.

getBusNumber()[source]
getDevice()[source]
getDeviceAddress()[source]
getDeviceClass()[source]
getDeviceProtocol()[source]
getDeviceSpeed()[source]
getDeviceSubClass()[source]
getNumConfigurations()[source]
getProductID()[source]
getTransfer()[source]
getVendorID()[source]
getbcdDevice()[source]
iterConfigurations()[source]
open()[source]
USBIPSimDeviceConfiguration(dev: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice, config_descr: struct usb_descriptor_configuration_t {
USBIPSimDeviceConfiguration    struct usb_descriptor_header_t {
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> bLength
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> bDescriptorType
USBIPSimDeviceConfiguration    } header
USBIPSimDeviceConfiguration    struct usb_descriptor_configuration_body_t {
USBIPSimDeviceConfiguration        <Bits, 16bits, unsigned> wTotalLength
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> bNumInterfaces
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> bConfigurationValue
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> iConfiguration
USBIPSimDeviceConfiguration        struct usb_configuration_body_bmAttributes_t {
USBIPSimDeviceConfiguration            <Bits, 5bits> reserved0
USBIPSimDeviceConfiguration            <Bits, 1bit> remoteWakeup
USBIPSimDeviceConfiguration            <Bits, 1bit> selfPowered
USBIPSimDeviceConfiguration            <Bits, 1bit> reserved1
USBIPSimDeviceConfiguration        } bmAttributes
USBIPSimDeviceConfiguration        <Bits, 8bits, unsigned> bMaxPower
USBIPSimDeviceConfiguration    } body
USBIPSimDeviceConfiguration})

Bases: object

USBIPSimDeviceConfiguration.__init__(dev: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice, config_descr: struct usb_descriptor_configuration_t {
USBIPSimDeviceConfiguration.__init__    struct usb_descriptor_header_t {
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> bLength
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> bDescriptorType
USBIPSimDeviceConfiguration.__init__    } header
USBIPSimDeviceConfiguration.__init__    struct usb_descriptor_configuration_body_t {
USBIPSimDeviceConfiguration.__init__        <Bits, 16bits, unsigned> wTotalLength
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> bNumInterfaces
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> bConfigurationValue
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> iConfiguration
USBIPSimDeviceConfiguration.__init__        struct usb_configuration_body_bmAttributes_t {
USBIPSimDeviceConfiguration.__init__            <Bits, 5bits> reserved0
USBIPSimDeviceConfiguration.__init__            <Bits, 1bit> remoteWakeup
USBIPSimDeviceConfiguration.__init__            <Bits, 1bit> selfPowered
USBIPSimDeviceConfiguration.__init__            <Bits, 1bit> reserved1
USBIPSimDeviceConfiguration.__init__        } bmAttributes
USBIPSimDeviceConfiguration.__init__        <Bits, 8bits, unsigned> bMaxPower
USBIPSimDeviceConfiguration.__init__    } body
USBIPSimDeviceConfiguration.__init__})
USBIPSimDeviceConfiguration.getConfigurationValue()[source]
USBIPSimDeviceConfiguration.getNumInterfaces()[source]
USBIPSimDeviceConfiguration.iterInterfaces()[source]
USBIPSimDeviceInterface(conf: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceConfiguration, descr: struct usb_descriptor_interface_t {
USBIPSimDeviceInterface    struct usb_descriptor_header_t {
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bLength
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bDescriptorType
USBIPSimDeviceInterface    } header
USBIPSimDeviceInterface    struct usb_descriptor_interface_body_t {
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bInterfaceNumber
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bAlternateSetting
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bNumEndpoints
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bInterfaceClass
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bInterfaceSubClass
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> bInterfaceProtocol
USBIPSimDeviceInterface        <Bits, 8bits, unsigned> iInterface
USBIPSimDeviceInterface    } body
USBIPSimDeviceInterface})

Bases: object

USBIPSimDeviceInterface.__init__(conf: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceConfiguration, descr: struct usb_descriptor_interface_t {
USBIPSimDeviceInterface.__init__    struct usb_descriptor_header_t {
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bLength
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bDescriptorType
USBIPSimDeviceInterface.__init__    } header
USBIPSimDeviceInterface.__init__    struct usb_descriptor_interface_body_t {
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bInterfaceNumber
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bAlternateSetting
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bNumEndpoints
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bInterfaceClass
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bInterfaceSubClass
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> bInterfaceProtocol
USBIPSimDeviceInterface.__init__        <Bits, 8bits, unsigned> iInterface
USBIPSimDeviceInterface.__init__    } body
USBIPSimDeviceInterface.__init__})
USBIPSimDeviceInterface.iterSettings()[source]
class hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceInterfaceSetting(intf: USBIPSimDeviceInterface)[source]

Bases: object

__init__(intf: USBIPSimDeviceInterface)[source]
getClass()[source]
getProtocol()[source]
getSubClass()[source]
class hwtLib.peripheral.usb.sim.usbip.device.USBIPTransfer(dev: USBIPSimDevice)[source]

Bases: object

__init__(dev: USBIPSimDevice)[source]
_next_bulk_pid(pid)[source]
getActualLength()[source]
getBuffer()[source]
getStatus()[source]
setBulk(ep: int, buff_or_len: Union[int, bytes], callback: Callable[[USBIPTransfer], None])[source]
async submit()[source]
hwtLib.peripheral.usb.sim.usbip.server module

This server allows to connect virtual USB devices in the simulator directly to any machine which supports USBIP.

Based on https://github.com/jwise/pyusbip/blob/master/pyusbip.py https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html https://forums.aws.amazon.com/thread.jspa?messageID=968176

note

usbip is a part of linux-tools-common apt package but in /usr/bin/ is only a placeholder the /usr/lib/linux-tools-uname -r/usbipd

https://developer.ridgerun.com/wiki/index.php?title=How_to_setup_and_use_USB/IP

note

on some machines /usr/bin/usbip does not work correctly because the version of a kernel slightly differs from version of linux tools /usr/lib/linux-tools-5.8.0-25/usbip /usr/lib/linux-tools-5.9.0-050900-generic/usbip

modprobe vhci_hcd
usbip list -r 127.0.0.1 -l
usbip attach -r 127.0.0.1 -b 0-1

usbip port -r 127.0.0.1
usbip detach -p 00
class hwtLib.peripheral.usb.sim.usbip.server.UsbipServer(usb_ag: UtmiUsbAgent, host='127.0.0.1', port=3240, debug=False)[source]

Bases: object

__init__(usb_ag: UtmiUsbAgent, host='127.0.0.1', port=3240, debug=False)[source]
_start_server(loop)[source]
handle_loop_exception(loop, context)[source]
install_session_recorder(session_recoder: UsbipServerSessionRecorder)[source]
async on_usbip_connection(reader: StreamReader, writer: StreamWriter)[source]
run()[source]
terminate()[source]
hwtLib.peripheral.usb.sim.usbip.session_recorder module
class hwtLib.peripheral.usb.sim.usbip.session_recorder.UsbipServerReplayer(usb_ag: UtmiUsbAgent, session_data, debug=False)[source]

Bases: UsbipServer

class Reader(sim: HdlSimulator, data: Deque[Tuple[int, str, List[int]]])[source]

Bases: object

__init__(sim: HdlSimulator, data: Deque[Tuple[int, str, List[int]]])[source]
async readexactly(size) bytes[source]
class Writer(sim: HdlSimulator, ref_data: Deque[List[int]])[source]

Bases: object

__init__(sim: HdlSimulator, ref_data: Deque[List[int]])[source]
close()[source]
async drain()[source]
get_extra_info(name)[source]
write(data: bytes)[source]
__init__(usb_ag: UtmiUsbAgent, session_data, debug=False)[source]
_start_server(loop)[source]
async on_usbip_connection(reader: StreamReader, writer: StreamWriter)[source]
class hwtLib.peripheral.usb.sim.usbip.session_recorder.UsbipServerSessionRecorder(sim: HdlSimulator)[source]

Bases: object

Used to record the client-server communication in hwtLib.peripheral.usb.sim.usbip.server.UsbipServer for later replay.

class Reader(sim: HdlSimulator, original: StreamReader, dst: List[List[int]])[source]

Bases: object

__init__(sim: HdlSimulator, original: StreamReader, dst: List[List[int]])[source]
async readexactly(size)[source]
class Writer(sim: HdlSimulator, original: StreamWriter, dst: List[List[int]])[source]

Bases: object

__init__(sim: HdlSimulator, original: StreamWriter, dst: List[List[int]])[source]
close()[source]
async drain()[source]
get_extra_info(name)[source]
write(data)[source]
__init__(sim: HdlSimulator)[source]
apply(reader: StreamReader, writer: StreamWriter)[source]
hwtLib.peripheral.usb.sim.usbip.session_recorder.cut_off_empty_time_segments(data: List[Tuple[int, str, List[int]]], time_segments: List[Tuple[int, int]]) List[Tuple[int, str, List[int]]][source]
Note

if time segments contains some transaction the assertion error is raised

Note

if segment (0,10) is cut off from times 0, 10, 11 it becomes 0, 1, 2

Parameters

time_segments – list of ranges of times to cut off (the time after is shifted)

Returns

filtered list of data from input

hwtLib.peripheral.usb.sim.usbip.session_recorder.filter_empty_in(_data: List[Tuple[int, str, List[int]]], seqnum_to_rm: Set[int]) List[Tuple[int, str, List[int]]][source]

Remove empty IN transfers from endpoints other than 0 and remove transactions by seqnum

Parameters
  • _data – list of tuples time, r/w, list of bytes

  • seqnum_to_rm – set of seqnum to remove (all parts of the transaction with that specified seqnum are removed entirely)

  • cut_off_segments – list of ranges of times to cut off (the time after is shifted)

Returns

filtered list of data from input

Submodules
hwtLib.peripheral.usb.sim.agent_base module
class hwtLib.peripheral.usb.sim.agent_base.UsbAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]

Bases: object

__init__(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]
deparse_packet(p)[source]

Called to convert the packet from types supported by this class before putting into tx/rx queue

parse_packet(p)[source]

Called to convert the packet from tx/rx queues to types supported by this class

receive(packet_cls)[source]
send(p)[source]

send and wait until other side consumes the data

send_ack()[source]
wait_on_ack()[source]
class hwtLib.peripheral.usb.sim.agent_base.UsbPacketData(pid: int, data: List[int])[source]

Bases: object

__init__(pid: int, data: List[int])[source]
__repr__()[source]

Return repr(self).

crc16()[source]
unpack(t: HdlType)[source]

reinterpret data as specified type

class hwtLib.peripheral.usb.sim.agent_base.UsbPacketHandshake(pid: USB_PID)[source]

Bases: object

__init__(pid: USB_PID)[source]
__repr__()[source]

Return repr(self).

class hwtLib.peripheral.usb.sim.agent_base.UsbPacketToken(pid: USB_PID, addr: int, endp: int)[source]

Bases: object

Note

bits of individual items are sent in LSB first but the items of the packet are sent in the oreder defined by structure of the packet

__init__(pid: USB_PID, addr: int, endp: int)[source]
__repr__()[source]

Return repr(self).

crc5()[source]
classmethod from_pid_and_body_bytes(pid: int, addr_ep_crc_byte_list: Union[BitsVal, List[BitsVal]])[source]
hwtLib.peripheral.usb.sim.usb_agent_device module
class hwtLib.peripheral.usb.sim.usb_agent_device.UsbDevAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData]], tx: Deque[Union[UsbPacketToken, UsbPacketData]], descriptors: UsbDescriptorBundle)[source]

Bases: UsbAgent

This agent uses rx and tx queue to comunicate with a USB device. The agnet implements address assignment and descriptor upload and it is meant to be extended with a specific functionality of USB device.

__init__(rx: Deque[Union[UsbPacketToken, UsbPacketData]], tx: Deque[Union[UsbPacketToken, UsbPacketData]], descriptors: UsbDescriptorBundle)[source]
get_data_pid()[source]
proc()[source]
send_data(endp: int, pid_init: USB_PID, maxPacketLen: int, data_bytes: List[int])[source]
set_data_pid(pid: USB_PID)[source]
hwtLib.peripheral.usb.sim.usb_agent_host module
class hwtLib.peripheral.usb.sim.usb_agent_host.UsbHostAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]

Bases: UsbAgent

This agent uses rx and tx queue to comunicate with a USB device. It performs bus enumerations, sets address to a device and downloads the descriptors. Note that the agent is written in a way which allows for easy extension to a driver which can parse the specific descriptors and comunicate with devices further.

__init__(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]
control_read(addr, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bRequest: int, wValue: int, wIndex: int, wLength: int, bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT = 0, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION = 1)[source]
control_write(addr: int, ep: int, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bRequest: int, wValue: int, wIndex: int, buff: List[int], bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT = 0, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION = 0)[source]
download_descriptor(addr: int, descriptor_t: ~typing.Union[~hwt.hdl.types.struct.HStruct, str], index: int, wIndex: int = 0, wLength: ~typing.Optional[int] = <class 'hwt.synthesizer.rtlLevel.constants.NOT_SPECIFIED'>)[source]
get_max_packet_size(addr: int, endp: int, direction: USB_ENDPOINT_DIR)[source]
parse_configuration_descriptor_bundle(data_bytes: List[int])[source]
parse_interface_functional_descriptor(interface_descr: StructValBase, data: BitsVal)[source]
proc()[source]
receive_bulk(addr: int, endp: int, pid_init: ~hwtLib.peripheral.usb.constants.USB_PID, size=<class 'hwt.synthesizer.rtlLevel.constants.NOT_SPECIFIED'>) List[int][source]
transmit_bulk(addr: int, endp: int, pid_init: USB_PID, data_bytes: List[int])[source]
Submodules
hwtLib.peripheral.usb.constants module
attention

on USB the LSB bits are sent first

class hwtLib.peripheral.usb.constants.USB_LINE_STATE[source]

Bases: object

J = 1
K = 2
SE0 = 0
SE1 = 3
class hwtLib.peripheral.usb.constants.USB_PID[source]

Bases: object

USB Protocol layer packet identifier values (Specifies the type of transaction)

Attention

visualy written in msb-first, transmited in lsb first

Note

packet formats are described in structs in this file

Note

if the PID is in 8b format the other 4 bits (check field) are a bitwise inversion of original 4b PID field

DATA_0 = 3
DATA_1 = 11
DATA_2 = 7
DATA_M = 15
ERR = 12
HS_ACK = 2
HS_NACK = 10
HS_NYET = 6
HS_STALL = 14
PING = 4
PREAMBLE = 12
SPLIT = 8
TOKEN_IN = 9
TOKEN_OUT = 1
TOKEN_SETUP = 13
TOKEN_SOF = 5
classmethod is_data(v: Union[int, RtlSignalBase])[source]
classmethod is_hs(v: Union[int, RtlSignalBase])[source]
classmethod is_token(v: Union[int, RtlSignalBase])[source]
class hwtLib.peripheral.usb.constants.USB_VER[source]

Bases: object

USB_VER

Speed

1.0 - 2.0

Low Speed 1.5 Mbit/s

1.0 - 2.0

Full Speed 12 Mbit/s

2.0

High Speed 480 Mbit/s

3.0

SuperSpeed 5Gbit/s

3.1

SuperSpeed+ 10Gbit/s

3.2

SuperSpeed+ 20Gbit/s

4.0

SuperSpeed+ 40Gbit/s

USB1_0 = '1.0'
USB1_1 = '1.1'
USB2_0 = '2.0'
USB3_0 = '3.0'
USB3_1 = '3.1'
USB3_2 = '3.2'
USB4_0 = '4.0'
static from_uint16_t(usbVer: int)[source]
static to_uint16_t(usbVer: str)[source]
values = ['1.0', '1.1', '2.0', '3.0', '3.1', '3.2', '4.0']
hwtLib.peripheral.usb.constants.usb2_0_packet_data_t = struct {     <Bits, 4bits> pid     <HStream len:(1, 1024), align:(0,)         <Bits, 8bits>> data     <Bits, 16bits> crc }

There are three type of handshake packets which consist simply of the USB_PID

  • ACK - Acknowledgment that the packet has been successfully received.

  • NAK - Reports that the device temporary cannot send or received data. Also used during interrupt transactions to inform the host there is no data to send.

  • STALL - The device finds its in a state that it requires intervention from the host.

hwtLib.peripheral.usb.constants.usb_packet_hs_t = struct {     <Bits, 4bits> pid }

The SOF (Start of Frame) packet consisting of an 11-bit frame number is sent by the host every 1ms ± 500ns on a full speed bus or every 125 µs ± 0.0625 µs on a high speed bus.

hwtLib.peripheral.usb.constants.usb_pid_t = <Bits, 4bits>
Attention

every packet starts with sync and ends in EOP, which is not in data structures below

hwtLib.peripheral.usb.device_request module
class hwtLib.peripheral.usb.device_request.USB_REQUEST[source]

Bases: object

Values for usb_device_request_t.bRequest

CLEAR_FEATURE = 1
GET_CONFIGURATION = 8
GET_DESCRIPTOR = 6
GET_INTERFACE = 10
GET_STATUS = 0
SET_ADDRESS = 5
SET_CONFIGURATION = 9
SET_DESCRIPTOR = 7
SET_FEATURE = 3
SET_INTERFACE = 17
SYNCH_FRAME = 18
class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_DIRECTION[source]

Bases: object

Values for usb_request_type_t.recipient

DEV_TO_HOST = 1
HOST_TO_DEV = 0
class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_RECIPIENT[source]

Bases: object

Values for usb_request_type_t.data_transfer_direction

DEVICE = 0
ENDPOINT = 2
INTERFACE = 1
OTHER = 3
class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_TYPE[source]

Bases: object

Values for usb_request_type_t.type

CLASS = 1
STANDARD = 0
VENDOR = 2
hwtLib.peripheral.usb.device_request.make_usb_device_request(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest: USB_REQUEST, wValue: int, wIndex: int, wLength: int)[source]

hwtLib.sim package

Submodules
hwtLib.sim.abstractMemSpaceMaster module
class hwtLib.sim.abstractMemSpaceMaster.AbstractMemSpaceMaster(bus, registerMap)[source]

Bases: MemorySpaceItemStruct

Abstraction over bus interface which converts it to memory space from where you can read or write

__init__(bus, registerMap)[source]
_mask(start, width)[source]
_read(addr, size, onDone=None)[source]

Add read transaction to agent of interface :param addr: address value on bus to read froms :param size: size of data to read in bites :param onDone: on read done callback function(sim) -> None

_write(addr, size, data, mask, onDone=None)[source]

Add write transaction to agent of interface

Parameters
  • addr – address value on bus to write on

  • size – size of data to write in bites

  • data – data to write on bus

  • onDone – on write done callback function(sim) -> None

parse_responses()[source]

Parse responses after sim

class hwtLib.sim.abstractMemSpaceMaster.MemorySpaceItem(memHandler, transTmpl, offset=0)[source]

Bases: object

Abstraction over place in memory, allows you read and write data to/from this space

__init__(memHandler, transTmpl, offset=0)[source]
_add_read_resp(resp)[source]
_add_write_resp(resp)[source]
read(onDone=None)[source]

read data from place in memory

write(data, onDone=None)[source]

write data to place in memory

class hwtLib.sim.abstractMemSpaceMaster.MemorySpaceItemArr(memHandler, transTmpl, offset=0)[source]

Bases: object

Abstraction over place in memory, allows you read and write data to/from this space

__getitem__(index)[source]
__init__(memHandler, transTmpl, offset=0)[source]
class hwtLib.sim.abstractMemSpaceMaster.MemorySpaceItemStruct(memHandler, transTmpl, offset=0)[source]

Bases: object

__init__(memHandler, transTmpl, offset=0)[source]
_decorateWithRegisters(memHandler, structT)[source]

Decorate this object with attributes from memory space (name is same as specified in register map)

Parameters
  • memHandler – instance of AbstractMemSpaceMaster(subclass of)

  • structT – instance of HStruct or TransTmpl used as template

hwtLib.tools package

Submodules
hwtLib.tools.debug_bus_monitor_ctl module
class hwtLib.tools.debug_bus_monitor_ctl.Colorizer[source]

Bases: object

A base class for objects which looks at the data and resolves color of the output text/element

get_color(name: str, data_spec: list, data: int)[source]
class hwtLib.tools.debug_bus_monitor_ctl.ColorizerHandshakeOrEnLike[source]

Bases: Colorizer

LIGHT_GREEN = '#90ee90'
LIGHT_PURPLE = '#b19cd9'
LIGHT_RED = '#ffcccb'
_get_intf_names(data_spec)[source]
_try_get_intf_index_by_name(intfs: Dict[str, Tuple[int, Tuple[int, int]]], names: List[str], data) Optional[int][source]
get_color(name: str, data_spec: list, data: int)[source]
class hwtLib.tools.debug_bus_monitor_ctl.DebugBusMonitorCtl(addr)[source]

Bases: object

A tool used to interact with a hwtLib.abstract.debug_bus_monitor.DebugBusMonitor

REG_DATA_MEMORY = 8
REG_NAME_MEMORY_OFFSET = 4
REG_NAME_MEMORY_SIZE = 0
__init__(addr)[source]
_decode_meta_memory_json(data: list)[source]
_dump_dot_node_set(meta_memory: List[VisualNodeTemplate], out: StringIO, colorizer: Colorizer, data: int, indent: int) None[source]
_load_meta_and_data() int[source]
construct_id_to_node_dict(meta_memory: List[VisualNodeTemplate], res: Dict[int, VisualNodeTemplate])[source]
dump_dot(out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, colorizer=<hwtLib.tools.debug_bus_monitor_ctl.ColorizerHandshakeOrEnLike object>) None[source]
dump_txt(out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[source]
get_data_memory_width(meta_memory: Union[VisualNodeTemplate, list, List[int]])[source]
load_meta_memory()[source]
read(addr: int, size: int)[source]
read_int(addr: int, size: int) int[source]
class hwtLib.tools.debug_bus_monitor_ctl.DebugBusMonitorCtlDevmem(addr)[source]

Bases: DebugBusMonitorCtl

__init__(addr)[source]
data_memory_size: Optional[int]
meta_memory: Optional[VisualNodeTemplate]
read(addr, size)[source]
class hwtLib.tools.debug_bus_monitor_ctl.VisualNodeTemplate(id_: int, name: str, data_spec: list, parent: Optional[VisualNodeTemplate] = None)[source]

Bases: object

__init__(id_: int, name: str, data_spec: list, parent: Optional[VisualNodeTemplate] = None)[source]
_default_dot_formatter(data: int, out: StringIO, indent: int, colorizer: Optional[Colorizer]) str[source]

Format interface signals and values as a html like table for graphwiz

classmethod _default_txt_formatter(name: str, data_spec, children: List[VisualNodeTemplate], data: int, out: StringIO, indent: int)[source]
classmethod _dump_txt_indent(out: StringIO, indent: int)[source]
classmethod _format_data(data, data_spec: Tuple[int, int])[source]
classmethod _get_intf_depth(data_spec: Union[dict, Tuple[int, int]]) int[source]
classmethod _visual_format_intf_rows(name: str, data_spec: Union[dict, Tuple[int, int]], buff: StringIO, column_cnt: int, cur_indent: int, data: int, text_indent: int, colorizer: Optional[Colorizer]) None[source]
hwtLib.tools.debug_bus_monitor_ctl.bit_mask(w)[source]
Note

duplication with pyMathBitPrecise in order to keep this script without non-std dependencies

hwtLib.tools.debug_bus_monitor_ctl.select_bit_range(val: int, bits_start: int, bits_len: int)[source]

Get sequence of bits from an int value

Note

duplication with pyMathBitPrecise in order to keep this script without non-std dependencies

hwtLib.tools.debug_bus_monitor_ctl.words_to_int(words, word_size, size)[source]

hwtLib.types package

Subpackages
hwtLib.types.net package
Submodules
hwtLib.types.net.arp module
class hwtLib.types.net.arp.ARP_HW_TYPE[source]

Bases: object

ARP_SEC = 32
ETHERNET = 1
FIBRE_CHANNEL = 18
FRAME_RELAY = 15
INIFNIBAND = 32
IP_SEC_TUNNEL = 31
class hwtLib.types.net.arp.ARP_OPTCODE[source]

Bases: object

ARP_NAK = 10
class DRARP[source]

Bases: object

ERROR = 7
REPLY = 6
REQUEST = 5
IN_ARP_REPLY = 9
IN_ARP_REQUEST = 8
MAPOS_UNARP = 23
class MARS[source]

Bases: object

GROUPLIST_REPLY = 21
GROUPLIST_REQUEST = 20
JOIN = 14
LEAVE = 15
MSERV = 13
MULTI = 12
NAK = 16
REDIRECT_MAP = 22
REQUEST = 11
SJOIN = 18
SLEAVE = 19
UNSERV = 17
OP_EXP1 = 24
OP_EXP2 = 25
REPLY = 2
REQUEST = 1
REQUEST_REVERSE = 3
hwtLib.types.net.dpdk module
hwtLib.types.net.ethernet module
class hwtLib.types.net.ethernet.ETHER_TYPE[source]

Bases: object

ARP = 2054
IPX = 33079
IPX_b = 33080
IPv4 = 2048
IPv6 = 34525
MPLS_multicast = 34888
MPLS_unicast = 34887
QNX_qnet = 33284
VLAN_1AD = 34984
VLAN_1Q = 33024
WoL = 2114
hwtLib.types.net.ethernet.eth_addr_format(mac: List[Union[int, str]])[source]
hwtLib.types.net.ethernet.eth_addr_parse(macStr: str)[source]
hwtLib.types.net.icmp module
class hwtLib.types.net.icmp.ICMP_TYPE[source]

Bases: object

DESTINATION_UNREACHABLE = 3
ECHO_REPLY = 0
ECHO_REQUEST = 8
PARAMETER_PROBLE = 12
REDIRECT = 5
ROUTER_ADVERTISEMENT = 9
ROUTER_SOLICITATION = 10
TIMESTAMP = 13
TIMESTAMP_REPLY = 14
TIME_EXCEEDED = 11
TRACEROUTE = 30
hwtLib.types.net.ip module
class hwtLib.types.net.ip.IP_FLAGS[source]

Bases: object

DONT_FRAGMENT = 2
MORE_FRAGMENTS = 4
class hwtLib.types.net.ip.IP_PROTOCOL[source]

Bases: object

EGP = 8
ENCAP = 41
ETHERIP = 97
GGP = 3
HOPOPT = 0
ICMP = 1
IGMP = 2
IGP = 9
IPIP = 94
IPv4 = 4
IPv6_ICMP = 58
IPv6_frag = 44
IPv6_noNxt = 59
IPv6_opts = 60
IPv6_route = 43
L2TP = 115
OSPF = 89
QNX = 106
SCTP = 132
SMP = 121
TCP = 6
UDP = 17
hwtLib.types.net.tcp module
hwtLib.types.net.udp module
Submodules
hwtLib.types.ctypes module

hwtLib.xilinx package

Subpackages
hwtLib.xilinx.primitive package
Subpackages
hwtLib.xilinx.primitive.examples package
Submodules
hwtLib.xilinx.primitive.examples.dsp48e1Add module
class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1Add(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

postpone_val(sig_in, clock_enables: List[RtlSignal], name_prefix=None)[source]

Generate a register pipeline which can be used to dealy a value, the length of pipeline is derived from number of clock_enable signals

set_mode(dsp)[source]
class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1AluInput(masterDir=DIRECTION.OUT, hdl_name: Optional[Union[str, Dict[str, str]]] = None, loadConfig=True)[source]

Bases: HandshakeSync

_initSimAgent(sim: HdlSimulator)[source]
class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1AluInputAG(sim: HdlSimulator, intf: Handshaked, allowNoReset=False)[source]

Bases: HandshakedAgent

get_data()[source]

extract data from interface

set_data(data)[source]

write data to interface

hwtLib.xilinx.primitive.examples.dsp48e1Add.generate_handshake_pipe_cntrl(parent: Unit, n: int, name_prefix: str, in_valid: RtlSignal, out_ready: RtlSignal)[source]

An utility that construct a pipe of registers to store the validity status of a register in the pipeline. These registers are connected in pipeline and synchronized by handshake logic. Clock enable signal for each stage in pipeline is also provided.

Variables

~.n – number of stages

Submodules
hwtLib.xilinx.primitive.dsp48e1 module
class hwtLib.xilinx.primitive.dsp48e1.DSP48E1(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

DSP hadblock in Xilinx 7 series (2x pre adder, multiplier, ALU)

See

https://www.xilinx.com/support/documentation/user_guides/ug479_7Series_DSP48E1.pdf

deassign_xyz_mux()[source]
display_invalid_opmode()[source]
input_check()[source]
hwtLib.xilinx.primitive.dsp48e1_constants module
class hwtLib.xilinx.primitive.dsp48e1_constants.CARRYIN_SEL(value)[source]

Bases: Enum

An enumeration.

A_27_eq_B_17 = 6
CARRYCASCIN = 2
CARRYCASCOUT = 4
CARRYIN = 0
PCIN_47 = 3
PCIN_47_n = 1
P_47 = 7
P_47_n = 5
class hwtLib.xilinx.primitive.dsp48e1_constants.MUL_A_SEL(value)[source]

Bases: Enum

An enumeration.

A1 = 1
A2 = 0
D = 5
D_MINUS_A1 = 9
D_MINUS_A2 = 8
D_PLUS_A1 = 4
D_PLUS_A2 = 3
MINUS_A1 = 7
MINUS_A2 = 6
ZERO = 2
class hwtLib.xilinx.primitive.dsp48e1_constants.MUL_B_SEL(value)[source]

Bases: Enum

An enumeration.

B1 = 1
B2 = 0
class hwtLib.xilinx.primitive.dsp48e1_constants.X_SEL(value)[source]

Bases: Enum

An enumeration.

A_B = 3
M = 5
P = 2
ZERO = 0
class hwtLib.xilinx.primitive.dsp48e1_constants.Y_SEL(value)[source]

Bases: Enum

An enumeration.

C = 12
M = 5
MINUS_1 = 8
ZERO = 0
class hwtLib.xilinx.primitive.dsp48e1_constants.Z_SEL(value)[source]

Bases: Enum

An enumeration.

C = 48
P = 32
PCIN = 16
PCIN_SHIFT_17b = 80
P_MACC = 72
P_SHIFT_17b = 96
ZERO = 0
hwtLib.xilinx.primitive.dsp48e1_constants.get_inmode(AREG: int, USE_DPORT: bool, mul_a_sel: MUL_A_SEL, mul_b_sel: MUL_B_SEL)[source]
hwtLib.xilinx.primitive.dsp48e1_constants.get_opmode(x: X_SEL, y: Y_SEL, z: Z_SEL)[source]
hwtLib.xilinx.primitive.lutAsShiftReg module
class hwtLib.xilinx.primitive.lutAsShiftReg.LutAsShiftReg(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

This components generates SRL16E and other shift registers.

In order to allow Xilinx Vivado 2020.2 (and possibly any other version) to map this component into SRL16E and equivalents we need to satisfy several conditions: 1. the memory must not have reset 2. the shift expressions must be performed on a single signal 3. whole memory must be single signal 4. the output must be read only by index operator (switch on address does not work) 5. we can not merge memories of individual data bits

hwtLib.xilinx.primitive.mmcme2 module
class hwtLib.xilinx.primitive.mmcme2.MMCME2_ADV(hdl_name_override: Optional[str] = None)[source]

Bases: Unit

Mixed-Mode Clock Manager (PLL like frequency synchronizer/clock generator) on Xilinx 7+ series

https://www.xilinx.com/support/documentation/user_guides/ug472_7Series_Clocking.pdf

clkout_duty_chk(CLKOUT_DIVIDE, CLKOUT_DUTY_CYCLE, CLKOUT_DUTY_CYCLE_N)[source]
param_range_chk(para_in, para_name, range_low, range_high)[source]
type_check_bit_param(name)[source]
type_check_bool_param(name)[source]
Submodules
hwtLib.xilinx.constants module
hwtLib.xilinx.platform module
class hwtLib.xilinx.platform.XilinxVivadoPlatform(part: Optional[str] = None)[source]

Bases: DummyPlatform

__init__(part: Optional[str] = None)[source]
hwtLib.xilinx.slr_crossing module
class hwtLib.xilinx.slr_crossing.HsSlrCrossing(hdl_name_override: Optional[str] = None)[source]

Bases: HsSlrCrossingIo

Super Logic Region (SLR) crossing for handshaked interfaces

SLR represents one chiplet of FPGA which uses stacked silicon interconnect (SSI) or equivalent. The SLR corssing is required on SLR boundaries to met the timing. The crossing itself is just a pipeline of registers.

class hwtLib.xilinx.slr_crossing.HsSlrCrossingIo(hdl_name_override: Optional[str] = None)[source]

Bases: BusBridge

An abstract class with a declaration of interfaces for handskaked SLR crosings

class hwtLib.xilinx.slr_crossing.SlrCrossingDst(hdl_name_override: Optional[str] = None)[source]

Bases: HsSlrCrossingIo

A part of SLR crossing which should be placed in SLR of consumer

class hwtLib.xilinx.slr_crossing.SlrCrossingSrc(hdl_name_override: Optional[str] = None)[source]

Bases: HsSlrCrossingIo

A part of SLR crossing which should be placed in SLR of producer

Indices and tables