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

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

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

Declarations consist of a type, as specified in the grammar below, followed by a unique identifier and an object body. The exact format of the body depends on the object type, andis described in more detail for each type throughout this document.The order that objects are declared in does not matter, and objects can reference otherobjects that were declared before them in the code.In general each P4 level declaration has its own namespace, though potential ambiguities are identified in the spec.P4 types generally consist of the kind of abstraction, followed by the specific type name.type_spec ::=header [ header_type_name ] |metadata [ header_type_name ] |field_list |field_list_calculation |parser |parser_exception |parser_value_set |counter |meter |register |action |action_profile |table |control |extern [ extern_type_name ] |data_typedata_type ::=bit |bit < decimal_digit+ > |varbit < decimal_digit+ > |int < decimal_digit+ >P4 actions consist of signatures which look like the typed parameter lists of traditional112.4 P4 data types2 STRUCTURE OF THE P4 LANGUAGEprogramming languages.

The types of the parameters in these signatures must be oneof the above.Section 2.4 explains the details of data_type. The bit type represents a bitstring of thelength specified within angle brackets (a compile time constant). If the angle bracketsare omitted, the length is implied to be 1. Most of the data processed by P4 is stored in abitstring of some sort, as described in Section 2.4. The varbit type represents a bitstringwith a length that is variable at run time, but at most the length specified within anglebrackets (again, a compile time constant). This data type is used for quickly parsingthrough variable-length headers and does not currently have utility beyond that. Morefunctionality may be added for this type in subsequent versions of P4 (such as the abilityto read it from a match+action pipeline).

The int type represetns a fixed-width signedintegerTypes which are followed by an optional identifier like header can be used in two ways:• "header foo" refers to a header instance specifically of header_type foo• "header" without an identifier refers to any header instance, of any type.2.4 P4 data typesP4 is a strongly-typed language; all values are statically typed. Programs that do notpass type-checking are invalid.P4 supports several base types and allows the construction of derived types. This section discusses only the following base types: Booleans and types for representing integers (bitstrings).2.4.1 PrinciplesThe typing rules for the integer types are chosen according to the following principles:Inspired from C: Typing of integers is modeled after the well-defined parts of C, expanded to cope with arbitrary fixed-width integers.

In particular, the type of theresult of an expression only depends on the expression operands, and not on howthe result of the expression is consumed.No undefined behaviors: P4 attempts to remedy the undefined C behaviors. Unfortunately C has many undefined behaviors, including specifying the size of an integer (int), results produced on overflow, and results for some arguments values(e.g., shifts with negative amounts, division of negative numbers, overflows onsigned numbers, etc.). In contrast, P4 computations on integer types have no undefined behaviors.122.4 P4 data types2 STRUCTURE OF THE P4 LANGUAGELeast surprise: The P4 typing rules are chosen to behave as closely as possible to traditional well-behaved C programs.Forbid rather than surprise: Rather than provide surprising or undefined results (e.g.,in C comparisons between signed and unsigned integers), we have chosen to forbid expressions with ambiguous interpretations.

For example, P4 does not allowbinary operations that combine signed and unsigned integers.The priority of arithmetic operations is also chosen similar to C (e.g., multiplicationbinds stronger than addition).2.4.2 Base typesThe P4 base types are shown in Table 2.Typeboolbit<W >int<W >varbit<W >intDescriptionBoolean valuesFixed-width unsigned integers of anarbitrary width WFixed-width signed integers of an arbitrary width W , represented usingtwo’s complementBit-strings of dynamically-computedwidth (also called varbits) with amaximum width WInfinite-precision integer constantvaluesExamplebit<20>Section2.4.52.4.6int<33>2.4.7varbit<1024>2.4.8int2.4.9boolTable 2: Base P4 TypesValues can be converted to a different type by using casts. The range of casts availableis intentionally restricted.

There are very few implicit casts. Most binary operationsrequire both operands to be of the same type. No operations produce runtime exceptions.2.4.3 PortabilityNo P4 target can support all possible types and operations. For example, the followingtype is legal in P4: bit<23132312>. Hence, each target can impose restrictions on thevalues it can support. Such restrictions may include:• The maximum width supported132.4 P4 data types2 STRUCTURE OF THE P4 LANGUAGE• Alignment and padding constraints (e.g., arithmetic may only be supported onwidths which are an integral number of bytes).• Constraints on some operands (e.g., some architectures may only support multiplications with small constants, or shifts with small values).Target-specific documentation should describe such restrictions, and target-specificcompilers should provide clear error messages when such restrictions are encountered.An architecture may reject a well-typed P4 program and still be conformant to the P4spec.

However, if an architecture accepts a P4 program as valid, the runtime programbehavior should match this specification.2.4.4 No saturated typesP4 does not support saturated integer types for the following reasons:• Saturated types are unlikely to be portable.• The semantics of many operations on saturated types may be open for debate.• Most operations may be unnecessary on saturated types (addition, subtractionand multiplication seem to be the most frequent ones).• Finally, saturated arithmetic can be implemented by using P4 v1.1 extern custom constructs that operate on bitstrings rather than by built-in arithmetic operators. For example, an architecture could provide an extern saturated_aluwhose methods operate on unsigned bitstrings but perform saturated operations.2.4.5 BooleanThe Boolean type contains two values, false and true.

The type is written as bool.Operations on Boolean values are described in Section 2.5.1. Booleans are not integers.2.4.6 Unsigned integers (bit-strings)An unsigned integer (which we also call a “bit-string”) has an arbitrary width, expressedin bits. A bit-string of width W is declared as: bit<W >. W must be a compile-time constantvalue evaluating to a positive integer greater than 0.142.4 P4 data types2 STRUCTURE OF THE P4 LANGUAGEBits within a bit-string are numbered from 0 to W -1. Bit 0 is the least significant, and bitW -1 is the most significant1 .For example, the type bit<128> denotes the type of bit-string values with 128 bits numbered from 0 to 127, where bit 127 is the most significant.The type bit is a shorthand for bit<1>.P4 target architectures may impose additional compile-time or runtime constraints onbit types: for example, they may limit the maximum size, or they may only supportsome arithmetic operations on certain sizes (e.g., 16-, 32- and 64- bit values).All operations that can be performed on unsigned integers are described in Section 2.5.2.2.4.7 Signed IntegersSigned integers are represented using 2’s complement.

An integer with W bits is declaredas: int<W >. W must be a compile-time constant value evaluating to a positive integergreater than 0.Bits within an integer are numbered from 0 to W -1. Bit 0 is the least significant, and bitW -1 is the sign bit.For example, the type int<64> describes the type of integers represented using exactly64 bits.There are no constraints of the value of W , but specific targets may impose limits.All operations that can be performed on signed integers are described in Section 2.5.3.2.4.8 Dynamically-sized bit-stringsSome network protocols use fields whose size is only known at runtime (e.g., IPv4 options).

To support restricted manipulations of such values, P4 provides a special bitstring type whose size is set at runtime, called a varbit.varbit<W > denotes a bit-string with a width of at most W bits, where W is a compile-time constant value evaluating to a positive integer. For example, the type varbit<120>denotes the type of bit-string values that may have between 0 and 120 bits. Most operations that are applicable to fixed-size bit-strings (unsigned numbers) cannot be performed on dynamically sized bit-strings.1No P4 operation currently depends on the bit numbering within an integer, but future languageadditions may.152.4 P4 data types2 STRUCTURE OF THE P4 LANGUAGEP4 target architectures may impose additional compile-time or runtime constraintson varbit types: for example, they may limit the maximum size, or they may requirevarbit values to always contain an integer number of bytes at runtime.All operations that can be performed on dynamically-sized bitstrings are described inSection 2.5.5.2.4.9 Infinite-precision integersThe infinite-precision datatype describes integers with an unlimited precision.

Thistype is written as int. This type is reserved for compile-time integer literals only. NoP4 run-time value can have an int type; at compile time the compiler will convert allint values that have a runtime component to fixed-width types, according to the rulesdescribed below.All operations that can be performed on infinite-precision integers are described in Section 2.5.6.2.4.10 Integer literal typesAs described in Section 2.2, there are three types of integer literals (constants):• A simple integer constant has type int.• A simple positive integer can be prefixed with a width and the character ’w’ (nospaces) to indicate an unsigned integer with the specified width in bits.• A simple integer (positive or negative) can be prefixed with a width and the character ’s’ (no spaces) to indicate a signed integer with the specified width in bits.Table 3 shows several examples of integer literals and their types.Literal10-108w10-8w108s10-8s102s31w101s10InterpretationType is int, value is 10.Type is int, value is -10.Type is bit<8>, value is 10.Illegal: negative unsigned number.Type is int<8>, value is 10.Type is int<8>, value is -10.Type is int<2>, value is -1 (last 2 bits), overflow warning.Type is bit<1>, value is 0 (last bit), overflow warning.Type is int<1>, value is 0 (last bit), overflow warning.Table 3: Integer literals and their types.162.5 Base type operations2 STRUCTURE OF THE P4 LANGUAGE2.5 Base type operationsThis section describes all legal operations that can be performed on base types.

Foreach operation we describe the input operand types and the result type.2.5.1 Computations on Boolean valuesNote: In C binary Boolean operations are performed using short-circuit evaluation,where the second operand is only evaluated if necessary. This is important only if theevaluation of an operand can produce side-effects. Currently there are no operations inP4 that produce side-effects. In consequence, there is no semantic difference betweenshort-circuit and full evaluation. If the P4 language is extended in the future to encompass operations with side-effects, the semantics of Boolean operations may have to berevisited.Table 4 describes all operations available on Boolean values.Operationand2or3not4==, !=DescriptionBinary associative operation; both operands must be Boolean; resultis Boolean.Binary associative operation; both operands must be Boolean; resultis Boolean.Unary operation; operand is Boolean, result is Boolean.Test for equality/inequality; result is Boolean.Table 4: Boolean operationsIn addition, all comparison operations (==, !=, >, <, <=, >=), described below, produce asresults Boolean values.There are no implicit casts from bit-strings to Booleans or vice-versa.

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

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