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

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

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

Figure 2 shows a very simpleexample. Note that this figure identifies a header with each state. While P4 supportsthis approach, it does not require it. A node in the parse graph may be purely a decisionnode and not bound to a particular header instance, or a node may process multipleheaders at once.Figure 2: Simple Parse Graph and mTag Parse GraphHere are a few of the P4 parser functions for the mTag parser. The start function callsethernet directly.parser ethernet {extract(ethernet);// Start with the ethernet headerreturn select(latest.ethertype) {0x8100:vlan;0x800:ipv4;default:ingress;}}parser vlan {extract(vlan);365.1 Parsed Representation5 PARSER SPECIFICATIONreturn select(latest.ethertype) {0xaaaa:mtag;0x800:ipv4;default:ingress;}}parser mtag {extract(mtag);return select(latest.ethertype) {0x800:ipv4;default:ingress;}}The reference to ingress terminates parsing and invokes the ingress control flow function.5.1 Parsed RepresentationThe parser produces the representation of the packet on which match+action stagesoperate.

This is called the Parsed Representation of the packet. It is the set of headerinstances which are valid for the packet. The parser produces the initial Parsed Representation as described below. Match+action may update the Parsed Representation ofthe packet by modifying field values and by changing which header instances are valid;the latter results in adding and removing headers.The Parsed Representation holds packet headers as they are updated by match+action.The original packet data may be maintained for special operations such as cloning, described in Section 15.Metadata is considered part of the Parsed Representation for the packet as it is generallytreated like other packet headers.5.2 Parser OperationThe parser is fed the packet from the first byte.

It maintains a current offset into thepacket which is a pointer to a specific byte in the header. It extracts headers from thepacket at the current offset into per-packet header instances and marks those instancesvalid, updating the Parsed Representation of the packet.

The parser then moves the current offset forward (indicating the next valid byte of the packet to process) and makes astate transition.375.3 Value Sets5 PARSER SPECIFICATIONThe P4 program may examine metadata in making state transition decisions, thoughtargets may have limitations on this ability. For example, the ingress port may be usedto determine an initial parser state allowing of different packet formats.

Similarly, themetadata provided by cloning or recirculation can be used to change the parsing behavior for such packets; see Section 15.In P4, each state is represented as a parser function. A parser function may exit in oneof four ways:• A return statement specifying the name of a parser function is executed. Thisparser function is the next state to which the machine must transition.• A return statement specifying the name of a control function (as described in Section 13) is executed. This terminates parsing and begins match-action processingby calling the indicated control function.• An explicit parse_error statement executes. See Section 5.6 for more information.• An implicit parser error occurs.

These are described in Section 5.6.1.Note that because of the first two points, parser function names and control functionnames share a common namespace. The compiler must raise an error if two such functions have the same name.A select operation is defined to allow branching to different states depending on expressions involving fields or packet data.If headers are to be extracted when entering a state, these are signaled explicitly by callsto an extract function (defined in 5.5) at the beginning of the parser function definition(defined in 5.4).5.3 Value SetsIn some cases, the values that determine the transition from one parser state to anotherneed to be determined at run time.

MPLS is one example where the value of the MPLSlabel field is used to determine what headers follow the MPLS tag and this mapping maychange dynamically at run time. To support this functionality, P4 supports the notionof a Parser Value Set. This is a named set of values with a run time API to add andremove values from the set.

The set name may be referenced in parse state transitionconditions (the value list in a case entry).Parser Value Sets contain values only, no header types or state transition information.All values in a value set must correspond to the same transition. For example, all MPLSlabels corresponding to an IPv4 transition would exist in one set, while all MPLS labelscorresponding to an IPv6 transition would exist in a different set.385.4 Parser Function BNF5 PARSER SPECIFICATIONValue sets are declared at the top level of a P4 program, outside of parser functions.There is a single global namespace for value sets. They should be declared before beingreferenced in parser functions.value_set_declaration ::= parser_value_set value_set_name;The width of the values is inferred from the place where the value set is referenced.

If theset is used in multiple places and they would infer different widths, then the compilermust raise an error.The run time API for updating parser value sets must allow value and mask pairs to bespecified together.5.4 Parser Function BNFHere is the BNF for declaring a parser function:parser_function_declaration ::=parser parser_state_name { parser_function_body }parser_function_body ::=parser_body_call*return_statementparser_body_call ::=extract_statement |set_statement |extern_method_call ;extract_statement ::= extract ( header_extract_ref );header_extract_ref ::=header_instance_name |header_instance_name "[" header_extract_index "]"header_extract_index ::= const_expr | nextset_statement ::= set_metadata ( field_ref, general_expr ) ;return_statement ::=return_value_type |return select ( select_exp ) { case_entry + }return_value_type ::=395.4 Parser Function BNF5 PARSER SPECIFICATIONreturn parser_state_name ; |return control_function_name ; |parse_error parser_exception_name ;case_entry ::= value_list : case_return_value_type ;value_list ::= value_or_masked [ , value_or_masked ]* | defaultcase_return_value_type ::=parser_state_name |control_function_name |parse_error parser_exception_namevalue_or_masked ::=field_value | field_value mask field_value | value_set_name |( value_or_masked [, value_or_masked] * )select_exp ::= field_or_data_ref [, field_or_data_ref] *field_or_data_ref ::=field_ref |latest.field_name |current( const_expr , const_expr )The extract function can only extract to packet headers, not to metadata.Select functions take a comma-separated list of fields and concatenate their values,with the left-most field forming the most-significant bits of the concatenated value.

Theselect operation then compares the values in the order they occur in the program to theentries to find a matching one.The mask operator is used to indicate a ternary match should be performed using theindicated mask value. The comparison between the select expression and the case’svalue is limited to the bits set in the mask; that is, the select expression and value areeach ANDed with the mask before the comparison is made.Allowing masked matches and value sets means that more than one of the cases couldmatch.

The order of cases determines which takes precedence: the first case in the listthat matches is used.The header reference latest refers to the most recently extracted header instance withinthe parse function. It is an error to reference latest without a preceding extract operation in the same function.The field reference current(...) allows the parser to reference bits that have not yetbeen parsed into fields.

Its first argument is the bit offset from the current offset and its405.5 The extract Function5 PARSER SPECIFICATIONsecond argument is the bit width. The result is treated as an unsigned field-value of thegiven bit width. It is converted to the metadata field according to the conversion rulesdescribed in Section 2.6.2.In a set_metadata statement, the first argument (field_ref) is the destination of theoperation, and the second the source. The destination argument must be a metadatainstance. If the evaluated value of the second argument has a different width than thedestination metadata field, then conversion occurs as described in Section 2.6.2.

Targets may introduce limitations to the level of complexity they support for the general_expr argument.5.5 The extract FunctionThe extract function takes a header instance as a parameter. The header instance cannot be metadata. Extract copies data from the packet at the current offset into thatheader instance and moves the current parsing location to the end of that header.Note that we use the special identifier next (rather than last) for header stacks as weare extracting into the next available free location.5.6 Parser ExceptionsThere are two possible treatments for errors that occur during parsing: drop or process.In the drop case, the packet may be immediately dropped by the parser.

No match+action processing is done on the packet. An implementation should provide one ormore counters for such events.For the alternative, process, the parsing operation is halted, special metadata is set toindicate that a parser error occurred and the packet is passed to a control function formatch+action processing. The packet is processed according to the installed match+action rules like any other packet, but those rules may check for a parser error andapply policies such as forwarding the packet to the control plane.There are a number of error conditions recognized by P4 which may be triggered implicitly. These are listed in the table below.

In addition, the programmer may signalerrors with the parse_error exception in a parser function. They are both handled inthe same manner.Parser exception handlers may be explicitly declared by the programmer as follows.Multiple metadata set calls may be invoked followed by a directive either to return toa control function or to drop the packet. Note that setting metadata will only have aneffect if return is executed.parser_exception_declaration ::=parser_exception parser_exception_name {415.6 Parser Exceptions5 PARSER SPECIFICATIONset_statement *return_or_drop ;}return_or_drop ::= return_to_control | parser_dropreturn_to_control ::= return control_function_name5.6.1 Standard Parser ExceptionsA set of standard exception names are defined as follows. The prefix "pe" stands forparser exception.Identifierp4_pe_index_out_of_boundsp4_pe_out_of_packetp4_pe_header_too_longp4_pe_header_too_shortp4_pe_unhandled_selectp4_pe_checksump4_pe_defaultException EventA header stack array index exceeded the declaredbound.There were not enough bytes in the packet to complete an extraction operation.A calculated header length exceeded the declaredmaximum value.A calculated header length was less than the minimum length of the fixed length portion of theheader.A select statement had no default specified but theexpression value was not in the case list.A checksum error was detected.This is not an exception itself, but allows the programmer to define a handler to specify the defaultbehavior if no handler for the condition exists.Table 11: Standard Parser ExceptionsWhen an exception passes the packet for match+action processing, the exception typeis indicated as metadata; see Section 7.5.6.2 Default Exception HandlingIf a handler for p4_pe_default is defined and an exception occurs for which noparser_exception handler was defined by the programmer, the p4_pe_default handleris invoked.427 STANDARD INTRINSIC METADATAIf an exception occurs, no parser_exception handler was defined for that exception,and no p4_pe_default handler is defined, then the packet is dropped by the parser.6DeparsingAt some points, the forwarding element may need to convert the Parsed Representation (as updated by match+action) back to a serial stream of bytes (for example, ategress transmission).

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

Тип файла
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
Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6510
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее