«…Труд избавляет человека от трех великих зол: скуки, порока, нужды…»

Спец курс (Автоматизация процесса проектирования)/Практические задания 4

Материал из Wiki
< Спец курс (Автоматизация процесса проектирования)
Версия от 19:18, 30 марта 2018; ANA (обсуждение | вклад)

Это снимок страницы. Он включает старые, но не удалённые версии шаблонов и изображений.
Перейти к: навигация, поиск
Лекции SCRIPT

Лекции

Практические задания
Тесты

Табель успеваемости

Экзамен

Доп. материалы

Содержание

Перед выполнение ознакомиться с правилами оформления задания

Описание входного файла

run.log

Входной файл для задач представляет собой лог пакетов данных, передаваемых по PCIe протоколу между Host`ом и Device`ом. Поверх PCIe протокола передаются пакеты с командами и данными другого протокола - NVMe. Задания направлены на то, чтобы провести дополнительную обработку данных в логе, чтобы улучшить читаемость данных и ускорить анализ NVMe протокола.

Рассмотрим основные позиции в лог файле на следующем примере: PCIe log example.png

  • В столбце 1 буквы T и R озаначают направление передачи данных, от хоста к девайсу (T) и от девайса к хосту (R) соответственно.
  • В столбце 2 задаётся тип пакета: запрос на запись (MWr32, MWr64), запрос на чтение (MRd32, MRd64), ответ на запрос чтения (CplD).
  • В столбце 3 задаётся номер запроса/ответа. Для запроса и ответа на него данный номер должен совпадать, как в примере.
  • В поле 4 для запроса на запись или чтение будет указан адрес.
  • В поле 5 для ответов на запрос чтения указывается количество байт. Для NVMe команд данное поле равно 64 байт.
  • В поле 6 указывается количество двойных слов (4 байта) которые нужно прочитать или записать, в зависимости от запроса.
  • В поле 7 указываются передаваемые данные.

run.info

Дополнительный файл, который требуется в некоторых заданиях, содержит информацию о некоторых конфигурационных параметрах.

Общие требования к интерфейсу программ

  • первый параметр обязательный - имя входного файла (может содержать путь к файлу). Если этот параметр не задан, то вывести сообщение о том, как использовать программу (usage)
  • второй параметр необязательный - имя выходного файла. Если параметр не задан, то сформировать имя выходного файла из имени входного по шаблону: <имя_вх_файла>_out.<расширение_вх_файла>.

Если входной файл не может быть открыт, либо выходной файл не может быть создан (если задан неправильный путь в командной строке), то вывести соответствующее сообщение об ошибке.

Задание 1. Разворот байт

Во входном файле (лог файл) строки с пометкой "(D)" включают данные - от одного до четырёх двойных слов (двойное слово (DWord) - 32 двоичных разряда, далее DW), заданных в шестнадцатеричной форме. Например:

0 (D) 80000d00 02000000 00000000 00000000 Some comments

Задача развернуть байты в каждом DW`е, как показано ниже

0 (D) 000d0080 00000002 00000000 00000000 Some comments

После данных в строке могут быть какие-либо текстовые комментарии, их необходимо перенести без изменений.

В файле есть строки с данными со слово "LittleEndian", в которых уже проведено данное преобразование, поэтому их не следует изменять. Например:

0 (D) 8020c011 LittleEndian

Остальные строки из входного файла перенести в выходной без изменений.

Задание 2. Распознавание Admin команд

Обработать входной лог файл, найти в логе пакеты с данными, которые задают NVMe команду и дополнить соответствующие строки с данными расшифровкой, записав в строке после данных имена и значения полей команды.

Пакет данных относящийся к команде имеет размер 64 байта, в заголовке пакета должно быть BC:0064. После строки заголовка следует 4 строки с данными, где в первом столбце - номер DWord`а данных пакета, второй столбец - маркер данных "(D)".

test_top     203865.00 203869.00 R MRd32      0x0100/01   355  0 0    0 0 0          0x40008080   f f     16 (H) 00008010 010001ff 40008080   ----     0x3191b2b4  0xf87188a                                            
test_top     203897.00 203917.00 T CplD       0x0100/01   182  0 0    0 0 0  ID:0xffff Stat:SC  BC:0064   16 (H) 4a008010 ffff0040 01000100   ----   0 0xa94d0d83 0x37e1b7df                                            
                                                                                                          0 (D) 01000400 02000000 00000000 00000000                                                                    
                                                                                                          4 (D) 00000000 00000000 00900140 00000000                                                                    
                                                                                                          8 (D) 00c00140 00000000 0a000000 00000000                                                                    
                                                                                                         12 (D) 01000000 00000000 00000000 00000000                                                                    

Данные в логе записываются слева направо - с младшего адреса. В приведённом примере байт 0 нулевого DWord`а равень 01, второй байт - 00, третий 04, четвертый байт - 00 и т.д. Далее идут четыре DWorda данных от младшего к старшему.

Расшифровка команды в спецификации NVMe 1.2.

  • Figure 10: Command Dword 0
Bit Description
31:16 Command Identifier (CID): This field specifies a unique identifier for the command when combined with the Submission Queue identifier.
15:14 PRP or SGL for Data Transfer (PSDT): This field specifies whether PRPs or SGLs are used for any data transfer associated with the command. PRPs shall be used for all Admin commands for NVMe over PCIe. SGLs shall be used for all Admin and I/O commands for NVMe over Fabrics. This field shall be set to 01b for NVMe over Fabrics 1.0 implementations. The definition is described in the table below.
Value Definition
00b PRPs are used for this transfer.
01b SGLs are used for this transfer. If used, Metadata Pointer (MPTR) contains an address of a single contiguous physical buffer that is byte aligned.
10b SGLs are used for this transfer. If used, Metadata Pointer (MPTR) contains an address of an SGL segment containing exactly one SGL Descriptor that is Qword aligned.
11b Reserved

If there is metadata that is not interleaved with the logical block data, as specified in the Format NVM command, then the Metadata Pointer (MPTR) field is used to point to the metadata. The definition of the Metadata Pointer field is dependent on the setting in this field. Refer to Figure 11.

13:10 Reserved
09:08 Fused Operation (FUSE): In a fused operation, a complex command is created by “fusing” together two simpler commands. Refer to section 4.10. This field specifies whether this command is part of a fused operation and if so, which command it is in the sequence.
Value Definition
00b Normal operation
01b Fused operation, first command
10b Fused operation, second command
11b Reserved
07:00 Opcode (OPC): This field specifies the opcode of the command to be executed.
  • Figure 11: Command Dword 0-15: Command Format – Admin Command Set
Bytes Description
03:00 Command Dword 0 (CDW0): This field is common to all commands and is defined in Figure 10.
07:04 Namespace Identifier (NSID): This field specifies the namespace that this command applies to. If the namespace is not used for the command, then this field shall be cleared to 0h. Setting this value to FFFFFFFFh causes the command to be applied to all namespaces attached to this controller, unless otherwise specified.

Specifying an inactive namespace ID in a command that uses the namespace ID shall cause the controller to abort the command with status Invalid Field in Command, unless otherwise specified. Specifying an invalid namespace ID in a command that uses the namespace ID shall cause the controller to abort the command with status Invalid Namespace or Format, unless otherwise specified.

15:08 Reserved
23:16 Metadata Pointer (MPTR): This field is valid only if the command has metadata that is not interleaved with the logical block data, as specified in the Format NVM command. This is a reserved field in NVMe over Fabrics.

If CDW0.PSDT is set to 00b, then this field shall contain the address of a contiguous physical buffer of metadata and shall be Dword aligned.

If CDW0.PSDT is set to 01b, then this field shall contain the address of a contiguous physical buffer of metadata and shall be byte aligned.

If CDW0.PSDT is set to 10b, then this field shall contain the address of an SGL segment containing exactly one SGL Descriptor and shall be Qword aligned. If the SGL segment is a Data Block descriptor, then it describes the entire data transfer. Refer to section 4.4.

39:24 Data Pointer (DPTR): This field specifies the data used in the command.
If CDW0.PSDT is set to 00b, then the definition of this field is:
39:32 PRP Entry 2 (PRP2): This field:

a) is reserved if the data transfer does not cross a memory page boundary.

b) specifies the Page Base Address of the second memory page if the data transfer crosses exactly one memory page boundary. E.g.,:

  • i. the command data transfer length is equal in size to one memory page and the offset portion of the PBAO field of PRP1 is non-zero or
  • ii. the Offset portion of the PBAO field of PRP1 is equal to zero and the command data transfer length is greater than one memory page and less than or equal to two memory pages in size.

c) is a PRP List pointer if the data transfer crosses more than one memory page boundary. E.g.,:

  • i. the command data transfer length is greater than or equal to two memory pages in size but the offset portion of the PBAO field of PRP1 is non-zero or'
  • ii. the command data transfer length is equal in size to more than two memory pages and the Offset portion of the PBAO field of PRP1 is equal to zero.'
31:24 PRP Entry 1 (PRP1): This field contains the first PRP entry for the command or a PRP List pointer depending on the command.

If CDW0.PSDT is set to 01b or 10b, then the definition of this field is:

39:24 SGL Entry 1 (SGL1): This field contains the first SGL segment for the command. If the SGL segment is an SGL Data Block or Keyed SGL Data Block descriptor, then it describes the entire data transfer. If more than one SGL segment is needed to describe the data transfer, then the first SGL segment is a Segment, or Last Segment descriptor. Refer to section 4.4 for the definition of SGL segments and descriptor types.

The NVMe Transport may support a subset of SGL Descriptor types and features as defined in the NVMe Transport binding specification.

43:40 Command Dword 10 (CDW10): This field is command specific Dword 10.
47:44 Command Dword 11 (CDW11): This field is command specific Dword 11.
51:48 Command Dword 12 (CDW12): This field is command specific Dword 12.
55:52 Command Dword 13 (CDW13): This field is command specific Dword 13.
59:56 Command Dword 14 (CDW14): This field is command specific Dword 14.
63:60 Command Dword 15 (CDW15): This field is command specific Dword 15.
  • Figure 40: Opcodes for Admin Commands
Opcode by Field Combined Opcode2 O/M1 Namespace Identifier Used3 Command
(07) (06:02) (01:00)
Generic Command Function Data Transfer4
0b 000 00b 00b 00h M No Delete I/O Submission Queue
0b 000 00b 01b 01h M No Create I/O Submission Queue
0b 000 00b 10b 02h M Yes Get Log Page
0b 000 01b 00b 04h M No Delete I/O Completion Queue
0b 000 01b 01b 05h M No Create I/O Completion Queue
0b 000 01b 10b 06h M Yes Identify
0b 000 10b 00b 08h M No Abort
0b 000 10b 01b 09h M Yes Set Features
0b 000 10b 10b 0Ah M Yes Get Features
0b 000 11b 00b 0Ch M No Asynchronous Event Request
0b 000 11b 01b 0Dh O Yes Namespace Management
0b 001 00b 00b 10h O No Firmware Commit
0b 001 00b 01b 11h O No Firmware Image Download
0b 001 01b 00b 14h O Yes Device Self-test
0b 001 01b 01b 15h O Yes Namespace Attachment
0b 001 10b 00b 18h NOTE 5 No Keep Alive
0b 001 10b 01b 19h O Yes Directive Send
0b 001 10b 10b 1Ah O Yes Directive Receive
0b 001 11b 00b 1Ch O No Virtualization Management
0b 001 11b 01b 1Dh O No NVMe-MI Send
0b 001 11b 10b 1Eh O No NVMe-MI Receive
0b 111 11b 00b 7Ch O No Doorbell Buffer Config
0b 111 11b 11b 7Fh O Refer to the NVMe over Fabrics specification.
I/O Command Set Specific
1b na NOTE 4 80h – BFh O I/O Command Set specific
Vendor Specific
1b na NOTE 4 C0h – FFh O Vendor specific
NOTES:
  1. O/M definition: O = Optional, M = Mandatory.
  2. Opcodes not listed are reserved.
  3. A subset of commands uses the Namespace Identifier field (CDW1.NSID). When not used, the field shall be cleared to 0h.
  4. Indicates the data transfer direction of the command. All options to the command shall transfer data as specified or transfer no data. All commands, including vendor specific commands, shall follow this convention: 00b = no data transfer; 01b = host to controller; 10b = controller to host; 11b = bidirectional.
  5. For NVMe over PCIe implementations, the Keep Alive command is optional. For NVMe over Fabrics implementations, the associated NVMe Transport binding defines whether the Keep Alive command is optional or mandatory.
  • Figure 41: Opcodes for Admin Commands – NVM Command Set Specific
Opcode (07) Opcode (06:02) Opcode (01:00) Opcode2 O/M1 Namespace Identifier Used3 Command
Generic Command Function Data Transfer4
1b 000 00b 00b 80h O Yes Format NVM
1b 000 00b 01b 81h O NOTE 5 Security Send
1b 000 00b 10b 82h O NOTE 5 Security Receive
1b 000 01b 00b 84h O No Sanitize
NOTES:
  1. O/M definition: O = Optional, M = Mandatory.
  2. Opcodes not listed are reserved.
  3. A subset of commands uses the Namespace Identifier field (CDW1.NSID). When not used, the field shall be cleared to 0h.
  4. Indicates the data transfer direction of the command. All options to the command shall transfer data as specified or transfer no data. All commands, including vendor specific commands, shall follow this convention: 00b = no data transfer; 01b = host to controller; 10b = controller to host; 11b = bidirectional.
  5. The use of the Namespace Identifier is Security Protocol specific.

Например, строка с первыми четырьмя DWord`ами:

0 (D) 01000400 02000000 00000000 00000000

должна быть преобразована согласно таблицы 10 и 11 в следующую строку:

0 (D) 01000400 02000000 00000000 00000000 CMD=01, FUSE=00, PSDT=PRP, CID=0004, NSID=2

Для того чтобы определить админ команду нужно, проверить адрес по которому читается пакет данных. Диапазон адресов для админ команд необходимо прочитать из файла run.info:

    118245000.00 ps       8   H00/C01                 Reg   Write (AQA)                        0x0000_0024, 0x00ed_0001/4B        ACQS=237, ASQS=1                                                  
    118245000.00 ps       8   H00/C01                 Reg   Write (ACQ)                        0x0000_0030,   (see ACQ)/8B        ACQ=0x0000_0000_4000_0000                                         
    118274000.00 ps       9   H00/C01                 Reg   Write (AQA)                        0x0000_0024, 0x00ed_00b8/4B        ACQS=237, ASQS=184                                                
    118274000.00 ps       9   H00/C01                 Reg   Write (ASQ)                        0x0000_0028,   (see ASQ)/8B        ASQ=0x0000_0000_4000_1000 
  • Поле ACQ=0x0000_0000_4000_0000 - содержит адрес начала диапазона (hex)
  • Поле ACQS=237 - содержит количество команд в диапазоне (по 64 байта) (dec). Размер диапазона 237 * 64 = 15168 (0х3B40)

Данные поля могут содержаться в нескольких строчках, следует использовать последнее встречающееся значение.

Для данного примера админ команды должны лежать в диапазоне от 0х4000_0000 до 0х4000_3B3F (включительно). Таким образом, в приведённом выше примере адрес 0x40008080 запроса на чтение команды не попадает в этот диапазон, что означает, что это не админ команда, а IO команда.


Задание 4. Распознавание Admin команды Identify

Задание 3. Распознавание IO команд

  • Figure : Opcodes for NVM Commands
Opcode by Field Combined Opcode2 O/M1 Command3
(07) (06:02) (01:00)
Standard Command Function Data Transfer5
0b 000 00b 00b 00h M Flush
0b 000 00b 01b 01h M Write
0b 000 00b 10b 02h M Read
0b 000 01b 00b 04h O Write Uncorrectable
0b 000 01b 01b 05h O Compare
0b 000 10b 00b 08h O Write Zeroes
0b 000 10b 01b 09h O Dataset Management
0b 000 11b 01b 0Dh O4 Reservation Register
0b 000 11b 10b 0Eh O4 Reservation Report
0b 001 00b 01b 11h O4 Reservation Acquire
0b 001 01b 01b 15h O4 Reservation Release
Vendor Specific
1b na NOTE 5 80h – FFh O Vendor specific
NOTES:
  1. O/M definition: O = Optional, M = Mandatory.
  2. Opcodes not listed are reserved.
  3. All NVM commands use the Namespace Identifier field (CDW1.NSID).
  4. Mandatory if reservations are supported as indicated in the Identify Controller data structure.
  5. Indicates the data transfer direction of the command. All options to the command shall transfer data as specified or transfer no data. All commands, including vendor specific commands, shall follow this convention: 00b = no data transfer; 01b = host to controller; 10b = controller to host; 11b = bidirectional.

Задание 5. Распознавание полей IO Read команды

Задание 6. Распознавание полей IO Write команды