p4 spec v1.1 (1185620), страница 5

Файл №1185620 p4 spec v1.1 (Домашнее задание) 5 страницаp4 spec v1.1 (1185620) страница 52020-08-25СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 5)

The reason is that oftenthe implicit casts have a non-trivial semantics, which is invisible for the programmer.Implicit casts are allowed in P4 only when their meaning is completely unambiguous:• To convert an int value to a fixed-width type.• In assignments (including passing arguments to method calls), when RHS has adifferent type from LHS.Most binary operations that take an int and a fixed-width operand will insert an implicit cast to convert the int operand to the type of the fixed-width operand.Consider a program with the following values:bit<8>x;bit<16> y;int<8>z;Table 9 shows how implicit casts are inserted by the compiler:232.6 Casts2 STRUCTURE OF THE P4 LANGUAGEExpressionImplementationx+1x+(bit<8>)1z<0z<(int<8>)0x<<130; overflow warningx|0xFFFx|(bit<8>)0xFFF; overflow warningTable 9: Examples of implicit casts.2.6.3 Illegal expressionsConsider a program with the following values:bit<8>x;bit<16> y;int<8>z;Table 10 shows several expressions which are illegal because they do not obey the P4typing rules.

For each expression we provide several ways that the expression couldbe manually rewritten into a legal expression. Note that for some expression there areseveral legal alternatives, which may produce different results!Expressionx+yWhy is it illegalDifferent widthsAlternatives(bit<16>)x+y orx+(bit<8>)yx+zDifferent signs(int<8>)x+z orx+(bit<8>)z(int<8>)yCannot change both size and widthy+zDifferent widths and signs(int<8>)(bit<8>)y or(int<8>)(int<16>)y(int<8>)(bit<8>)y+z ory+(bit<16>)(bit<8>)z or(bit<8>)y+(bit<8>)z or(int<16>)y+(int<16>)zx<<zx<zRHS of shift cannot be signedDifferent signsx<<(bit<8>)zx<(bit<8>)z or(int<8>)x<z1<<xWidth of 1 unknown((bit<32>)1)<<x or32w1<<x˜15&-3Bitwise operation on intBitwise operation on int˜32w132w5&-3Table 10: Illegal P4 expressions.242.7 References2 STRUCTURE OF THE P4 LANGUAGE2.7 ReferencesConcrete instances of the above types are referenced via their instance names.

P4 islexically scoped.object_ref ::=instance_name |header_ref |field_refThe terminal instance_name refers to any named object, while header and field references are handled specially as described in Section 3.3.2.8 ExpressionsVarious language constructs can contain expressions built out of these object references.general_expr ::=bool_expr | arith_expr | const_expr | object_refbool_expr ::=valid ( object_ref ) | bool_expr bool_op bool_expr |not bool_expr | ( bool_expr ) | arith_expr rel_op arith_expr |bool_valuearith_expr ::=object_ref | const_value |max ( arith_expr , arith_expr ) | min ( arith_expr , arith_expr ) |( arith_expr ) | arith_expr bin_op arith_expr | un_op arith_expr |( data_type ) arith_exprconst_expr ::= const_value |max ( const_expr , const_expr ) | min ( const_expr, const_expr ) |( const_expr ) | const_expr bin_op const_expr | un_op const_exprbin_op ::= "+" | "*" | - | << | >> | & | "|" | ^un_op ::= ~ | bool_op ::= or | andrel_op ::= > | >= | == | <= | < | !=252.9 Pragma3 HEADERS AND FIELDSOperator precedence and associativity follows C programming conventions.The min and max functions return whatever is the smaller or larger of their two arguments, respectively, or the first argument if the two compare equally.2.9 PragmaA P4 program may make use of directives for compilers.

The specific meanings of anydirectives are compiler specific and target specific, which are beyond the scope of thisspecification. The P4 grammar that enables this feature is as follows. pragma_text isany string or strings up to the end of the line.p4_pragma ::= @pragma pragma_name pragma_text3Headers and Fields3.1 Header Type DeclarationsHeader types describe the layout of fields and provide names for referencing information. Header types are used to declare header and metadata instances. These are discussed in the next section.Header types are specified declaratively according to the following BNF:header_type_declaration ::=header_type header_type_name { header_dec_body }header_dec_body ::=fields { field_dec * }[ length : length_exp ; ]field_dec ::= data_type field_name ;length_bin_op ::= "+" | - | "*" | << | >>length_exp ::=const_expr |field_name |length_exp length_bin_op length_exp |( length_exp )Header types are defined with the following conventions.263.1 Header Type Declarations3 HEADERS AND FIELDS• Header types must have a fields attribute.– The list of individual fields is ordered.– Fields must be either of type bit or varbit.– The bit offset of a field from the start of the header is determined by the sumof the widths of the fields preceding it in the list.– Bytes are ordered sequentially (from the packet ordering).– Bits are ordered within bytes by most-significant-bit first.

Thus, if the firstfield listed in a header has a bit width of 1, it is the high order bit of the firstbyte in that header.– All bits in the header must be allocated to some field.– One field at most within a header type may be of type varbit, which indicatesit is of variable length.• If all fields are fixed width (no fields of type varbit) then the header is said to be offixed length. Otherwise it is of variable length.• A header length in bits must be a multiple of eight.

In other words, a header canhave only a natural number of bytes.• The length attribute specifies an expression whose evaluation gives the length ofthe header in bytes for variable length headers.– It must be present if the header has variable length (some field has type varbit).– A compiler warning must be generated if it is present for a fixed length header.– Fields referenced in the length attribute must be located before the variablelength field.• If, at run time, the calculated length results in more data extracted to the varbitthan its declared maximum length a parser exception is triggered. See Section 5.6.• Operator precedence and associativity follows C programming conventions.An example declaration for a VLAN header (802.1Q) is:header_type vlan_t {fields {bit<3>pcp;bitcfi;bit<12> vid;bit<16> ethertype;273.1 Header Type Declarations3 HEADERS AND FIELDS}}Metadata header types are declared with the same syntax.header_type packet_metadata_t {fields {bit<16> ingress_port; // The port on which the packet arrived.bit<16> length;// The number of bytes in the packet.// For Ethernet, does not include the CRC.// Cannot be used if the switch is in// ’cut-through’ mode.bit<8>type;// Represents the type of instance of// the packet://- PACKET_TYPE_NORMAL//- PACKET_TYPE_INGRESS_CLONE//- PACKET_TYPE_EGRESS_CLONE//- PACKET_TYPE_RECIRCULATED// Specific compilers will provide macros// to give the above identifiers the// appropriate values}}P4 supports variable-length packet headers via fields of type varbit.

The width of sucha field is inferred from the total header length (which is in bytes) as indicated by thelength attribute: ((8 * length) - sum-of-fixed-width-fields). Only one field atmost within a header may specify a field of type varbit.An example of a variable-width header is IPv4 with options:header_type ipv4_t {fields {bit<4> version;bit<4> ihl;bit<8> diffserv;bit<16> totalLen;bit<16> identification;bit<3> flags;bit<13> fragOffset;bit<8> ttl;283.2 Header and Metadata Instances3 HEADERS AND FIELDSbit<8> protocol;bit<16> hdrChecksum;bit<32> srcAddr;bit<32> dstAddr;varbit<320> options;}length : ihl * 4;}This header can be parsed and manipulated the same way fixed-length headers are,with the exception that there are no language facilities to read or write data in the options field.3.2 Header and Metadata InstancesWhile a header type declaration defines a header type, a packet may contain multipleinstances of a given type.

P4 requires each header instance to be declared explicitlyprior to being referenced.There are two sorts of header instances: packet headers and metadata. Usually, packetheaders are identified from the packet as it arrives at ingress while metadata holds information about the packet that is not normally represented by the packet data such asingress port or a time stamp.Most metadata is simply per-packet state used like scratch memory while processinga packet. However, some metadata may have special significance to the operation ofthe forwarding element.

For example, the queuing system may interpret the value of aparticular metadata field when choosing a queue for a packet. P4 acknowledges thesetarget specific semantics, but does not attempt to represent them.Packet headers (declared with the header keyword) and metadata (declared with themetadata keyword) differ only in their validity. Packet headers maintain a separate validindication which may be tested explicitly. Metadata is always considered to be valid.This is further explained in Section 3.2.1. Metadata instances are initialized to 0 bydefault, but initial values may be specified in their declaration.The BNF for header and metadata instances is:header_instance_declaration ::= header_instance | metadata_instanceheader_instance ::= scalar_instance | array_instancescalar_instance ::= header header_type_name instance_name ;array_instance ::=header header_type_nameinstance_name "[" const_expr "]" ;293.2 Header and Metadata Instances3 HEADERS AND FIELDSmetadata_instance ::=metadata header_type_nameinstance_name [ metadata_initializer ] | ;metadata_initializer ::= { [ field_name : field_value ; ] + }Some notes:• Only packet headers (not metadata instances) may be arrays (header stacks).• header_type_name must be the name of a declared header type.• Metadata instances may not be declared with variable length header types.• The fields named in the initializer must be from the header type’s fields list.• If an initializer is present, the named fields are initialized to the indicated values;unspecified values are initialized to 0.• The total length of all fields in a header instance must be an integral number ofbytes.

The compiler may produce an error or insert padding at the end of theheader to resolve this issue.• Only packet headers (not metadata instances) may be arrays (header stacks).For example:header vlan_t inner_vlan_tag;This indicates that space should be allocated in the Parsed Representation of the packetfor a vlan_t header. It may be referenced during parsing and match+action by the nameinner_vlan_tag.A metadata example is:metadata global_metadata_t global_metadata;This indicates that an global_metadata_t type object called global_metadata shouldbe allocated for reference during match+action.3.2.1 Testing if Header and Metadata Instances are ValidPacket headers and their fields may be checked for being valid (that is, having a definedvalue).

Характеристики

Тип файла
PDF-файл
Размер
1,13 Mb
Тип материала
Высшее учебное заведение

Список файлов курсовой работы

Домашнее задание
VasilenkoAE_521 (switch openflow start)
staticNAT
p4factory
mininet
lvk_demo.py
targets
lvk_task
openflow_mapping
l2.py
l2.pyc
mapping_common.py
mapping_common.pyc
p4src
includes
headers.p4
parser.p4
lvk_task.p4
targets
libpd_thrift
libtbl_packing
tests
pd_thrift
conn_mgr_pd_rpc
__init__.py
__init__.pyc
conn_mgr-remote.
conn_mgr.py
conn_mgr.pyc
constants.py
ttypes.py
ttypes.pyc
devport_mgr_pd_rpc
Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6510
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее