«…лишь недалекие люди боятся конкуренции, а люди подлинного творчества ценят общение с каждым талантом…» А. Бек, Талант.

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

Материал из Wiki
Перейти к: навигация, поиск
м (Задание 6. Распознавание полей IO Write команды)
(Распознавание Admin и IO команд)
 
Строка 491: Строка 491:
 
  0 (D) 01000400 02000000 00000000 00000000 '''CMD=01, FUSE=00, PSDT=PRP, CID=0004, NSID=2'''
 
  0 (D) 01000400 02000000 00000000 00000000 '''CMD=01, FUSE=00, PSDT=PRP, CID=0004, NSID=2'''
  
==== Распознавание Admin и IO команд ====
+
==== Задание 3. Распознавание Admin и IO команд ====
  
 
Для того чтобы определить админ команду нужно, проверить адрес по которому читается пакет данных. Диапазон адресов для админ команд необходимо прочитать из файла run.info:
 
Для того чтобы определить админ команду нужно, проверить адрес по которому читается пакет данных. Диапазон адресов для админ команд необходимо прочитать из файла run.info:

Текущая версия на 14:16, 26 апреля 2021

Лекции 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 указываются передаваемые данные. Данные записаны младшим байтом вперёд. Подробнее об этом описано в задании 1.

run.info

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

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

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

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

Задание 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

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

Для того чтобы определить админ команду нужно, проверить адрес по которому читается пакет данных. Диапазон адресов для админ команд необходимо прочитать из файла 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 команда.


В данном задании нужна расшифровка следующих полей:

  • DW0: CID, PSDT, FUSE, OPC
  • DW1: NSID,
  • DW4-5: MPTR
  • DW6-7: PRP1
  • DW8-9: PRP2

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

Как определить Admin команды описано в задании 2

Identify

Админ команда Identify использует поля PRP Entry 1, PRP Entry 2, и DW 10. Все остальные поля не используются. В таблицах на Figure 86-89 в спецификации NVMe 1.2 дана расшифровка используемых полей.

  • Figure 87: Identify – PRP Entry 1
  • Figure 88: Identify – PRP Entry 2
  • Figure 89: Identify – Command Dword 10
  • Figure 86: Identify – Data Structure Returned

Для команды Identify нужна расшифровка следующих полей:

  • DW10: CNTID, CNS

Format

Команда Format NVM использует поля в Command Dword 10, которые описаны в таблице

  • Figure 138: Format NVM – Command Dword 10

Для команды Format нужна расшифровка следующих полей:

  • DW10: SES, PIL, PI, MS, LBAF

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

Как определить IO команды описано в задании 2

Расшифровка значений кода команды (DW0.OPC) дана в таблице:

  • Figure 149: 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.

В данном задании нужна расшифровка следующих полей:

  • DW0: CID, PSDT, FUSE, OPC
  • DW1: NSID,
  • DW4-5: MPTR
  • DW6-9:
    • PRP1, PRP2 - если DW0.PSDT = 00b
    • SGL1 - если CDW0.PSDT = 01b или 10b

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

Как определить IO команды описано в задании 2

Команда IO Read использует DW 10, DW 11, DW 12, DW 13, DW 14, и DW 15 fields. Если команда использует PRPs для передачи данных (DW0.PSDT=00b), тогда используются поля Metadata Pointer, PRP Entry 1, и PRP Entry 2. Если команда использует SGL (DW0.PSDT=01b или 10b) для передачи данных, то в этом случае задействованы поля Metadata SGL Segment Pointer и SGL Entry 1.

  • Figure 170: Read – Metadata Pointer
Bit Description
63:00 Metadata Pointer (MPTR): This field contains the Metadata Pointer, if applicable. Refer to Figure 11 for the definition of this field.
  • Figure 171: Read – Data Pointer
Bit Description
127:00 Data Pointer (DPTR): This field specifies where data is transferred to. Refer to Figure 11 for the definition of this field.
  • Figure 172: Read – Command Dword 10 and Command Dword 11
Bit Description
63:00 Starting LBA (SLBA): This field indicates the 64-bit address of the first logical block to be read as part of the operation. Command Dword 10 contains bits 31:00; Command Dword 11 contains bits 63: 32.
  • Figure 173: Read – Command Dword 12
Bit Description
31 Limited Retry (LR): If set to ‘1’, the controller should apply limited retry efforts. If cleared to ‘0’, the controller should apply all available error recovery means to return the data to the host.
30 Force Unit Access (FUA): This field indicates that the data read shall be returned from non-volatile media. There is no implied ordering with other commands.
29:26 Protection Information Field (PRINFO): Specifies the protection information action and check field, as defined in Figure 196.
25:16 Reserved
15:00 Number of Logical Blocks (NLB): This field indicates the number of logical blocks to be read. This is a 0’s based value.
  • Figure 174: Read – Command Dword 13
Bit Description
31:08 Reserved
07:00 Dataset Management (DSM): This field indicates attributes for the LBA(s) being read.
Bit Attribute Definition
07 Incompressible If set to ‘1’, then data is not compressible for the logical blocks indicated. If cleared to ‘0’, then no information on compression is provided.
06 Sequential Request If set to ‘1’, then this command is part of a sequential read that includes multiple Read commands. If cleared to ‘0’, then no information on sequential access is provided.
05:04 Access Latency
Value Definition
00b None. No latency information provided.
01b Idle. Longer latency acceptable.
10b Normal. Typical latency.
11b Low. Smallest possible latency.
03:00 Access Frequency
Value Definition
0000b No frequency information provided.
0001b Typical number of reads and writes expected for this LBA range.
0010b Infrequent writes and infrequent reads to the LBA range indicated.
0011b Infrequent writes and frequent reads to the LBA range indicated.
0100b Frequent writes and infrequent reads to the LBA range indicated.
0101b Frequent writes and frequent reads to the LBA range indicated.
0110b One time read. E.g. command is due to virus scan, backup, file copy, or archive.
0111b Speculative read. The command is part of a prefetch operation.
1000b The LBA range is going to be overwritten in the near future.
1001b – 1111b Reserved
  • Figure 175: Read – Command Dword 14
Bit Description
31:00 Expected Initial Logical Block Reference Tag (EILBRT): This field specifies the Initial Logical Block Reference Tag expected value. This field is only used if the namespace is formatted to use end-to-end protection information. Refer to section 8.3.
  • Figure 176: Read – Command Dword 15
Bit Description
31:16 Expected Logical Block Application Tag Mask (ELBATM): This field specifies the Application Tag Mask expected value. This field is only used if the namespace is formatted to use end-to-end protection information. Refer to section 8.3.
15:00 Expected Logical Block Application Tag (ELBAT): This field specifies the Application Tag expected value. This field is only used if the namespace is formatted to use end-to-end protection information. Refer to section 8.3.

Для команды Read нужна расшифровка следующих полей:

  • DW10-11: SLBA
  • DW12: LR, FUA, PRINFO.PRACT, PRINFO.PRCHK, NLB
  • DW13: DSM.Incompressible, DCM.SR, DCM.AL, DCM.AF
  • DW14: EILBRT
  • DW15: ELBATM, ELBAT

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

Как определить IO команды описано в задании 2

Команда IO Write использует поля, расположенные в DW 10, DW 11, DW 12, DW 13, DW 14, и DW 15. Если команда использует PRPs для передачи данных (DW0.PSDT=00b), тогда используются поля Metadata Pointer, PRP Entry 1, и PRP Entry 2. Если команда использует SGL (DW0.PSDT=01b или 10b) для передачи данных, то в этом случае задействованы поля Metadata SGL Segment Pointer и SGL Entry 1.

В следующих таблицах в спецификации на NVMe 1.2 дана расшифровка используемых полей

  • Figure 192: Write – Metadata Pointer
  • Figure 193: Write – Data Pointer
  • Figure 194: Write – Command Dword 10 and Command Dword 11
  • Figure 195: Write – Command Dword 12
  • Figure 196: Write – Command Dword 13
  • Figure 197: Write – Command Dword 14
  • Figure 198: Write – Command Dword 15

Для команды Write нужна расшифровка следующих полей:

  • DW10-11: SLBA
  • DW12: LR, FUA, PRINFO.PRACT, PRINFO.PRCHK, NLB
  • DW13: DSM.Incompressible, DCM.SR, DCM.AL, DCM.AF
  • DW14: ILBRT
  • DW15: LBATM, LBAT