From 7fe23e4a8fa6fce19fb3d5e3a8a1f5472496c928 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Sat, 7 Nov 2026 10:26:34 +0300 Subject: publish --- .gitignore | 2 + README.org | 359 ++++++++++++++++++++++++++++++++++ UNLICENSE | 24 +++ doc/gost/gost-7-32-bibliography.sty | 57 ++++++ doc/gost/gost-7-32-captions.sty | 23 +++ doc/gost/gost-7-32-counters.sty | 37 ++++ doc/gost/gost-7-32-headings.sty | 98 ++++++++++ doc/gost/gost-7-32-lists.sty | 15 ++ doc/gost/gost-7-32-tables.sty | 29 +++ doc/gost/gost-7-32-toc.sty | 34 ++++ doc/gost/gost-7-32.cls | 62 ++++++ doc/ox-init.el | 32 +++ doc/raid0.png | Bin 0 -> 19955 bytes doc/raid5.png | Bin 0 -> 25288 bytes doc/raid50.png | Bin 0 -> 11928 bytes doc/report.org | 269 +++++++++++++++++++++++++ doc/setup.org | 40 ++++ doc/spbstu-report.cls | 73 +++++++ doc/task.org | 137 +++++++++++++ makefile | 54 +++++ src/raid-4-poly-10b-7d.c | 337 ++++++++++++++++++++++++++++++++ src/raid-4-poly-8b-6d.c | 304 +++++++++++++++++++++++++++++ src/raid-4-poly-8b-7d.c | 333 +++++++++++++++++++++++++++++++ src/raid-4-xor-10b-3d.c | 249 +++++++++++++++++++++++ src/raid-4-xor-10b-6d.c | 279 ++++++++++++++++++++++++++ src/raid-4-xor-10b-7d.c | 285 +++++++++++++++++++++++++++ src/raid-4-xor-12b-4d.c | 289 +++++++++++++++++++++++++++ src/raid-4-xor-12b-5d.c | 284 +++++++++++++++++++++++++++ src/raid-4-xor-12b-7d.c | 264 +++++++++++++++++++++++++ src/raid-4-xor-14b-4d.c | 298 ++++++++++++++++++++++++++++ src/raid-4-xor-14b-5d.c | 293 +++++++++++++++++++++++++++ src/raid-4-xor-14b-8d.c | 283 +++++++++++++++++++++++++++ src/raid-4-xor-8b-8d.c | 286 +++++++++++++++++++++++++++ src/raid-5-poly-14b-4d.c | 294 ++++++++++++++++++++++++++++ src/raid-5-xor-12b-3d.c | 329 +++++++++++++++++++++++++++++++ src/raid-5-xor-12b-5d.c | 341 ++++++++++++++++++++++++++++++++ src/raid-5-xor-12b-6d.c | 380 ++++++++++++++++++++++++++++++++++++ src/raid-50-poly-12b-6d.c | 312 +++++++++++++++++++++++++++++ src/raid-50-poly-8b-6d.c | 305 +++++++++++++++++++++++++++++ src/raid-50-xor-12b-6d.c | 328 +++++++++++++++++++++++++++++++ src/raid-50-xor-8b-6d.c | 328 +++++++++++++++++++++++++++++++ 41 files changed, 7746 insertions(+) create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100644 doc/gost/gost-7-32-bibliography.sty create mode 100644 doc/gost/gost-7-32-captions.sty create mode 100644 doc/gost/gost-7-32-counters.sty create mode 100644 doc/gost/gost-7-32-headings.sty create mode 100644 doc/gost/gost-7-32-lists.sty create mode 100644 doc/gost/gost-7-32-tables.sty create mode 100644 doc/gost/gost-7-32-toc.sty create mode 100644 doc/gost/gost-7-32.cls create mode 100644 doc/ox-init.el create mode 100644 doc/raid0.png create mode 100644 doc/raid5.png create mode 100644 doc/raid50.png create mode 100644 doc/report.org create mode 100644 doc/setup.org create mode 100644 doc/spbstu-report.cls create mode 100644 doc/task.org create mode 100644 makefile create mode 100644 src/raid-4-poly-10b-7d.c create mode 100644 src/raid-4-poly-8b-6d.c create mode 100644 src/raid-4-poly-8b-7d.c create mode 100644 src/raid-4-xor-10b-3d.c create mode 100644 src/raid-4-xor-10b-6d.c create mode 100644 src/raid-4-xor-10b-7d.c create mode 100644 src/raid-4-xor-12b-4d.c create mode 100644 src/raid-4-xor-12b-5d.c create mode 100644 src/raid-4-xor-12b-7d.c create mode 100644 src/raid-4-xor-14b-4d.c create mode 100644 src/raid-4-xor-14b-5d.c create mode 100644 src/raid-4-xor-14b-8d.c create mode 100644 src/raid-4-xor-8b-8d.c create mode 100644 src/raid-5-poly-14b-4d.c create mode 100644 src/raid-5-xor-12b-3d.c create mode 100644 src/raid-5-xor-12b-5d.c create mode 100644 src/raid-5-xor-12b-6d.c create mode 100644 src/raid-50-poly-12b-6d.c create mode 100644 src/raid-50-poly-8b-6d.c create mode 100644 src/raid-50-xor-12b-6d.c create mode 100644 src/raid-50-xor-8b-6d.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23f832b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.html +*.pdf diff --git a/README.org b/README.org new file mode 100644 index 0000000..79efc39 --- /dev/null +++ b/README.org @@ -0,0 +1,359 @@ +#+title: RAID 50 simulation +#+subtitle: with message size of 8 bytes and 6 disks +#+date: 2024H1 + +* Task +:PROPERTIES: +:CUSTOM_ID: task +:END: +#+begin_note +This is a machine translation.[fn:1] +#+end_note + +Each student individually needs to develop an application that +simulates the operation of a RAID array at levels 6 and 50 (5+0) with +a specified size of the original message and the number of disks. The +application performs read and write operations on the message at the +specified address (a linear array of strings with indices from 0 to +63). A table with task options is attached to the email, where one "+" +symbol indicates one available option. Distribute them among +yourselves in such a way that each person gets their own variant. The +work must be completed in the form of an executable application file, +a report, and an archive with the source code. + +The parameters for the task variants are from the table. +1) Array type: RAID 6 or RAID 50 (5+0). Information about these levels + in a simple and accessible form with explanatory images: + https://en.wikipedia.org/wiki/Standard_RAID_levels. RAID 6 Arrays + must restore data in case of failure of any two disks, RAID 50 + arrays -- in case of failure of any one disk. +2) Redundancy calculation: XOR and/or POLY. XOR -- calculating the + value of a redundancy block using the "exclude or" operation for a + pair of blocks. In case of a larger and/or an odd number of blocks + messages can use a hierarchical XOR calculation., adding a fixed + service value (for example, a set of "1" according to the block + size) and any other techniques you choose discretion. POLY -- + calculating the value of the redundancy block with using polynomial + expressions (for example, a pair of polynomials the first level is + A-B+C-D+E=X and A+2B-3C+4D-5E=Y for a RAID 6 array of seven disks, + where A..E are the blocks that make up the original message, X and + Y are redundancy blocks). +3) Message size: 8, 10, 12, 14 bytes. This is the size of the + original (whole) message to be written to the array and read from + the array. Message This size is specified by the user when + selecting a write operation, and the same size messages are given + to the user when selecting a read operation. +4) Number of disks: 3, 4, 5, 6, 7, 8, 10. This is the total number + disks in the array for writing message blocks and redundancy + blocks. + +Comments on the table. +1) You can, if you wish, choose a more complex RAID array + configuration, such as RAID 60 (6+0), if you’re interested, but + this must be согласован with me. +2) You can, if you wish, choose any other method of calculating + redundancy blocks, if you’re interested, but this must be + согласован. with me. You also need to be sure that the chosen + method allows you to fully restore the original message in case of + loss. any two blocks for RAID 6/60 (any message block + any block + redundancy, any two message blocks, two redundancy blocks). The + hierarchical calculation of XOR is demonstrated by the following + example. Let's give a RAID 5 array on five disks and the message + 12345678(hex). Then the message blocks will be: 12, 34, 56, 78. We + count the XOR separately for the first pair of blocks: 12 XOR 34 = + 26, separately for the second pair blocks: 56 XOR 78 = 2E, then + count the XOR for these two results: 26 XOR 2E = 08 -- we will + write this value in the block. redundancy. Now, if we lose any + message block (for example, 34), we will restore it. First, let's + check which original pair the block is missing from and calculate + the XOR of the remaining pair: 56 XOR 78 = 2E, now we count the XOR + of our redundancy block with the resulting result: 08 XOR 2E = 26 + -- got the XOR of the first pair of values, now we find the lost + block from this value and the saved one. message block: 26 XOR 12 + = 34 — the message block is restored, we can fully reconstruct the + original message. Adding a fixed service value can help, for + example, if the number of blocks is odd. Let’s say we have a RAID + 5 array on four disks and the message is 123456(hex). Then the + message blocks will be: 12, 34, 56. You can add a service value, + for example, FF as of a fixed “virtual” block and completely repeat + the algorithm described above. Or you can do it differently: + calculate the XOR for the first pair of message blocks, then + calculate the XOR of the resulting value and the remaining message + block. That is: 12 XOR 34 = 26, 26 XOR 56 = 70 — this value will be + written to the redundancy block. +3) After analyzing the message size and the number of disks, you can + see that the message is not always "divided" into an integer number + of blocks. This should not bother you, because you can always + adopt rules according to which you will supplement the message + block with seniors. zeros so that all blocks have the same size. + For example, let given a RAID 6 array on five disks and a 5 byte + message (Martin: If we take ASCII, not hex...): 12345(hex). Given + that two disks will be used for redundancy when writing the + message, we need to divide the original message into three blocks: + 12, 34, 5. The last block can be supplemented with a leading zero + to get the value 05, which will be written to the disk. +4) Do not forget that the parity in RAID 5 and 6 arrays, as well as in + their derivatives, is distributed. That is, when accessing each + next "row", the blocks of messages and redundancy will be They can + be arranged in different order. You can use a simple technique: + create a placement matrix and select a row of the matrix on based + on dividing the address modulo the number of disks. For example, + let there will be a RAID 5 array on four disks. For him, the + matrix of block placements can be as follows (here BS is a message + block, BI is a block redundancy). + +Your application can use either of two approaches as disks: text files +(one disk is one file, one message block -- one line of the file) or a +database (one disk - one table, one message block - one table entry) +at your discretion. Files and tables must be named + +* Documentation +:PROPERTIES: +:CUSTOM_ID: documentation +:END: +The exported report can be found at [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/latest/report.pdf][this link]]. + +* Showcase +:PROPERTIES: +:CUSTOM_ID: showcase +:END: +A sample session of working with the program is provided; lines with +comments start with =#=.[fn:2] +#+begin_src text +# Program start, there are no disk files +INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages... +WARNING: found bad disk (missing): disk0 +WARNING: found bad disk (missing): disk1 +WARNING: found bad disk (missing): disk2 +WARNING: found bad disk (missing): disk3 +WARNING: found bad disk (missing): disk4 +WARNING: found bad disk (missing): disk5 +ERROR: too many bad disks, reinitializing the array with new disks... +# At this point, the disk files already exist. +> 0 asdf +ERROR: invalid command, must be on of (read, write) +> 0 read asdf +ERROR: trailing junk after command: asdf +> 0 write +ERROR: expected 16 hex digits for message, received 0 +> 0 write 112233445566778 +ERROR: expected 16 hex digits for message, received 15 +> 0 write 11223344556677888 +ERROR: expected 16 hex digits for message, received 17 +> 0 write asdf +ERROR: message contains invalid character `s' +> 0 write -10 +ERROR: message contains invalid character `-' +> +> 0 write 1122334455667788 +> 1 write 1122334455667788 +> 2 write 1122334455667788 +> 0 read +1122334455667788 +> 1 read +1122334455667788 +> 2 read +1122334455667788 +> +# Manualy damaged the disk2 file +> 0 read +WARNING: found bad disk (corrupted): disk2 +INFO: there is just 1 bad disk, recomputing it... +1122334455667788 +> +# Manualy damaged the disk4 file +> 1 read +WARNING: found bad disk (corrupted): disk4 +INFO: there is just 1 bad disk, recomputing it... +1122334455667788 +> +# Manualy damaged disk0 and disk5 files => we can recover +> 2 read +WARNING: found bad disk (corrupted): disk0 +WARNING: found bad disk (corrupted): disk5 +INFO: there are 2 bad disk in separate clusters, recomputing them... +1122334455667788 +> +# Manualy damaged disk0 and disk1 files => we can't recover +> 0 read +WARNING: found bad disk (corrupted): disk0 +WARNING: found bad disk (corrupted): disk1 +ERROR: too many bad disks, reinitializing the array with new disks... +No data stored! +> +# No message has been recorded at address 0x1F yet +> 1F read +No data stored! +> +# Attempt to access an address outside the allowed range +> 40 read +ERROR: address not in set [0x00; 0x40) +> AA read +ERROR: address not in set [0x00; 0x40) +> 100 read +ERROR: address not in set [0x00; 0x40) +> interrupt +#+end_src + +* Releases +- [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/latest/][latest]] +- [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/][all]] + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse + +* Footnotes +:PROPERTIES: +:CUSTOM_ID: footnotes +:END: +[fn:1] Original text: +#+HTML: +#+begin_quote +Каждому студенту индивидуально необходимо разработать приложение, +моделирующее работу RAID-массива уровней 6 и 50 (5+0) с заданными +размером исходного сообщения и числом дисков. Приложение выполняет +операции чтения и записи сообщения по указываемому адресу (линейный +массив строк с индексами от 0 до 63). К письму приложена таблица с +вариантами заданий, где один символ "+" обозначает один доступный для +выбора вариант. Распределите их между собой таким образом, чтобы +каждому достался свой вариант. Работа должна быть выполнена в виде +исполняемого файла приложения, отчёта, архива с исходным кодом. + +Параметры вариантов задания из таблицы. +1) Тип массива: RAID 6 или RAID 50 (5+0). Информация об этих уровнях + в простой и доступной форме с поясняющими изображениями: + https://en.wikipedia.org/wiki/Standard_RAID_levels. Массивы RAID 6 + должны восстанавливать данные при выходе из строя любых двух + дисков, массивы RAID 50 -- при выходе из строя любого одного диска. +2) Подсчёт избыточности: XOR и/или POLY. XOR -- подсчёт значения + блока избыточности с использованием операции "исключающего или" для + пары блоков. В случае большего и/или нечётного количества блоков + сообщения можно использовать иерархическое вычисление XOR, + добавление фиксированного служебного значения (например, набор "1" + соответственно размеру блока) и любые другие приёмы на ваше + усмотрение. POLY -- подсчёт значения блока избыточности с + использованием полиномиальных выражений (например, пара полиномов + первого уровня вида A-B+C-D+E=X и A+2B-3C+4D-5E=Y для массива RAID + 6 из семи дисков, где A..E -- блоки, составляющие исходное + сообщение, X и Y -- блоки избыточности). +3) Размер сообщения: 8, 10, 12, 14 байт. Это размер исходного (целого) + сообщения для записи на массив и читаемого с массива. Сообщение + такого размера указывает пользователь при выборе операции записи и + такого же размера сообщения выдаются пользователю при выборе + операции чтения. +4) Количество дисков: 3, 4, 5, 6, 7, 8, 10. Это общее количество + дисков в массиве для записи блоков сообщения и блоков избыточности. + +Комментарии по таблице. +1) Вы можете, по желанию, выбрать более сложный вариант массива RAID + 60 (6+0), если вам это интересно, но это необходимо согласовать со + мной. +2) Вы можете, по желанию, выбрать любой другой способ подсчёта блоков + избыточности, если вам это интересно, но это необходимо согласовать + со мной. Также вы должны быть уверены, что выбранный способ + позволяет вам полностью восстановить исходное сообщение при потере + любых двух блоков для RAID 6/60 (любой блок сообщения + любой блок + избыточности, любые два блока сообщения, два блока избыточности). + Иерархическое вычисление XOR демонстрируется следующим примером. + Пусть дан массив RAID 5 на пяти дисках и сообщение 12345678(hex). + Тогда блоки сообщения будут: 12, 34, 56, 78. Считаем XOR отдельно + для первой пары блоков: 12 XOR 34 = 26, отдельно -- для второй пары + блоков: 56 XOR 78 = 2E, затем считаем XOR для этих двух + результатов: 26 XOR 2E = 08 -- это значение и запишем в блок + избыточности. Теперь при потере любого блока сообщения + (например, 34) восстановим его. Сначала проверим, из какой + исходной пары пропал блок и посчитаем XOR оставшейся пары: 56 XOR + 78 = 2E, теперь считаем XOR нашего блока избыточности с полученным + результатом: 08 XOR 2E = 26 -- получили XOR первой пары значений, + теперь находим потерянный блок из этого значения и сохранившегося + блока сообщения: 26 XOR 12 = 34 -- блок сообщения восстановлен, + можем полностью собрать исходное сообщение. Добавление + фиксированного служебного значения может помочь, например, если + количество блоков нечётное. Пусть дан массив RAID 5 на четырёх + дисках сообщение 123456(hex). Тогда блоки сообщения будут: 12, + 34, 56. Можно добавить служебное значение, например, FF в качестве + фиксированного "виртуального" блока и полностью повторить описанный + выше алгоритм. А можно и поступить иначе: вычислять XOR для первой + пары блоков сообщения, затем вычислять XOR полученного значения и + оставшегося блока сообщения. То есть: 12 XOR 34 = 26, 26 XOR 56 = + 70 -- это значение и запишем в блок избыточности. +3) Проанализировав размер сообщения и количество дисков, вы можете + увидеть, что сообщение не всегда "делится" на целое число блоков. + Это не должно вас смущать, поскольку вы всегда можете принять + правила, по которым будете дополнять блок сообщения старшими + нулями, чтобы все блоки имели одинаковый размер. Например, пусть + дан массив RAID 6 на пяти дисках и сообщение размером 5 байт (Мартин: + если брать ascii, а не hex...): 12345(hex). Учитывая, что два + диска при записи сообщения будут задействованы под избыточность, + нам необходимо разделить исходное сообщение на три блока: 12, + 34, 5. Последний блок можно дополнить старшим нулём, чтобы получить + значение 05, которое и будет записано на диск. +4) Не забывайте, что чётность в массивах RAID 5 и 6, как и в + производных от них, распределённая. То есть, при обращении к + каждой следующей "строке" блоки сообщений и избыточности будут + располагаться в разном порядке. Вы можете использовать простой + приём: создать матрицу размещений и выбирать строку матрицы на + основе деления адреса по модулю от числа дисков. Например, пусть + будет массив RAID 5 на четырёх дисках. Для него матрица размещений + блоков может быть такой (здесь БС -- блок сообщения, БИ -- блок + избыточности). + +В качестве дисков ваше приложение может использовать любой из двух +подходов: текстовые файлы (один диск -- один файл, один блок сообщения +-- одна строка файла) или базу данных (один диск -- одина таблица, +один блок сообщения -- одна запись таблицы) на ваше усмотрение. Файлы +и таблицы должны быть проименованы как disk0..disk9, файлы должны +располагаться в рабочем каталоге приложения и не блокироваться для +записи в процессе его работы (чтобы можно было очистить содержимое +любого файла или удалить его, моделируя выход диска из строя). + +Примеры пользовательских операций (массив RAID 5 на трёх дисках): + +=> 00 write 3d6c= (адрес: 00, операция: запись, сообщение: 3D6C, блок +сообщения для записи на диск 0: 3D, блок сообщения для записи на диск +1: 6C, блок избыточности для записи на диск 2 -- арифметическая сумма +3В+6С: A9); + +=> 01 write 519a= (адрес: 01, операция: запись, сообщение: 519A, блок +сообщения для записи на диск 0: 51, блок избыточности для записи на +диск 2 -- арифметическая сумма 51+9A: EB, блок сообщения для записи на +диск 1: 9A); + +... удаляем содержимое файла или таблицы "disk0"; + +=> 00 read= (адрес: 00, операция: чтение, диск 0: пусто, диск 1: блок +сообщения 6C, диск 2: блок избыточности A9, вычисляем блок сообщения +диска 0: A9-6C=3D, собираем сообщение: 3D6C). + +Графика, анимации, счётчики -- ничего этого не нужно, простое +консольное приложение. При использовании базы данных необходимо +отдельно приложить файлы сценариев создания таблиц, в качестве +диалектов допустимы T-SQL и MySQL. +#+end_quote +#+HTML: + +[fn:2] I've actually implemented all of these configurations: +- [[file:../tree/src/raid-4-poly-10b-7d.c][raid-4-poly-10b-7d]] +- [[file:../tree/src/raid-4-poly-8b-6d.c][raid-4-poly-8b-6d]] +- [[file:../tree/src/raid-4-poly-8b-7d.c][raid-4-poly-8b-7d]] +- [[file:../tree/src/raid-4-xor-10b-3d.c][raid-4-xor-10b-3d]] +- [[file:../tree/src/raid-4-xor-10b-6d.c][raid-4-xor-10b-6d]] +- [[file:../tree/src/raid-4-xor-10b-7d.c][raid-4-xor-10b-7d]] +- [[file:../tree/src/raid-4-xor-12b-4d.c][raid-4-xor-12b-4d]] +- [[file:../tree/src/raid-4-xor-12b-5d.c][raid-4-xor-12b-5d]] +- [[file:../tree/src/raid-4-xor-12b-7d.c][raid-4-xor-12b-7d]] +- [[file:../tree/src/raid-4-xor-14b-4d.c][raid-4-xor-14b-4d]] +- [[file:../tree/src/raid-4-xor-14b-5d.c][raid-4-xor-14b-5d]] +- [[file:../tree/src/raid-4-xor-14b-8d.c][raid-4-xor-14b-8d]] +- [[file:../tree/src/raid-4-xor-8b-8d.c][raid-4-xor-8b-8d]] +- [[file:../tree/src/raid-5-poly-14b-4d.c][raid-5-poly-14b-4d]] +- [[file:../tree/src/raid-5-xor-12b-3d.c][raid-5-xor-12b-3d]] +- [[file:../tree/src/raid-5-xor-12b-5d.c][raid-5-xor-12b-5d]] +- [[file:../tree/src/raid-5-xor-12b-6d.c][raid-5-xor-12b-6d]] +- [[file:../tree/src/raid-50-poly-12b-6d.c][raid-50-poly-12b-6d]] +- [[file:../tree/src/raid-50-poly-8b-6d.c][raid-50-poly-8b-6d]] +- [[file:../tree/src/raid-50-xor-12b-6d.c][raid-50-xor-12b-6d]] +- [[file:../tree/src/raid-50-xor-8b-6d.c][raid-50-xor-8b-6d]] diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty @@ -0,0 +1,57 @@ +\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] + +\def\UrlBreaks{\do\/\do-} +\RequirePackage{url} + +\newdimen\bibindent +\renewenvironment{thebibliography}[1]{ + \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy\clubpenalty4000\widowpenalty4000% + \sfcode`\.\@m +}{ + \setcounter{totalbib}{\c@enumiv}% + \def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist +} +\renewcommand\@biblabel{}% +\setlength\bibindent{1.5em} + +% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. +%\makeatletter +\renewcommand*{\@biblabel}[1]{\hfill#1.} + + +% +% Remove References header completely +% Stolen from original article.cls +% +\makeatletter +\renewenvironment{thebibliography}[1]{% +% \usection{\refname}% +% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% + \list{\@biblabel{\@arabic\c@enumiv}}% + {\settowidth\labelwidth{\@biblabel{#1}}% + \leftmargin\labelwidth + \advance\leftmargin\labelsep + \@openbib@code + \usecounter{enumiv}% + \let\p@enumiv\@empty + \renewcommand\theenumiv{\@arabic\c@enumiv}}% + \sloppy + \clubpenalty4000 + \@clubpenalty \clubpenalty + \widowpenalty4000% + \sfcode`\.\@m} + {\def\@noitemerr + {\@latex@warning{Empty `thebibliography' environment}}% + \endlist} +\makeatother diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..1dff33f --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty @@ -0,0 +1,23 @@ +\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{caption} +\RequirePackage{subcaption} + +% +% Table caption aligned to the left with dash as a separator +% +\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off} + +% +% Dash as separator in figure caption and centering +% +\captionsetup[figure]{labelsep=endash, justification=centering} + +% +% Listing caption +% +\captionsetup[listing]{labelsep=endash, justification=centering} + +\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}} +\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}} +\addto\captionsrussian{\captionsetup[listing]{name=Листинг}} diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..d694c93 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty @@ -0,0 +1,37 @@ +\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] + +% +% Values for capital russian letters counter +% +\makeatletter +\newcommand\AlphRus[1]{% + \expandafter \@AlphRus \csname c@#1\endcsname +} + +\newcommand\@AlphRus[1]{% + \ifcase #1% + \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or + Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or + Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% + \else \@ctrerr +\fi +} +\makeatother + +% +% Values for lowercase russian letters counter +% +\makeatletter +\newcommand\alphRus[1]{% + \expandafter \@alphRus \csname c@#1\endcsname +} + +\newcommand\@alphRus[1]{% + \ifcase #1% + \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or + л\or м\or н\or п\or р\or с\or т\or у\or ф\or + х\or ц\or ш\or щ\or э\or ю\or я% + \else \@ctrerr +\fi +} +\makeatother diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..d0bb40e --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty @@ -0,0 +1,98 @@ +\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{titlesec} +\RequirePackage{titling} +\RequirePackage{setspace} + +\RequirePackage{gost-7-32-counters} + +% +% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection +% +\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} +\titlespacing{\section}{0cm}{0cm}{0.5cm} + +\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} +\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} + +\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] +\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} + +% +% Make special headings, that have their own formatting rules: +% - centered +% - all-caps +% - bold +% +% Only three of them must appear in TOC: introduction, conclusion and references +% +\newcommand{\introduction}{ + \addcontentsline{toc}{section}{ВВЕДЕНИЕ} + \begin{center} + \bfseries\large + ВВЕДЕНИЕ + \end{center} +} + +\newcommand{\conclusion}{ + \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} + \begin{center} + \bfseries\large + ЗАКЛЮЧЕНИЕ + \end{center} +} + +\newcommand{\references}{ + \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} + \begin{center} + \bfseries\large + СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ + \end{center} +} + +\newcommand{\essay}{ + \begin{center} + \bfseries\large + РЕФЕРАТ + \end{center} +} + +\newcommand{\definitions}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ + \end{center} +} + +\newcommand{\abbreviations}{ + \begin{center} + \bfseries\large + ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +\newcommand{\defsabbrs}{ + \begin{center} + \bfseries\large + ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ + \end{center} +} + +% +% Appendices headings. Appendices have autoincrementing number, +% that is represented with russian letter. +% This heading must appear in TOC +% +\newcounter{appendixcnt} +\setcounter{appendixcnt}{1} + +\renewcommand{\appendix}[1]{ + \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} + \begin{center} + \bfseries\large + ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} + + #1 + \end{center} + \stepcounter{appendixcnt} +} diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..b68d55f --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty @@ -0,0 +1,15 @@ +\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{enumitem} +\RequirePackage{gost-7-32-counters} + +\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} + +\setlist{nosep} +\setlist[itemize, 1]{label=\textendash} +\setlist[itemize, 2]{label=\bullet} + +\setlist[enumerate, 2]{label=\alphRus*)} + +\setlist[1]{wide=\parindent} +\setlist[2]{wide=2\parindent, leftmargin=\parindent} diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..750ab75 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty @@ -0,0 +1,29 @@ +\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] + +\RequirePackage{tabularx} + +% +% Center-aligned column with automatic width +% +\newcolumntype{Y}{>{\centering\arraybackslash}X} + +% +% Right-aligned column with automatic width +% +\newcolumntype{Z}{>{\raggedleft\arraybackslash}X} + +% +% Table with designations +% +\newenvironment{designations}{ + \noindent + \tabularx{\textwidth}{@{} + >{\raggedright \arraybackslash \hsize=0.25\hsize}X + >{\centering \arraybackslash \hsize=0.05\hsize}X + >{\arraybackslash \hsize=0.70\hsize}X + } +}{ + \endtabularx +} + +\newcommand{\designation}[2]{#1 &---& #2. \\} diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..c3b835a --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty @@ -0,0 +1,34 @@ +\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] + +%% \RequirePackage{tocloft} +\RequirePackage[ + bookmarks=true, + colorlinks=true, + unicode=true, + urlcolor=black, + linkcolor=black, + anchorcolor=black, + citecolor=black, + menucolor=black, + filecolor=black +]{hyperref} + +% +% Set custom font styles +% +%% \renewcommand{\cftsecfont}{\normalfont} +%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} +%% \renewcommand{\cftsecpagefont}{\normalsize} +%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries} +%% \renewcommand{\cftaftertoctitle}{\hfill\hfill} +%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries} +\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} +\titlespacing{\tableofcontents}{0cm}{0cm}{1cm} + +% +% Set indents and line spacing +% +%% \setlength{\cftbeforesecskip}{0cm} +%% \setlength{\cftbeforesubsecskip}{0cm} +%% \setlength{\cftbeforesubsubsecskip}{0cm} +%% \setlength{\cftbeforeparaskip}{0cm} diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..c13b00e --- /dev/null +++ b/doc/gost/gost-7-32.cls @@ -0,0 +1,62 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] + +% +% Supported font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +% +% Set A4 paper format +% +\LoadClass[a4paper]{extarticle} + +% +% Use 1.5 line spacing +% +\RequirePackage{setspace} +\spacing{1.5} + +% +% First paragraph indentation +% +\RequirePackage{indentfirst} +\setlength{\parindent}{12.5mm} + +% +% Page margin +% +\RequirePackage[ + left=2.5cm, + right=2cm, + top=2cm, + bottom=2cm, + footskip=1cm, +]{geometry} + +% +% Use TMR-like font +% +\RequirePackage{fontspec} +\RequirePackage{xunicode} +\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +\setmainfont{Times New Roman} + +% +% Use russian language +% +\RequirePackage[main=russian, english]{babel} +\babelhyphenation[russian]{} + +% +% gost-7-32 packages +% +\RequirePackage{gost-7-32-headings} +\RequirePackage{gost-7-32-toc} +\RequirePackage{gost-7-32-lists} +\RequirePackage{gost-7-32-bibliography} +\RequirePackage{gost-7-32-captions} +\RequirePackage{gost-7-32-tables} diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..913d021 --- /dev/null +++ b/doc/ox-init.el @@ -0,0 +1,32 @@ +;;; ox-init --- Initialization script for async org exprort session +;;; Commentary: +;;; Code: +(org-babel-do-load-languages + 'org-babel-load-languages + '((latex . t) + (C . t))) + +(require 'ox-extra) +(ox-extras-activate '(ignore-headlines)) + +(require 'oc-bibtex) + +(setq org-latex-src-block-backend 'minted) + +(setq org-latex-bib-compiler "biber") + +(setq org-latex-remove-logfiles nil) + +(setq org-latex-caption-above '(table src-block special-block)) + +(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" + "%bib %b" + "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) +(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" + ("\\section{%s}" . "\\usection{%s}") + ("\\subsection{%s}" . "\\subsection*{%s}") + ("\\subsubsection{%s}" . "\\subsubsection*{%s}") + ("\\paragraph{%s}" . "\\paragraph*{%s}") + ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) + +;;; ox-init.el ends here diff --git a/doc/raid0.png b/doc/raid0.png new file mode 100644 index 0000000..451f892 Binary files /dev/null and b/doc/raid0.png differ diff --git a/doc/raid5.png b/doc/raid5.png new file mode 100644 index 0000000..02a4a9a Binary files /dev/null and b/doc/raid5.png differ diff --git a/doc/raid50.png b/doc/raid50.png new file mode 100644 index 0000000..8a0a824 Binary files /dev/null and b/doc/raid50.png differ diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..061295c --- /dev/null +++ b/doc/report.org @@ -0,0 +1,269 @@ +#+TITLE: Разработка приложения, моделирующего работу RAID 50 с заданным размером исходного сообщения --- 8 байт и 6 дисками +#+AUTHOR: Михалец Мартин +#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ} +#+LATEX_HEADER: \subject{по дисциплине «Архитектура суперкомпьютеров»} +#+LATEX_HEADER: \reviewertitle{}\reviewer{Чуватов Михаил Владимирович} +#+DATE: 2024 + +#+SETUPFILE: setup.org +#+LATEX: \sloppy + +* Введение +:PROPERTIES: +:UNNUMBERED: t +:END: +В данном отчёте представлено описание шестой лабораторной работы в +которой необходимо было разработать приложение, моделирующее работу +RAID-массива уровня 50 (5+0) с заданными размером исходного сообщения +и числом дисков. Приложение выполняет операции чтения и записи +сообщения по указываем адресу. Работа должна быть выполнена в виде +исполняемого файла приложения, отчёта и архива с исходным кодом. В качестве дисков приложение использует текстовые файлы: =disk0=, =disk1=, =disk2=, =disk3=, =disk4=, =disk5=. + +*Выбранный вариант:* +- Тип массива --- RAID 50 +- Подсчет избыточности --- XOR +- Размер сообщения --- 8 байт +- Количество дисков --- 8 +- Представление дисков --- текстовые файлы + +* Математическое описание +** RAID +RAID (/Reduntant Array of Independent Disks --- избыточный массив +самостоятельных/независимых дисков/) --- это технология объединения +двух и более накопителей в единый логический элемент с целью повышения +производительности и, или, отказоустойчивости отдельно взятого +элемента/-ов массива. + +Избыточные данные по-другому называют дополнительными. Для их +хранения нужун какой-то объем. Выделяемый объем для этих данных в +массивах называется аналогично --- избыточным. Избыточность массива +--- это наличие такого объема, чем больше который, тем больше у +массива избыточности, что в свою очередь обеспечивает +отказоустойчивость. + +Простыми словами, RAID-массив --- это несколько дисков соединенные в +единый диск с выделением места под хранение информации для исправления +ошибок в данных. + +Накопители в массив можно объединять по-разному, и на вы выходе +получать разные массивы со своими достоинствами и недостатками, от +которых будет зависеть выбор для разных сценариев. Каждый такой +массив еще называется уровнем. + +#+LATEX: \newpage\cleardoublepage +** RAID 0 +RAID 0 (также /stripe/ или /striped volume/) равномерно распределяет +данные (/полосы/) по двум или более дискам без дополнительной избыточной +информации. Поскольку RAID 0 не обеспечивает отказоустойчивости, +отказ одного диска приведет к сбою всего массива из-за распределения +данных по всем дискам. Обычно такая конфигурация реализуется для +повышения пропускной способности, хотя его также можно использовать +как способ создания большого логического тома из двух или больше +физических дисков (см. рисунок [[raid0]]). + +#+name: raid0 +#+caption: Схема RAID 0 на 2 дисках +#+attr_latex: :float nil :height 10cm +[[./raid0.png]] + +#+LATEX: \newpage\cleardoublepage +** RAID 5 +RAID 5 состоит из чередования на уровне блоков с распределенной четностью. Информация о четности распределяется между дисками. Для работы требуется присутствие всех дисков, кроме одного. При сбое одного диска последующие операции чтения могут быть рассчитаны на основе распределенной четности таким образом, чтобы данные не были потеряны. Для применения RAID 5 требуется не менее трёх дисков. + +В массиве дисководов RAID 5 существует множество компоновок данных и четности в зависимости от последовательности записи на диски, то есть: +- Последовательность блоков банных, записываемых слева направо или + справа налево на дисковом массиве, с дисков от 0 до n. +- Разложение блока четности в начале или конце полосы. +- Расположение первого блока полосы относительно чётности предыдущей + полосы. + +На рисунке [[raid5]] показаны блоки данных, записанные слева направо, блок +чётности в конце полосы и первый блок следующей полосы не на том же +диске, что и блок чётности предыдущей полосы. Его можно обозначить +как левосторонний асинхронный макет RAID 5. В синхронной компоновке +первый блок данных следующей полосы записывается на тот же диск, что и блок чётности предыдущей полосы. + +#+name: raid5 +#+caption: Схема RAID 5 на 4 дисках +#+attr_latex: :float nil :height 10cm +[[./raid5.png]] + +#+LATEX: \newpage\cleardoublepage +** RAID 50 +RAID 50 --- объединение обычно двух, или более, массивов RAID 5 в +полосу, т.е. комбинация RAID 5 и RAID 0 (см. рисунок [[raid50]]), частично +исправляющая главный недостаток RAID 5 --- малая пропускная +способность записи данных за счет параллельного использования +нескольких таких массивов. Общая ёмкость массива уменьшается на +ёмкость двух дисков, но, в отличие от RAID 6, без потери данных такой +массив переносит отказ при потере одного диска на RAID 5 массив. +Минимальное необходимое число дисков для создания массива RAID 50 +равно 6. Наряду с RAID 10, это наиболее рекомендуемый уровень RAID +для использования в приложениях, где требуется высокая +производительность в сочетании с приемлемой надёжностью. + +#+name: raid50 +#+caption: Схема RAID 50 на 6 дисках +#+attr_latex: :float nil :height 10cm +[[./raid50.png]] + +* Особенности реализации +** Представление дисков +В данной работе в качестве дисков используются текстовые файлы. Один +файл --- один диск. Программа сама обеспечивает присутствие файлов +дисков в правильном формате, пересчитывая поврежденные или удаленные +файлы дисков, если это возможно, иначе она заново инициализирует все +файлы дисков. Каждый диск может хранить до 64 (=0x40=) блоков и каждый +блок хранит 2Б. Блоки и адреса в программе представляются в +шестнадцатеричной системе счисления. Адрес блока --- номер строки в +файле. Если на определённом адресе блок не записан, то на его месте +хранится служебное значение из пробелов, чтобы отличить записан блок +от блока нулей. + +#+name: shift-tbl +#+caption: Зависимость диска блока от адреса сообщения +#+attr_latex: :float nil :align r|ccc|ccc| :font \ttfamily +| addr % 3 | disk0 | disk1 | disk2 | disk3 | disk4 | disk5 | +|----------+-------+-------+-------+-------+-------+-------| +| 0 | БС1 | БС2 | БИ1 | БС3 | БС4 | БИ2 | +| 1 | БС1 | БИ1 | БС2 | БС3 | БИ2 | БС4 | +| 2 | БИ1 | БС1 | БС2 | БИ2 | БС3 | БС4 | + +По таблицы [[shift-tbl]] видно, что первая половина сообщения всегда на +дисках первого массива, а вторая на дисках второго, причем на каждом +из дисков хранится либо избыточная информация либо 1/4 сообщения, +откуда и получается размер блока 2Б. + +** Запись сообщения +Команда записи сообщения имеет следующую штатную форму: =АА write +Б0Б1Б2Б3Б4Б5Б6Б7=, где =AA= --- адрес, =Бx= x-ый байт сообщения. При +успешном запуске команды =write= сначала проверяются диски на +исправность с устранением неисправностей, дальше отдельно для обоих +пар блоков сообщения считается их четность, и в итоге все блоки +записываются в ответствующие адресу файлы (см. таблицу [[shift-tbl]]). + +** Чтение сообщения +Команда чтения сообщения имеет следующую штатную форму: =АА read=, +печатая =Б0Б1Б2Б3Б4Б5Б6Б7=, где =AA= --- адрес, =Бx= x-ый байт сообщения. +При успешном запуске команды =read= сначала проверяются диски на +исправность с устранением неисправностей, дальше считаются блоки +сообщения из ответствующих адресу файлов (см. таблицу [[shift-tbl]]). + +Есть несколько случаев сборки сообщения: +1. Массивы целы --- блоки сообщения считываются как есть. +2. Выход из строя одного диска --- у подмассива, у которого вышел диск + из строя считываются блоки исправных дисков и для получения + последнего неисправного блока между ними выполняется операция XOR. + С другого, целого, подмассива блоки считываются как в пункте 1. +3. Выход из строя двух дисков на отдельных массивах --- блоки + считаются с обоих подмассивов как они считались в пункте 2 с + единственного неисправного. +4. Выход из строя двух или более дисков одного из массивов --- в этом + случае не получится собрать ни одного сообщения, потеря информации. + +* Результаты работы +Приводится примерочный сеанс работы с программой, строки с +комментариями сеанса начинаются с =#=. +#+begin_src text +# Запуск программы, файлов дисков нет +INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages... +WARNING: found bad disk (missing): disk0 +WARNING: found bad disk (missing): disk1 +WARNING: found bad disk (missing): disk2 +WARNING: found bad disk (missing): disk3 +WARNING: found bad disk (missing): disk4 +WARNING: found bad disk (missing): disk5 +ERROR: too many bad disks, reinitializing the array with new disks... +# На этот момент файлы дисков ужу существуют +> 0 asdf +ERROR: invalid command, must be on of (read, write) +> 0 read asdf +ERROR: trailing junk after command: asdf +> 0 write +ERROR: expected 16 hex digits for message, received 0 +> 0 write 112233445566778 +ERROR: expected 16 hex digits for message, received 15 +> 0 write 11223344556677888 +ERROR: expected 16 hex digits for message, received 17 +> 0 write asdf +ERROR: message contains invalid character `s' +> 0 write -10 +ERROR: message contains invalid character `-' +> +> 0 write 1122334455667788 +> 1 write 1122334455667788 +> 2 write 1122334455667788 +> 0 read +1122334455667788 +> 1 read +1122334455667788 +> 2 read +1122334455667788 +> +# Мануальное повреждение файла disk2 +> 0 read +WARNING: found bad disk (corrupted): disk2 +INFO: there is just 1 bad disk, recomputing it... +1122334455667788 +> +# Мануальное повреждение файла disk4 +> 1 read +WARNING: found bad disk (corrupted): disk4 +INFO: there is just 1 bad disk, recomputing it... +1122334455667788 +> +# Мануальное повреждение файлов disk0 и disk5 => можно востановить +> 2 read +WARNING: found bad disk (corrupted): disk0 +WARNING: found bad disk (corrupted): disk5 +INFO: there are 2 bad disk in separate clusters, recomputing them... +1122334455667788 +> +# Мануальное повреждение файлов disk0 и disk1 => некак востановить +> 0 read +WARNING: found bad disk (corrupted): disk0 +WARNING: found bad disk (corrupted): disk1 +ERROR: too many bad disks, reinitializing the array with new disks... +No data stored! +> +# По адресу 0x1F пока не было записано сообщение +> 1F read +No data stored! +> +# Попытка обращения к адресу за пределами +> 40 read +ERROR: address not in set [0x00; 0x40) +> AA read +ERROR: address not in set [0x00; 0x40) +> 100 read +ERROR: address not in set [0x00; 0x40) +> interrupt +#+end_src + +* Заключение +:PROPERTIES: +:UNNUMBERED: t +:END: +В результате данной работы было разработано приложение --- модель RAID +50 с 6 дисками и размером сообщения 6 байт, а именно консольная +программа с двумя командами =read= и =write=, написанная на языке +программирования Си (=-std=gnu99=). Программа успешно хранит информацию +в файлах массива RAID 50, выводит необходимые сообщения и +восстанавливает диски в случае их неисправности. + +* Используемая литература +:PROPERTIES: +:UNNUMBERED: t +:END: +1. Standard RAID levels --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Standard_RAID_levels]] (Дата обращения: + 22.05.2024) +2. Nested RAID levels --- Википедия // URL: + [[https://en.wikipedia.org/wiki/Nested_RAID_levels]] (Дата обращения: + 22.05.2024) + +# Local Variables: +# org-confirm-babel-evaluate: nil +# org-export-async-init-file: "ox-init.el" +# org-export-in-background: t +# End: diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..9c95160 --- /dev/null +++ b/doc/setup.org @@ -0,0 +1,40 @@ +#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline +#+OPTIONS: author:t broken-links:nil c:nil creator:nil +#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t +#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t +#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t +#+SELECT_TAGS: export +#+EXCLUDE_TAGS: noexport +#+CREATOR: Emacs 29.1 (Org mode 9.6.9) +#+BIBLIOGRAPHY: biblio.bib +#+CITE_EXPORT: biblatex +#+LATEX_COMPILER: xelatex +#+LATEX_CLASS: spbstu-report +# #+LATEX_CLASS_OPTIONS: [draft] +#+LATEX_HEADER: \usepackage{enumitem} +#+LATEX_HEADER: \usepackage{array} +#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type +#+LATEX_HEADER: \usepackage{float} +#+LATEX_HEADER: \usepackage{tikz} +#+LATEX_HEADER: \usepackage{pgfplots} +#+LATEX_HEADER: \pgfplotsset{compat=1.18} +#+LATEX_HEADER: \usepackage{afterpage} +#+LATEX_HEADER: \usepackage{minted} +#+LATEX_HEADER: \usemintedstyle{bw} +#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines} +#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} +#+LATEX_HEADER: \usepackage{algorithm} +#+LATEX_HEADER: \usepackage{algpseudocode} +#+LATEX_HEADER: \makeatletter +#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм} +#+LATEX_HEADER: \makeatother +#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} +#+LATEX_HEADER: \setmainfont{Times New Roman} +#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff] +#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}} +#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label} +#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}} +#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt} +#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt} +#+LATEX_HEADER: \hypersetup{hidelinks} +#+LATEX_HEADER: \newcommand{\overbar}[1]{\mkern 1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu} diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..1389249 --- /dev/null +++ b/doc/spbstu-report.cls @@ -0,0 +1,73 @@ +\NeedsTeXFormat{LaTeX2e} +\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] + +% +% Support font sizes: 12pt, 14pt +% +\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} +\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} + +\ProcessOptions\relax + +\LoadClass[a4paper]{gost-7-32} + +\RequirePackage{csquotes} +\RequirePackage{amsmath} +\RequirePackage{adjustbox} +\RequirePackage{setspace} + +\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}} + +\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} +\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} +\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} +\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} +\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} +\renewcommand{\maketitle}{ + \begin{titlepage} + \begin{center} + \vspace{2cm} + \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} + + \normalsize{Федеральное государственное автономное + образовательное учреждение высшего образования + \enquote{Санкт-Петербургский политехнический университет Петра Великого}} + + \vspace{0.5cm} + \normalsize{Институт компьютерных наук и кибербезопасности} + + \normalsize{Высшая школа технологии искусственного интеллекта} + + \normalsize{Направление 02.03.03 Математическое обеспечение и администрирование информационных систем} + + \vspace{2cm} + \LARGE{ОТЧЁТ} + + \normalsize{\@reportof} + + \large{\@subject} + + \large{\textit{\@title}} + \end{center} + + \vspace{3cm} + \small{ + \begin{tabular}{lrrl} + \!\!\!Студент, & \hspace{2cm} & & \\ + \!\!\!группы 5130203/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ + \!\!\!Преподаватель, & \hspace{2cm} & \\ + \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ + &&\hspace{5cm} + \end{tabular} + \begin{flushright} + \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. + \end{flushright} + } + + \vspace*{\fill} + \begin{center} + \small{Санкт-Петербург, \@date} + \end{center} + \end{titlepage} + \setcounter{page}{2} +} diff --git a/doc/task.org b/doc/task.org new file mode 100644 index 0000000..50e2ed8 --- /dev/null +++ b/doc/task.org @@ -0,0 +1,137 @@ +Добрый день. + +Формулирование задания затянулось в связи с тем, что на выходных мне +всё ещё присылали для проверки программы из предыдущей работы и это +были не только те, кому предоставлялось время до конца выходных, но и +все остальные, кто должен был закончить работу раньше. Тем не менее, +удалось сформулировать новое и последнее практическое задание. В этот +раз для двух направлений задания или варианты заданий будут +различными. Ниже текст задания для студентов направления МКН. + +Итак, каждому студенту индивидуально необходимо разработать +приложение, моделирующее работу RAID-массива уровней 6 и 50 (5+0) с +заданными размером исходного сообщения и числом дисков. Приложение +выполняет операции чтения и записи сообщения по указываемому адресу +(линейный массив строк с индексами от 0 до 63). К письму приложена +таблица с вариантами заданий, где один символ "+" обозначает один +доступный для выбора вариант. Распределите их между собой таким +образом, чтобы каждому достался свой вариант. Работа должна быть +выполнена в виде исполняемого файла приложения, отчёта, архива с +исходным кодом. + +Дата и время завершения приёма работ и отчётов: 23:59 24.05.2024. + +Параметры вариантов задания из таблицы. +1) Тип массива: RAID 6 или RAID 50 (5+0). Информация об этих уровнях + в простой и доступной форме с поясняющими изображениями: + https://en.wikipedia.org/wiki/Standard_RAID_levels. Массивы RAID 6 + должны восстанавливать данные при выходе из строя любых двух + дисков, массивы RAID 50 -- при выходе из строя любого одного диска. +2) Подсчёт избыточности: XOR и/или POLY. XOR -- подсчёт значения + блока избыточности с использованием операции "исключающего или" для + пары блоков. В случае большего и/или нечётного количества блоков + сообщения можно использовать иерархическое вычисление XOR, + добавление фиксированного служебного значения (например, набор "1" + соответственно размеру блока) и любые другие приёмы на ваше + усмотрение. POLY -- подсчёт значения блока избыточности с + использованием полиномиальных выражений (например, пара полиномов + первого уровня вида A-B+C-D+E=X и A+2B-3C+4D-5E=Y для массива RAID + 6 из семи дисков, где A..E -- блоки, составляющие исходное + сообщение, X и Y -- блоки избыточности). +3) Размер сообщения: 8, 10, 12, 14 байт. Это размер исходного (целого) + сообщения для записи на массив и читаемого с массива. Сообщение + такого размера указывает пользователь при выборе операции записи и + такого же размера сообщения выдаются пользователю при выборе + операции чтения. +4) Количество дисков: 3, 4, 5, 6, 7, 8, 10. Это общее количество + дисков в массиве для записи блоков сообщения и блоков избыточности. + +Комментарии по таблице. +1) Вы можете, по желанию, выбрать более сложный вариант массива RAID + 60 (6+0), если вам это интересно, но это необходимо согласовать со + мной. +2) Вы можете, по желанию, выбрать любой другой способ подсчёта блоков + избыточности, если вам это интересно, но это необходимо согласовать + со мной. Также вы должны быть уверены, что выбранный способ + позволяет вам полностью восстановить исходное сообщение при потере + любых двух блоков для RAID 6/60 (любой блок сообщения + любой блок + избыточности, любые два блока сообщения, два блока избыточности). + Иерархическое вычисление XOR демонстрируется следующим примером. + Пусть дан массив RAID 5 на пяти дисках и сообщение 12345678(hex). + Тогда блоки сообщения будут: 12, 34, 56, 78. Считаем XOR отдельно + для первой пары блоков: 12 XOR 34 = 26, отдельно -- для второй пары + блоков: 56 XOR 78 = 2E, затем считаем XOR для этих двух + результатов: 26 XOR 2E = 08 -- это значение и запишем в блок + избыточности. Теперь при потере любого блока сообщения + (например, 34) восстановим его. Сначала проверим, из какой + исходной пары пропал блок и посчитаем XOR оставшейся пары: 56 XOR + 78 = 2E, теперь считаем XOR нашего блока избыточности с полученным + результатом: 08 XOR 2E = 26 -- получили XOR первой пары значений, + теперь находим потерянный блок из этого значения и сохранившегося + блока сообщения: 26 XOR 12 = 34 -- блок сообщения восстановлен, + можем полностью собрать исходное сообщение. Добавление + фиксированного служебного значения может помочь, например, если + количество блоков нечётное. Пусть дан массив RAID 5 на четырёх + дисках сообщение 123456(hex). Тогда блоки сообщения будут: 12, + 34, 56. Можно добавить служебное значение, например, FF в качестве + фиксированного "виртуального" блока и полностью повторить описанный + выше алгоритм. А можно и поступить иначе: вычислять XOR для первой + пары блоков сообщения, затем вычислять XOR полученного значения и + оставшегося блока сообщения. То есть: 12 XOR 34 = 26, 26 XOR 56 = + 70 -- это значение и запишем в блок избыточности. +3) Проанализировав размер сообщения и количество дисков, вы можете + увидеть, что сообщение не всегда "делится" на целое число блоков. + Это не должно вас смущать, поскольку вы всегда можете принять + правила, по которым будете дополнять блок сообщения старшими + нулями, чтобы все блоки имели одинаковый размер. Например, пусть + дан массив RAID 6 на пяти дисках и сообщение размером 5 байт (Мартин: + если брать ascii, а не hex...): 12345(hex). Учитывая, что два + диска при записи сообщения будут задействованы под избыточность, + нам необходимо разделить исходное сообщение на три блока: 12, + 34, 5. Последний блок можно дополнить старшим нулём, чтобы получить + значение 05, которое и будет записано на диск. +4) Не забывайте, что чётность в массивах RAID 5 и 6, как и в + производных от них, распределённая. То есть, при обращении к + каждой следующей "строке" блоки сообщений и избыточности будут + располагаться в разном порядке. Вы можете использовать простой + приём: создать матрицу размещений и выбирать строку матрицы на + основе деления адреса по модулю от числа дисков. Например, пусть + будет массив RAID 5 на четырёх дисках. Для него матрица размещений + блоков может быть такой (здесь БС -- блок сообщения, БИ -- блок + избыточности). + +В качестве дисков ваше приложение может использовать любой из двух +подходов: текстовые файлы (один диск -- один файл, один блок сообщения +-- одна строка файла) или базу данных (один диск -- одина таблица, +один блок сообщения -- одна запись таблицы) на ваше усмотрение. Файлы +и таблицы должны быть проименованы как disk0..disk9, файлы должны +располагаться в рабочем каталоге приложения и не блокироваться для +записи в процессе его работы (чтобы можно было очистить содержимое +любого файла или удалить его, моделируя выход диска из строя). + +Примеры пользовательских операций (массив RAID 5 на трёх дисках): + +=> 00 write 3d6c= (адрес: 00, операция: запись, сообщение: 3D6C, блок +сообщения для записи на диск 0: 3D, блок сообщения для записи на диск +1: 6C, блок избыточности для записи на диск 2 -- арифметическая сумма +3В+6С: A9); + +=> 01 write 519a= (адрес: 01, операция: запись, сообщение: 519A, блок +сообщения для записи на диск 0: 51, блок избыточности для записи на +диск 2 -- арифметическая сумма 51+9A: EB, блок сообщения для записи на +диск 1: 9A); + +... удаляем содержимое файла или таблицы "disk0"; + +=> 00 read= (адрес: 00, операция: чтение, диск 0: пусто, диск 1: блок +сообщения 6C, диск 2: блок избыточности A9, вычисляем блок сообщения +диска 0: A9-6C=3D, собираем сообщение: 3D6C). + +Графика, анимации, счётчики -- ничего этого не нужно, простое +консольное приложение. При использовании базы данных необходимо +отдельно приложить файлы сценариев создания таблиц, в качестве +диалектов допустимы T-SQL и MySQL. + +При наличии вопросов предлагаю провести очные встречи, например, в +среду 08.05.2024, предварительно согласовав их накануне, во вторник +07.05.2024. diff --git a/makefile b/makefile new file mode 100644 index 0000000..830d209 --- /dev/null +++ b/makefile @@ -0,0 +1,54 @@ +all: \ +raid-50-xor-8b-6d \ +raid-50-xor-8b-6d.exe \ +raid-50-xor-12b-6d \ +raid-50-xor-12b-6d.exe \ +raid-50-poly-8b-6d \ +raid-50-poly-8b-6d.exe \ +raid-50-poly-12b-6d \ +raid-50-poly-12b-6d.exe \ +raid-4-xor-12b-7d \ +raid-4-xor-12b-7d.exe \ +raid-4-xor-12b-4d \ +raid-4-xor-12b-4d.exe \ +raid-4-xor-12b-5d \ +raid-4-xor-12b-5d.exe \ +raid-4-xor-14b-4d \ +raid-4-xor-14b-4d.exe \ +raid-4-xor-14b-5d \ +raid-4-xor-14b-5d.exe \ +raid-4-xor-14b-8d \ +raid-4-xor-14b-8d.exe \ +raid-4-xor-10b-3d \ +raid-4-xor-10b-3d.exe \ +raid-4-xor-10b-6d \ +raid-4-xor-10b-6d.exe \ +raid-4-xor-10b-7d \ +raid-4-xor-10b-7d.exe \ +raid-4-xor-8b-8d \ +raid-4-xor-8b-8d.exe \ +raid-4-poly-10b-7d \ +raid-4-poly-10b-7d.exe \ +raid-4-poly-8b-7d \ +raid-4-poly-8b-7d.exe \ +raid-4-poly-8b-6d \ +raid-4-poly-8b-6d.exe \ +raid-5-xor-12b-3d \ +raid-5-xor-12b-3d.exe \ +raid-5-xor-12b-5d \ +raid-5-xor-12b-5d.exe \ +raid-5-xor-12b-6d \ +raid-5-xor-12b-6d.exe \ +raid-5-poly-14b-4d \ +raid-5-poly-14b-4d.exe + +%: src/%.c + gcc -std=gnu99 -ggdb3 -D_GNU_SOURCE -o $@ $< + +%.exe: src/%.c + gcc-cross-x86_64-w64-mingw32-toolchain -- x86_64-w64-mingw32-gcc \ + -std=gnu99 -ggdb3 -D_GNU_SOURCE \ + -L gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/lib/ \ + -I gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/include/ \ + -B gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/lib/ \ + -o $@ $< diff --git a/src/raid-4-poly-10b-7d.c b/src/raid-4-poly-10b-7d.c new file mode 100644 index 0000000..1ca0bf3 --- /dev/null +++ b/src/raid-4-poly-10b-7d.c @@ -0,0 +1,337 @@ +// kira +// M1M2 M3M4 M5M6 M7M8 M9MA 0000 P1P2 +#include +#include +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 7 +#define MESSAGE_SIZE 10 +#define BLOCK_SIZE 2 +#define PADDING_SIZE 2 + +// uint8_t coefficients[DISK_COUNT - 1] = { 1, 3, 5, 7, 11, 13 }; +uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1, 1 }; + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[6]; + snprintf (filename, 6, "disk%d", i); + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR - unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING - found bad disk that is missing: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING - found corrupted disk: %s\n", filename); + bad_disks |= 1 << i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "NOTICE - only 1 bad disk, recomputing it again \n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + + int c = fgetc (disks[k]); + if (c == ' ') { + empty = true; + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + } else { + ungetc (c, disks[k]); + for (int l = 0; l < BLOCK_SIZE; ++l) { + fscanf (disks[k], "%02hhX", &block_bytes[k*BLOCK_SIZE + l]); + } + } + + fgetc (disks[k]); + } + + if (empty) { + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + if (bad_disk == DISK_COUNT - 1) { // lost parity + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] = 0x00; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] += + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]; + } + } else { // lost data + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + l]/coefficients[bad_disk]; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + if (k == bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] -= + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]/coefficients[bad_disk]; + } + } + + // write lost block + for (int l = 0; l < BLOCK_SIZE; ++l) + fprintf (disks[bad_disk], "%02hhX", block_bytes[bad_disk*BLOCK_SIZE + l]); + fprintf (disks[bad_disk], "\n"); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR - more than one bad disks, reinitializing the array with new disks \n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "Initialization RAID 4 with POLY parity on 7 disks. The message size is 10 bytes. \n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + char *line = NULL; + size_t line_size = 0; + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR - address not in set [0x00; 0x40) \n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "ERROR - there is no such command, try entering read or write \n"); + continue; + } break; + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ BLOCK_SIZE]; + uint8_t padding[PADDING_SIZE]; + + while (isspace (*head)) { + head += 1; + if (*head == '\n' || + *head == '\r') { + *head = '\0'; + } + } + if (*head) { + fprintf (stderr, "ERROR - extraneous data after the message: %s", head); + continue; + } + + open_disks (address); + + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("The line is empty \n"); + break; + } ungetc (c, disks[0]); + + // parse out message + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]); + fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]); + fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7], + message[0x8], message[0x9]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR - message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR - expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t padding[PADDING_SIZE] = {0}; + + // compute parity + uint8_t parity[BLOCK_SIZE] = { + coefficients[0]*message[0x0] + + coefficients[1]*message[0x2] + + coefficients[2]*message[0x4] + + coefficients[3]*message[0x6] + + coefficients[4]*message[0x8] + + coefficients[5]*padding[0x0], + + coefficients[0]*message[0x1] + + coefficients[1]*message[0x3] + + coefficients[2]*message[0x5] + + coefficients[3]*message[0x7] + + coefficients[4]*message[0x9] + + coefficients[5]*padding[0x1], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]); + fprintf (disks[5], "%02hhX%02hhX\n", padding[0x0], padding[0x1]); + fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } + free (line); + line = NULL; + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-poly-8b-6d.c b/src/raid-4-poly-8b-6d.c new file mode 100644 index 0000000..a53c293 --- /dev/null +++ b/src/raid-4-poly-8b-6d.c @@ -0,0 +1,304 @@ +// jasmin +// M1M2 M3M4 M5M6 M7M8 0000 P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 8 +#define PARITY_SIZE 2 +#define BLOCK_SIZE 2 +#define PADDING_SIZE 2 + +uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1 }; + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "The file was not opened:( %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "Missing disk:(: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "Corrupted disk: %s\n", filename); + bad_disks |= 1 << i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "There is only 1 faulty disk, I'm recalculating it again \n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + + int c = fgetc (disks[k]); + if (c == ' ') { + empty = true; + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", &block_bytes[k*BLOCK_SIZE + 0], &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + if (bad_disk == DISK_COUNT - 1) { // lost parity + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + for (int l = 0; l < PARITY_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] += + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]; + } + } else { // lost data + block_bytes[bad_disk*BLOCK_SIZE + 0] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + 1]; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + if (k == bad_disk) continue; + for (int l = 0; l < PARITY_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] -= + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]; + } + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "Too many damaged disks, reinitialization of the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "Starting RAID 4 with POLY on 7 disks using 12-byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "The address is not specified [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "Command not specified (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + uint8_t padding[PADDING_SIZE]; + + // parse out message + open_disks (address); + + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("There is no message\n"); + break; + } ungetc (c, disks[0]); + + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]); + fscanf (disks[5], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "Message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "Expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t padding[PADDING_SIZE] = {0}; + + uint8_t parity[PARITY_SIZE] = { + coefficients[0]*message[0x0] + + coefficients[1]*message[0x2] + + coefficients[2]*message[0x4] + + coefficients[3]*message[0x6] + + coefficients[4]*padding[0x0], + + coefficients[0]*message[0x1] + + coefficients[1]*message[0x3] + + coefficients[2]*message[0x5] + + coefficients[3]*message[0x7] + + coefficients[4]*padding[0x1], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]); + fprintf (disks[5], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-poly-8b-7d.c b/src/raid-4-poly-8b-7d.c new file mode 100644 index 0000000..873f7d6 --- /dev/null +++ b/src/raid-4-poly-8b-7d.c @@ -0,0 +1,333 @@ +// yana +// M1M2 M3M4 M5M6 M7M8 0000 0000 P1P2 +#include +#include +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 7 +#define MESSAGE_SIZE 8 +#define BLOCK_SIZE 2 +#define PADDING_SIZE 4 + +// uint8_t coefficients[DISK_COUNT - 1] = { 1, 3, 5, 7, 11, 13 }; +uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1, 1 }; + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[6]; + snprintf (filename, 6, "disk%d", i); + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR - unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING - found bad disk that is missing: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING - found corrupted disk: %s\n", filename); + bad_disks |= 1 << i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "NOTICE - only 1 bad disk, recomputing it again \n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + + int c = fgetc (disks[k]); + if (c == ' ') { + empty = true; + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + } else { + ungetc (c, disks[k]); + for (int l = 0; l < BLOCK_SIZE; ++l) { + fscanf (disks[k], "%02hhX", &block_bytes[k*BLOCK_SIZE + l]); + } + } fgetc (disks[k]); + } + + if (empty) { + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + if (bad_disk == DISK_COUNT - 1) { // lost parity + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] = 0x00; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] += + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]; + } + } else { // lost data + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + l]/coefficients[bad_disk]; + for (int k = 0; k < DISK_COUNT - 1; ++k) { + if (k == bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[bad_disk*BLOCK_SIZE + l] -= + coefficients[k]*block_bytes[k*BLOCK_SIZE + l]/coefficients[bad_disk]; + // printf ("%02hhX\n", coefficients[k]*block_bytes[k*BLOCK_SIZE + 0]/coefficients[bad_disk]); + } + } + + // write lost block + for (int l = 0; l < BLOCK_SIZE; ++l) + fprintf (disks[bad_disk], "%02hhX", block_bytes[bad_disk*BLOCK_SIZE + l]); + fprintf (disks[bad_disk], "\n"); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR - more than one bad disks, reinitializing the array with new disks \n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "Initialization RAID 4 on 7 disks. The message size is 8 bytes. \n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + char *line = NULL; + size_t line_size = 0; + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhu%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR - address not in set [0; 64) \n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "ERROR - there is no such command, try entering read or write \n"); + continue; + } break; + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ BLOCK_SIZE]; + uint8_t padding[PADDING_SIZE]; + + while (isspace (*head)) { + head += 1; + if (*head == '\n' || + *head == '\r') { + *head = '\0'; + } + } + if (*head) { + fprintf (stderr, "ERROR - extraneous data after the message: %s", head); + continue; + } + + open_disks (address); + + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("The line is empty \n"); + break; + } ungetc (c, disks[0]); + + // parse out message + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]); + fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x2], &padding[0x3]); + fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX " + "%02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR - message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR - expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t padding[PADDING_SIZE] = {0}; + + // compute parity + uint8_t parity[BLOCK_SIZE] = { + coefficients[0]*message[0x0] + + coefficients[1]*message[0x2] + + coefficients[2]*message[0x4] + + coefficients[3]*message[0x6] + + coefficients[4]*padding[0x0] + + coefficients[5]*padding[0x2], + + coefficients[0]*message[0x1] + + coefficients[1]*message[0x3] + + coefficients[2]*message[0x5] + + coefficients[3]*message[0x7] + + coefficients[4]*padding[0x1] + + coefficients[5]*padding[0x3], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]); + fprintf (disks[5], "%02hhX%02hhX\n", padding[0x2], padding[0x3]); + fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } + free (line); + line = NULL; + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-10b-3d.c b/src/raid-4-xor-10b-3d.c new file mode 100644 index 0000000..d752c10 --- /dev/null +++ b/src/raid-4-xor-10b-3d.c @@ -0,0 +1,249 @@ +// gdluck +// M1M2M3M4M5 M6M7M8M9MA P1P2P3P4P5 +#include +#include +#include +#include +#include + +#define DISK_COUNT 3 +#define MESSAGE_SIZE 10 +#define BLOCK_SIZE 5 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 11 +#else +#define LINE_SIZE 12 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "error: can't open the file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "warning: a bad disk has been found (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "warning: a bad disk has been found (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "information: there is only 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2], + &block_bytes[k*BLOCK_SIZE + 3], + &block_bytes[k*BLOCK_SIZE + 4]); + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3]; + block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2], + block_bytes[bad_disk*BLOCK_SIZE + 3], + block_bytes[bad_disk*BLOCK_SIZE + 4]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "error: too many damaged disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs ("0000000000\n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "information: initializing RAID 4 on 3 disks with 10 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "error: the address is not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "error: the command is not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ BLOCK_SIZE]; + + // parse out message + open_disks (address); + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x5], &message[0x6], &message[0x7], &message[0x8], &message[0x9]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4]); + close_disks (); + + printf ("%02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], + message[0x5], message[0x6], message[0x7], message[0x8], message[0x9]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + + if (message_size != MESSAGE_SIZE) { + fprintf (stderr, "error: the message is too short, expected %d bytes, received %d\n", + MESSAGE_SIZE, message_size); + continue; + } + + while (isspace (*head)) ++head; + if (*head) { + fprintf (stderr, "error: junk after message: %c...\n", *head); + continue; + } + } + + // compute parity + uint8_t parity[BLOCK_SIZE] = { + message[0x0] ^ message[0x5], + message[0x1] ^ message[0x6], + message[0x2] ^ message[0x7], + message[0x3] ^ message[0x8], + message[0x4] ^ message[0x9], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x5], message[0x6], message[0x7], message[0x8], message[0x9]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-10b-6d.c b/src/raid-4-xor-10b-6d.c new file mode 100644 index 0000000..621625a --- /dev/null +++ b/src/raid-4-xor-10b-6d.c @@ -0,0 +1,279 @@ +// Darya +// M1M2 M3M4 M5M6 M7M8 M9MA P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 10 +#define PARITY_SIZE 2 +#define BLOCK_SIZE 2 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: the file could not be opened: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: an inaccessible disk has been detected %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: a corrupted disk has been detected: %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFORMATION: there is only 1 inaccessible disk, a re-calculation is being performed.\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: there are too many inaccessible disks, the array is being initialized with new disks.\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFORMATION: initialization of RAID 4 on 6 disks with messages of 10 bytes in length. \n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: the address is not in the range [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n"); + continue; + } break; + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("EMPTY!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]); + fscanf (disks[5], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7], + message[0x8], message[0x9]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8], + message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]); + fprintf (disks[5], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-10b-7d.c b/src/raid-4-xor-10b-7d.c new file mode 100644 index 0000000..d8edfe5 --- /dev/null +++ b/src/raid-4-xor-10b-7d.c @@ -0,0 +1,285 @@ +// kira +// M1M2 M3M4 M5M6 M7M8 M9MA 0000 P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 7 +#define MESSAGE_SIZE 10 +#define PARITY_SIZE 2 +#define BLOCK_SIZE 2 +#define PADDING_SIZE 2 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "error: can't open the file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "warning: a bad disk has been found (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "warning: a bad disk has been found (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "information: there is only 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "error: too many damaged disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "information: initializing RAID 4 on 7 disks with 10 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "error: the address is not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "Invalid command, must be on of (read, write)\n"); + continue; + } break; + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + uint8_t padding[PADDING_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("no data at this address!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]); + fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]); + fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7], + message[0x8], message[0x9]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t padding[PADDING_SIZE] = {0}; + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ padding[0x0], + message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ padding[0x1], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]); + fprintf (disks[5], "%02hhX%02hhX\n", padding[0x0], padding[0x1]); + fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-12b-4d.c b/src/raid-4-xor-12b-4d.c new file mode 100644 index 0000000..79f98fe --- /dev/null +++ b/src/raid-4-xor-12b-4d.c @@ -0,0 +1,289 @@ +// Dash +// M1M2M3M4 M5M6M7M8 M9MAMBMC P1P2P3P4 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 4 +#define MESSAGE_SIZE 12 +#define PARITY_SIZE 4 +#define BLOCK_SIZE 4 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 9 +#else +#define LINE_SIZE 10 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR! Try another file \n"); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: MISSING DISK\n"); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: CORRUPTED DISK \n"); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: detected only one faulty disk; recalculating it\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2], + &block_bytes[k*BLOCK_SIZE + 3]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2], + block_bytes[bad_disk*BLOCK_SIZE + 3]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: Exceeding the maximum number of faulty disks.\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: Setting up RAID 4 with 4 disks, each handling 12-byte messages \n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: outside the range [0x00; 0x40) \n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: The provided command is not valid. Please use either 'read' or 'write\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x4], &message[0x5], &message[0x6], &message[0x7]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x8], &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3]); + close_disks (); + + printf ("%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], + message[0x4], message[0x5], message[0x6], message[0x7], + message[0x8], message[0x9], message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character '%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex-digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x4] ^ message[0x8], + message[0x1] ^ message[0x5] ^ message[0x9], + message[0x2] ^ message[0x6] ^ message[0xA], + message[0x3] ^ message[0x7] ^ message[0xB], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", message[0x4], message[0x5], message[0x6], message[0x7]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", message[0x8], message[0x9], message[0xA], message[0xB]); + fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3]); + close_disks (); + } break; + } + free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-12b-5d.c b/src/raid-4-xor-12b-5d.c new file mode 100644 index 0000000..e2716e0 --- /dev/null +++ b/src/raid-4-xor-12b-5d.c @@ -0,0 +1,284 @@ +// Dash +// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 5 +#define MESSAGE_SIZE 12 +#define PARITY_SIZE 3 +#define BLOCK_SIZE 3 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 7 +#else +#define LINE_SIZE 8 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2]); + } fgetc (disks[k]); + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 4 on 4 disks with 12 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("Empty!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + close_disks (); + + printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX %02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], + message[0x3], message[0x4], message[0x5], + message[0x6], message[0x7], message[0x8], + message[0x9], message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9], + message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA], + message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + close_disks (); + } break; + } + free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-12b-7d.c b/src/raid-4-xor-12b-7d.c new file mode 100644 index 0000000..6f2a852 --- /dev/null +++ b/src/raid-4-xor-12b-7d.c @@ -0,0 +1,264 @@ +// Dash +// M1M2 M3M4 M5M6 M7M8 M9MA MBMC P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 7 +#define MESSAGE_SIZE 12 +#define PARITY_SIZE 2 +#define BLOCK_SIZE 2 +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "Error: can't open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "Warning: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { + fprintf (stderr, "Warning: found bad disk (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { + fprintf (stderr, "there is just 1 bad disk, recomputing it\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { + fprintf (disks[bad_disk], " \n"); + continue; + } + + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1]; + } + + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { + fprintf (stderr, "Error: too many bad disks, reinitializing the array with new disks\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "initializing RAID 4 on 7 disks with 12 byte messages\n"); + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + + const char *head; + int assigned; + int scanned; + + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "Error: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "Error: command not in set (use commands write, read)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("There is no data\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]); + fscanf (disks[5], "%02hhX%02hhX\n", &message[0xA], &message[0xB]); + fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7], + message[0x8], message[0x9], + message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ message[0xA], + message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ message[0xB], + }; + + open_disks (address); + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]); + fprintf (disks[5], "%02hhX%02hhX\n", message[0xA], message[0xB]); + fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-14b-4d.c b/src/raid-4-xor-14b-4d.c new file mode 100644 index 0000000..f2f098c --- /dev/null +++ b/src/raid-4-xor-14b-4d.c @@ -0,0 +1,298 @@ +// Dash +// M1M2M3M4M5 M6M7M8M9MA MBMCMDME00 P1P2P3P4P5 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 4 +#define MESSAGE_SIZE 14 +#define PARITY_SIZE 5 +#define BLOCK_SIZE 5 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 11 +#else +#define LINE_SIZE 12 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "mistake: the file could not be opened: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "warning: a faulty disk has been found or the disk is missing: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "warning: a faulty/damaged disk has been detected: %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "message: only one faulty disk has been detected, I am detecting it\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2], + &block_bytes[k*BLOCK_SIZE + 3], + &block_bytes[k*BLOCK_SIZE + 4]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3]; + block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2], + block_bytes[bad_disk*BLOCK_SIZE + 3], + block_bytes[bad_disk*BLOCK_SIZE + 4]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "mistake: there are too many bad disks, we are re-initializing arrays with new disks\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "message: Initializing RAID 4 with XOR and 14 byte messages on 4 disks\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + char *line = NULL; + size_t line_size = 0; + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhX%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "mistake: the address must belong to [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "mistake: only the read and write commands are available\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + uint8_t reserved[1]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message [0x4]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x5], &message[0x6], &message[0x7], &message[0x8], &message [0x9]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0xA], &message[0xB], &message[0xC], &message[0xD], &reserved[0x0]); + fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4]); + close_disks (); + + printf ("%02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], + message[0x5], message[0x6], message[0x7], message[0x8], message[0x9], + message[0xA], message[0xB], message[0xC], message[0xD]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "mistake: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "mistake: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhX%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t reserved[1] = {0}; + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x5] ^ message [0xA], + message[0x1] ^ message[0x6] ^ message [0xB], + message[0x2] ^ message[0x7] ^ message [0xC], + message[0x3] ^ message[0x8] ^ message [0xD], + message[0x4] ^ message[0x9] ^ reserved[0x0], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message [0x4]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x5], message[0x6], message[0x7], message[0x8], message [0x9]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0xA], message[0xB], message[0xC], message[0xD], reserved[0x0]); + fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-14b-5d.c b/src/raid-4-xor-14b-5d.c new file mode 100644 index 0000000..51b8b4a --- /dev/null +++ b/src/raid-4-xor-14b-5d.c @@ -0,0 +1,293 @@ +// Dash +// M1M2M3M4 M5M6M7M8 M9MAMBMC MDME0000 P1P2P3P4 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 5 +#define MESSAGE_SIZE 14 +#define PARITY_SIZE 4 +#define BLOCK_SIZE 4 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 9 +#else +#define LINE_SIZE 10 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: The program could not open the file you are trying to use: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: the system has detected that one of the disks in the array is missing: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: the system has detected that one of the disks in the array is corrupted: %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2], + &block_bytes[k*BLOCK_SIZE + 3]); + } + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2], + block_bytes[bad_disk*BLOCK_SIZE + 3]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: Too many drives in the array have failed and the system is trying to rebuild the array with new drives\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 4 on 5 disks with 14 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + uint8_t reserved[2]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message [0x2], &message [0x3]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x4], &message[0x5], &message [0x6], &message [0x7]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x8], &message[0x9], &message [0xA], &message [0xB]); + fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", &message[0xC], &message[0xD], &reserved[0x0], &reserved[0x1]); + fscanf (disks[4], "%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3]); + close_disks (); + + printf ("%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], + message[0x4], message[0x5], message[0x6], message[0x7], + message[0x8], message[0x9], message[0xA], message[0xB], + message[0xC], message[0xD]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t reserved[2] = {0}; + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x4] ^ message[0x8] ^ message [0xC], + message[0x1] ^ message[0x5] ^ message[0x9] ^ message [0xD], + message[0x2] ^ message[0x6] ^ message[0xA] ^ reserved[0x0], + message[0x3] ^ message[0x7] ^ message[0xB] ^ reserved[0x1], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message [0x2], message [0x3]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", message[0x4], message[0x5], message [0x6], message [0x7]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", message[0x8], message[0x9], message [0xA], message [0xB]); + fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", message[0xC], message[0xD], reserved[0x0], reserved[0x1]); + fprintf (disks[4], "%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-14b-8d.c b/src/raid-4-xor-14b-8d.c new file mode 100644 index 0000000..151c8aa --- /dev/null +++ b/src/raid-4-xor-14b-8d.c @@ -0,0 +1,283 @@ +// Dash +// M1M2 M3M4 M5M6 M7M8 M9MA MBMC MDME P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 8 +#define MESSAGE_SIZE 14 +#define PARITY_SIZE 2 +#define BLOCK_SIZE 2 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "file opening error: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "missing disk is detected: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "damaged disk is detected: %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "only 1 bad disk detected, recalculate it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + fprintf (disks[bad_disk], " \n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "many unsuitable disks are detected, the array is reinitialized with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "RAID 4 initialization on 5 disks with 14-byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "invalid address, use: [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "command does not exist: expected (read/write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("Empty!\n"); + break; + } ungetc (c, disks[0]); + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]); + fscanf (disks[5], "%02hhX%02hhX\n", &message[0xA], &message[0xB]); + fscanf (disks[6], "%02hhX%02hhX\n", &message[0xC], &message[0xD]); + fscanf (disks[7], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7], + message[0x8], message[0x9], + message[0xA], message[0xB], + message[0xC], message[0xD]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ message[0xA] ^ message[0xC], + message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ message[0xB] ^ message[0xD], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]); + fprintf (disks[5], "%02hhX%02hhX\n", message[0xA], message[0xB]); + fprintf (disks[6], "%02hhX%02hhX\n", message[0xC], message[0xD]); + fprintf (disks[7], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-4-xor-8b-8d.c b/src/raid-4-xor-8b-8d.c new file mode 100644 index 0000000..898fb5d --- /dev/null +++ b/src/raid-4-xor-8b-8d.c @@ -0,0 +1,286 @@ +// nguyen +// M1M2 M3M4 M5M6 M7M8 0000 0000 0000 P1P2 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 8 +#define MESSAGE_SIZE 8 +#define BLOCK_SIZE 2 +#define PADDING_SIZE 6 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 5 +#else +#define LINE_SIZE 6 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "file opening error: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "missing disk is detected: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "damaged disk is detected: %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "only 1 bad disk detected, recalculate it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "many unsuitable disks are detected, the array is reinitialized with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "RAID 4 XOR initialization on 8 disks with 8-byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "invalid address, use: [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "command does not exist: expected (read/write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ BLOCK_SIZE]; + uint8_t padding[PADDING_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("EMPTY!\n"); + break; + } ungetc (c, disks[0]); + + fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]); + fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]); + fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]); + fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]); + fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x2], &padding[0x3]); + fscanf (disks[6], "%02hhX%02hhX\n", &padding[0x4], &padding[0x5]); + fscanf (disks[7], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]); + close_disks (); + + printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n", + message[0x0], message[0x1], + message[0x2], message[0x3], + message[0x4], message[0x5], + message[0x6], message[0x7]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + uint8_t padding[PADDING_SIZE] = {0}; + + // compute parity + uint8_t parity[BLOCK_SIZE] = { + message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ padding[0x0] ^ padding[0x2] ^ padding[0x4], + message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ padding[0x1] ^ padding[0x3] ^ padding[0x5], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]); + fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]); + fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]); + fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]); + fprintf (disks[5], "%02hhX%02hhX\n", padding[0x2], padding[0x3]); + fprintf (disks[6], "%02hhX%02hhX\n", padding[0x4], padding[0x5]); + fprintf (disks[7], "%02hhX%02hhX\n", parity [0x0], parity [0x1]); + close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-5-poly-14b-4d.c b/src/raid-5-poly-14b-4d.c new file mode 100644 index 0000000..f272dea --- /dev/null +++ b/src/raid-5-poly-14b-4d.c @@ -0,0 +1,294 @@ +// g, slock +// M1M2M3M4M5 M6M7M8M9MA MBMCMDME00 P1P2P3P4P5 +// M1M2M3M4M5 M6M7M8M9MA P1P2P3P4P5 MBMCMDME00 +// M1M2M3M4M5 P1P2P3P4P5 M6M7M8M9MA MBMCMDME00 +// P1P2P3P4P5 M1M2M3M4M5 M6M7M8M9MA MBMCMDME00 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 4 +#define MESSAGE_SIZE 14 +#define PADDING_SIZE 1 +#define BLOCK_SIZE 5 + +uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, }; + +int shift_table[][DISK_COUNT] = { + { 0, 1, 2, 3, }, + { 0, 1, 3, 2, }, + { 0, 2, 3, 1, }, + { 1, 2, 3, 0, }, +}; + +#define DISK_SIZE 0x40 +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +recompute_bad_disk (int bad_disk) +{ + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE]; + int shift = j % DISK_COUNT; + int logical_bad_disk; + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (shift_table[shift][k] == bad_disk) { + logical_bad_disk = k; + continue; + } + for (int l = 0; l < BLOCK_SIZE; ++l) { + int c = fgetc (disks[shift_table[shift][k]]); + if (c == ' ') { + fgetc (disks[shift_table[shift][k]]); + empty = true; + } else { + ungetc (c, disks[shift_table[shift][k]]); + fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l)]); + } + } fgetc (disks[shift_table[shift][k]]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } else if (logical_bad_disk % DISK_COUNT == DISK_COUNT - 1) { // lost parity + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] = 0x00; + for (int k = 0, c = 0; k < DISK_COUNT; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] += + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l)]; + c += 1; + } + } else { // lost data + for (int l = 0; l < BLOCK_SIZE; ++l) { + block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] = + block_bytes[((DISK_COUNT - 1)*BLOCK_SIZE + l)]; + } + for (int k = 0, c = 0; k < DISK_COUNT - 1; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] -= + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l)]; + c += 1; + } + } + + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l)]); + } fprintf (disks[bad_disk], "\n"); + } +} + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "Ошибка! Невозможно открыть файл: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "Предупреждение! Найден плохой диск: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "Предупреждение!Найден плохой диск: %s\n", filename); + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + bad_disks |= 1 << i; + } else rewind (disks[i]); + } + } + + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { + fprintf (stderr, "Повторный расчет, один диск плохой...\n"); + int bad_disk = CTZ (bad_disks); + recompute_bad_disk (bad_disk); + } else if (bad_disk_count) { + fprintf (stderr, "Ошибка! Повторная инициализация массива с новыми дисками.\n"); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) { + for (int k = 0; k < BLOCK_SIZE; ++k) { + fputs (" ", disks[i]); + } fputs ("\n", disks[i]); + } + } + } + + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "Инициализация RAID 5 с POLY на 4 дисках с 14 байтовым сообщением.\n"); + + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { + assigned = sscanf (head, "%hhu%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "Ошибка! Адрес не входит в границы! [0; 64)\n"); + continue; + } head += scanned; + } + + enum command command; { + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "Ошибка! Не корректная команда! (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE]; + int shift = address % DISK_COUNT; + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("Пусто\n"); + break; + } else ungetc (c, disks[0]); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) { + fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[BLOCK_SIZE*i + j]); + } + } close_disks (); + + for (int i = 0; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) { + if (i == DISK_COUNT - 2 && j + PADDING_SIZE >= BLOCK_SIZE) + continue; + printf ("%02hhX", block_bytes[BLOCK_SIZE*i + j]); + } + printf (" "); + } printf ("\n"); + } break; + case COMMAND_WRITE: { + uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE] = {0}; { // scan message + uint8_t *write_head = block_bytes; + int message_size = 0; + while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + write_head += 1; + if (message_size % ((DISK_COUNT - 1)*BLOCK_SIZE) == 0) + write_head += BLOCK_SIZE; + } + + if (message_size != MESSAGE_SIZE) { + fprintf (stderr, "Ошибка! Сообщение слишком большое, ожидалось %d байт, восстановленно %d\n", + MESSAGE_SIZE, message_size); + continue; + } + + while (isspace(*head)) ++head; + if (*head) { + fprintf (stderr, "Ошибка! Выводится мусор после сообщения: %c...\n", *head); + continue; + } + } + + for (int i = 0; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j]; + } + + int shift = address % DISK_COUNT; + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]); + fprintf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + } break; + } free (line); + } + return EXIT_SUCCESS; +} diff --git a/src/raid-5-xor-12b-3d.c b/src/raid-5-xor-12b-3d.c new file mode 100644 index 0000000..c52c7bc --- /dev/null +++ b/src/raid-5-xor-12b-3d.c @@ -0,0 +1,329 @@ +// North +// M1M2M3M4M5M6 M7M8M9MAMBMC P1P2P3P4P5P6 +// M1M2M3M4M5M6 P1P2P3P4P5P6 M7M8M9MAMBMC +// P1P2P3P4P5P6 M1M2M3M4M5M6 M7M8M9MAMBMC +// M1M2M3M4M5M6 M7M8M9MAMBMC P1P2P3P4P5P6 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 3 +#define MESSAGE_SIZE 12 +#define PARITY_SIZE 6 +#define BLOCK_SIZE 6 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 13 +#else +#define LINE_SIZE 14 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE + PARITY_SIZE]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc (c, disks[k]); + fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX", + &block_bytes[k*BLOCK_SIZE + 0], + &block_bytes[k*BLOCK_SIZE + 1], + &block_bytes[k*BLOCK_SIZE + 2], + &block_bytes[k*BLOCK_SIZE + 3], + &block_bytes[k*BLOCK_SIZE + 4], + &block_bytes[k*BLOCK_SIZE + 5]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 5] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3]; + block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4]; + block_bytes[bad_disk*BLOCK_SIZE + 5] ^= block_bytes[k*BLOCK_SIZE + 5]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2], + block_bytes[bad_disk*BLOCK_SIZE + 3], + block_bytes[bad_disk*BLOCK_SIZE + 4], + block_bytes[bad_disk*BLOCK_SIZE + 5]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 5 on 3 disks with 12 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data stored!\n"); + break; + } ungetc (c, disks[0]); + + switch (address % 3) { + case 0: + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]); + break; + case 1: + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]); + break; + case 2: + fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]); + fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]); + break; + } close_disks (); + + printf ("%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX " + "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5], + message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x6], + message[0x1] ^ message[0x7], + message[0x2] ^ message[0x8], + message[0x3] ^ message[0x9], + message[0x4] ^ message[0xA], + message[0x5] ^ message[0xB], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + switch (address % 3) { + case 0: + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]); + break; + case 1: + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + break; + case 2: + fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]); + fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + break; + } close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-5-xor-12b-5d.c b/src/raid-5-xor-12b-5d.c new file mode 100644 index 0000000..66afa7b --- /dev/null +++ b/src/raid-5-xor-12b-5d.c @@ -0,0 +1,341 @@ +// Жанг +// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 5 +#define MESSAGE_SIZE 12 +#define BLOCK_SIZE 3 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE 7 +#else +#define LINE_SIZE 8 +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE + BLOCK_SIZE]; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc(c, disks[k]); + fscanf(disks[k], "%02hhX%02hhX%02hhX", + &block_bytes[k * BLOCK_SIZE + 0], + &block_bytes[k * BLOCK_SIZE + 1], + &block_bytes[k * BLOCK_SIZE + 2]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 5 XOR on 5 disks with 12 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t parity [ BLOCK_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("EMPTY!\n"); + break; + } ungetc (c, disks[0]); + + switch (address % 5) { + case 0: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + break; + case 1: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + break; + case 2: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + break; + case 3: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + break; + case 4: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + break; + } close_disks (); + + printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX " + "%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5], + message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t parity[BLOCK_SIZE] = { + message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9], + message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA], + message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + switch (address % 5) { + case 0: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + break; + case 1: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + break; + case 2: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + break; + case 3: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + break; + case 4: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + break; + } close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-5-xor-12b-6d.c b/src/raid-5-xor-12b-6d.c new file mode 100644 index 0000000..d10721d --- /dev/null +++ b/src/raid-5-xor-12b-6d.c @@ -0,0 +1,380 @@ +// M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000 P1P2P3 +// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3 000000 +// M1M2M3 M4M5M6 M7M8M9 P1P2P3 MAMBMC 000000 +// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC 000000 +// M1M2M3 P1P2P3 M4M5M6 M7M8M9 MAMBMC 000000 +// P1P2P3 M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000 +// M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000 P1P2P3 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 12 +#define BLOCK_SIZE 3 +#define PADDING_SIZE 3 +#define PARITY_SIZE 3 + +#define DISK_SIZE 0x40 + +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + bad_disks |= 1 << i; + } rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + PARITY_SIZE] = {0}; + + // read blocks from good disks + bool empty = false; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + int c = fgetc (disks[k]); + if (c == ' ') { + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + + fgetc (disks[k]); + fgetc (disks[k]); + empty = true; + } else { + ungetc(c, disks[k]); + fscanf(disks[k], "%02hhX%02hhX%02hhX", + &block_bytes[k * BLOCK_SIZE + 0], + &block_bytes[k * BLOCK_SIZE + 1], + &block_bytes[k * BLOCK_SIZE + 2]); + } fgetc (disks[k]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00; + block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00; + for (int k = 0; k < DISK_COUNT; ++k) { + if (k == bad_disk) continue; + block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0]; + block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1]; + block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2]; + } + + // write lost block + fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n", + block_bytes[bad_disk*BLOCK_SIZE + 0], + block_bytes[bad_disk*BLOCK_SIZE + 1], + block_bytes[bad_disk*BLOCK_SIZE + 2]); + } + } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) + fputs (" \n", disks[i]); + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 5 XOR on 5 disks with 12 byte messages...\n"); + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t message[MESSAGE_SIZE]; + uint8_t padding[PADDING_SIZE]; + uint8_t parity [ PARITY_SIZE]; + + // parse out message + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("EMPTY!\n"); + break; + } ungetc (c, disks[0]); + + switch (address % DISK_COUNT) { + case 0: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + break; + case 1: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + break; + case 2: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + break; + case 3: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + break; + case 4: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + break; + case 5: + fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]); + fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]); + fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]); + fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]); + fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]); + fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]); + break; + } close_disks (); + + printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX " + "%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n", + message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5], + message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]); + } break; + case COMMAND_WRITE: { + uint8_t message[MESSAGE_SIZE] = {0}; { // scan message + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + } + } + + // compute parity + uint8_t padding[PADDING_SIZE] = { + 0x00, + 0x00, + 0x00, + }; + uint8_t parity[PARITY_SIZE] = { + message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9], + message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA], + message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB], + }; + + // write blocks + open_disks (address); // open disk files, ensuring their integrity + switch (address % DISK_COUNT) { + case 0: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + break; + case 1: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + break; + case 2: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + break; + case 3: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + break; + case 4: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + break; + case 5: + fprintf (disks[0], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]); + fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]); + fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]); + fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]); + fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]); + fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]); + break; + } close_disks (); + } break; + } free (line); + } + + return EXIT_SUCCESS; +} diff --git a/src/raid-50-poly-12b-6d.c b/src/raid-50-poly-12b-6d.c new file mode 100644 index 0000000..3550688 --- /dev/null +++ b/src/raid-50-poly-12b-6d.c @@ -0,0 +1,312 @@ +// Aksel +// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6 +// M1M2M3 P1P2P3 M4M5M6 M7M8M9 P4P5P6 MAMBMC +// P1P2P3 M1M2M3 M4M5M6 P4P5P6 M7M8M9 MAMBMC +// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 12 +#define BLOCK_SIZE 3 + +uint8_t coefficients[DISK_COUNT - 2] = { 1, 1, 1, 1, }; + +// TODO(cmmm): generate +int shift_table[][DISK_COUNT] = { + { 0, 1, 2, 3, 4, 5 }, + { 0, 2, 1, 3, 5, 4 }, + { 1, 2, 0, 4, 5, 3 }, +}; + +#define DISK_SIZE 0x40 +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +recompute_bad_disk (int bad_disk) +{ + int cluster = bad_disk/(DISK_COUNT/2); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = j % (DISK_COUNT/2); + int logical_bad_disk; + bool empty = false; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (shift_table[shift][k] == bad_disk) { + logical_bad_disk = k; + continue; + } + for (int l = 0; l < BLOCK_SIZE; ++l) { + int c = fgetc (disks[shift_table[shift][k]]); + if (c == ' ') { + fgetc (disks[shift_table[shift][k]]); + empty = true; + } else { + ungetc (c, disks[shift_table[shift][k]]); + fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } + } fgetc (disks[shift_table[shift][k]]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } else if (logical_bad_disk % (DISK_COUNT/2) == DISK_COUNT/2 - 1) { // lost parity + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00; + for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] += + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + c += 1; + } + } else { + for (int l = 0; l < BLOCK_SIZE; ++l) { + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = + block_bytes[((DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1)*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + } + for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] -= + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + c += 1; + } + } + + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } fprintf (disks[bad_disk], "\n"); + } +} + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "Ошибка! Невозможно открыть файл: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "Предупреждение! Найден плохой диск: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "Предупреждение!Найден плохой диск: %s\n", filename); + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + bad_disks |= 1 << i; + } else rewind (disks[i]); + } + } + + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { + fprintf (stderr, "Повторный расчет, один диск плохой...\n"); + int bad_disk = CTZ (bad_disks); + recompute_bad_disk (bad_disk); + } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) { + fprintf (stderr, "2 плохих диска в разделяющемся кластере, повторный расчет.\n"); + int bad_disk0 = CTZ (bad_disks); + int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0)); + recompute_bad_disk (bad_disk0); + recompute_bad_disk (bad_disk1); + } else if (bad_disk_count) { + fprintf (stderr, "Ошибка! Повторная инициализация массива с новыми дисками.\n"); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) { + for (int k = 0; k < BLOCK_SIZE; ++k) { + fputs (" ", disks[i]); + } fputs ("\n", disks[i]); + } + } + } + + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "Инициализация RAID 50 с POLY на 6 дисках с 12 байтовым сообщением.\n"); + + + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { + assigned = sscanf (head, "%hhu%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "Ошибка! Адрес не входит в границы! [0; 64)\n"); + continue; + } head += scanned; + } + + enum command command; { + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "Ошибка! Не корректная команда! (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = address % (DISK_COUNT/2); + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("Пусто\n"); + break; + } else ungetc (c, disks[0]); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) { + fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[BLOCK_SIZE*i + j]); + } + } close_disks (); + + for (int i = 0; i < DISK_COUNT; ++i) { + if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue; + for (int j = 0; j < BLOCK_SIZE; ++j) + printf ("%02hhX", block_bytes[BLOCK_SIZE*i + j]); + printf (" "); + } printf ("\n"); + } break; + case COMMAND_WRITE: { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message + uint8_t *write_head = block_bytes; + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "Ошибка! В сообщении запрещён символ `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "Ошибка! Ожидалось %d hex цифр для сообщения, получилось %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + write_head += 1; + if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0) + write_head += BLOCK_SIZE; + } + } + + int shift = address % (DISK_COUNT/2); + + for (int i = 0; i < DISK_COUNT/2 - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j]; + } + + for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i - 1]*block_bytes[i*BLOCK_SIZE + j]; + } + + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]); + fprintf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + } break; + } free (line); + } + return EXIT_SUCCESS; +} diff --git a/src/raid-50-poly-8b-6d.c b/src/raid-50-poly-8b-6d.c new file mode 100644 index 0000000..351ebbb --- /dev/null +++ b/src/raid-50-poly-8b-6d.c @@ -0,0 +1,305 @@ +// feld marshal +// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4 +// M1M2 P1P2 M3M4 M5M6 P3P4 M7M8 +// P1P2 M1M2 M3M4 P3P4 M5M6 M7M8 +// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4 +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 8 +#define BLOCK_SIZE 2 + +uint8_t coefficients[DISK_COUNT - 2] = { 1, 1, 1, 1, }; + +// TODO(cmmm): generate +int shift_table[][DISK_COUNT] = { + { 0, 1, 2, 3, 4, 5 }, + { 0, 2, 1, 3, 5, 4 }, + { 1, 2, 0, 4, 5, 3 }, +}; + +#define DISK_SIZE 0x40 +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +recompute_bad_disk (int bad_disk) +{ + int cluster = bad_disk/(DISK_COUNT/2); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = j % (DISK_COUNT/2); + + // read blocks from good disks + int logical_bad_disk; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (shift_table[shift][k] == bad_disk) { + logical_bad_disk = k; + continue; + } + for (int l = 0; l < BLOCK_SIZE; ++l) { + fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } fscanf (disks[shift_table[shift][k]], "\n"); + } + + // compute lost block + if (logical_bad_disk % (DISK_COUNT/2) == DISK_COUNT/2 - 1) { // lost parity + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00; + for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] += + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + c += 1; + } + } else { // lost data + for (int l = 0; l < BLOCK_SIZE; ++l) { + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = + block_bytes[((DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1)*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + } + for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] -= + coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + c += 1; + } + } + + // write lost block + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } fprintf (disks[bad_disk], "\n"); + } +} + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk: %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk: %s\n", filename); + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + bad_disks |= 1 << i; + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + recompute_bad_disk (bad_disk); + } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) { + fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n"); + int bad_disk0 = CTZ (bad_disks); + int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0)); + recompute_bad_disk (bad_disk0); + recompute_bad_disk (bad_disk1); + } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) { + for (int k = 0; k < BLOCK_SIZE; ++k) { + fputs ("00", disks[i]); + } fputs ("\n", disks[i]); + } + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 50 on 6 disks with 8 byte messages...\n"); + + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + const char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command; { // scan command + char command_buffer[6] = {0}; + assigned = sscanf (head, "%5s %n", command_buffer, &scanned); + if (assigned != 1 || + (!strncmp (command_buffer, "read", 4) && + !strncmp (command_buffer, "write", 5))) { + fprintf(stderr, "ERROR: command not in set (read; write)\n"); + continue; + } head += scanned; + command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE; + } + + switch (command) { + case COMMAND_READ: { + // parse out message + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = address % (DISK_COUNT/2); + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[2*i + j]); + fscanf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + + for (int i = 0; i < DISK_COUNT; ++i) { + if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue; + for (int j = 0; j < BLOCK_SIZE; ++j) + printf ("%02hhX", block_bytes[2*i + j]); + printf (" "); + } printf ("\n"); + } break; + case COMMAND_WRITE: { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message + uint8_t *write_head = block_bytes; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + int message_size = 0; + while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + write_head += 1; + if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0) + write_head += BLOCK_SIZE; + } + } + + int shift = address % (DISK_COUNT/2); + + // compute parity of first cluster + for (int i = 0; i < DISK_COUNT/2 - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j]; + } + + // compute parity of second cluster + for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i - 1]*block_bytes[i*BLOCK_SIZE + j]; + } + + // write needed blocks in each file in the necessary order + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]); + fprintf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + } break; + } free (line); + } + return EXIT_SUCCESS; +} diff --git a/src/raid-50-xor-12b-6d.c b/src/raid-50-xor-12b-6d.c new file mode 100644 index 0000000..0aac492 --- /dev/null +++ b/src/raid-50-xor-12b-6d.c @@ -0,0 +1,328 @@ +// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6 +// M1M2M3 P1P2P3 M4M5M6 M7M8M9 P4P5P6 MAMBMC +// P1P2P3 M1M2M3 M4M5M6 P4P5P6 M7M8M9 MAMBMC +// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 12 +#define BLOCK_SIZE 3 + +// TODO(cmmm): generate +int shift_table[][DISK_COUNT] = { + { 0, 1, 2, 3, 4, 5 }, + { 0, 2, 1, 3, 5, 4 }, + { 1, 2, 0, 4, 5, 3 }, +}; + +#define DISK_SIZE 0x40 +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +recompute_bad_disk (int bad_disk) +{ + int cluster = bad_disk/(DISK_COUNT/2); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = j % (DISK_COUNT/2); + + // read blocks from good disks + int logical_bad_disk; + bool empty = false; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (shift_table[shift][k] == bad_disk) { + logical_bad_disk = k; + continue; + } + for (int l = 0; l < BLOCK_SIZE; ++l) { + int c = fgetc (disks[shift_table[shift][k]]); + if (c == ' ') { + fgetc (disks[shift_table[shift][k]]); + empty = true; + } else { + ungetc (c, disks[shift_table[shift][k]]); + fscanf (disks[shift_table[shift][k]], "%02hhX", + &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } + } fgetc (disks[shift_table[shift][k]]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] ^= + block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + } + + // write lost block + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], "%02hhX", + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } fprintf (disks[bad_disk], "\n"); + } +} + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + bad_disks |= 1 << i; + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + recompute_bad_disk (bad_disk); + } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) { + fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n"); + int bad_disk0 = CTZ (bad_disks); + int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0)); + recompute_bad_disk (bad_disk0); + recompute_bad_disk (bad_disk1); + } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) { + for (int k = 0; k < BLOCK_SIZE; ++k) { + fputs (" ", disks[i]); + } fputs ("\n", disks[i]); + } + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...\n"); + + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE || scanned > 2) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command = COMMAND_NONE; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n"); + continue; + } break; + case COMMAND_READ: { + // parse out message + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = address % (DISK_COUNT/2); + + while (isspace (*head)) { + head += 1; + if (*head == '\n' || + *head == '\r') { + *head = '\0'; + } + } if (*head) { + fprintf (stderr, "ERROR: trailing junk after command: %s", head); + continue; + } + + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data stored!\n"); + break; + } ungetc (c, disks[0]); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[i*BLOCK_SIZE + j]); + fscanf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + + for (int i = 0; i < DISK_COUNT; ++i) { + if ((i + 1) % (DISK_COUNT/2) == 0) continue; + for (int j = 0; j < BLOCK_SIZE; ++j) + printf ("%02hhX", block_bytes[i*BLOCK_SIZE + j]); + } printf ("\n"); + } break; + case COMMAND_WRITE: { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message + uint8_t *write_head = block_bytes; + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + write_head += 1; + if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0) + write_head += BLOCK_SIZE; + } + } + + int shift = address % (DISK_COUNT/2); + + // compute parity of first cluster + for (int i = 0; i < DISK_COUNT/2 - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j]; + } + + // compute parity of second cluster + for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j]; + } + + // write needed blocks in each file in the necessary order + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]); + fprintf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + } break; + } free (line); + } return EXIT_SUCCESS; +} diff --git a/src/raid-50-xor-8b-6d.c b/src/raid-50-xor-8b-6d.c new file mode 100644 index 0000000..486e787 --- /dev/null +++ b/src/raid-50-xor-8b-6d.c @@ -0,0 +1,328 @@ +// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4 +// M1M2 P1P2 M3M4 M5M6 P3P4 M7M8 +// P1P2 M1M2 M3M4 P3P4 M5M6 M7M8 +// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4 +#include +#include +#include +#include +#include +#include + +#define DISK_COUNT 6 +#define MESSAGE_SIZE 8 +#define BLOCK_SIZE 2 + +// TODO(cmmm): generate +int shift_table[][DISK_COUNT] = { + { 0, 1, 2, 3, 4, 5 }, + { 0, 2, 1, 3, 5, 4 }, + { 1, 2, 0, 4, 5, 3 }, +}; + +#define DISK_SIZE 0x40 +#define POPCOUNT __builtin_popcount +#define CTZ __builtin_ctz + +#ifndef WIN32 +#define LINE_SIZE (2*BLOCK_SIZE + 1) +#else +#define LINE_SIZE (2*BLOCK_SIZE + 2) +static ssize_t +getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) { + register char c; + register char *cs = NULL; + register int length = 0; + while ((c = getc (stream)) != EOF) { + cs = (char *) realloc (cs, ++length + 1); + if ((*(cs + length - 1) = c) == '\n') { + *(cs + length) = '\0'; + break; + } + } + + // return the allocated memory if lineptr is null + if ((*lineptr) == NULL) { + *lineptr = cs; + } else { + // check if enough memory is allocated + if ((length + 1) < *n) + *lineptr = (char *) realloc (*lineptr, length + 1); + memcpy (*lineptr, cs, length); + free (cs); + } + + return (ssize_t) (*n = strlen (*lineptr)); +} +#endif + +enum command { + COMMAND_NONE, + COMMAND_WRITE, + COMMAND_READ, +}; + +FILE *disks[DISK_COUNT]; + +static void +recompute_bad_disk (int bad_disk) +{ + int cluster = bad_disk/(DISK_COUNT/2); + + for (int j = 0; j < DISK_SIZE; ++j) { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = j % (DISK_COUNT/2); + + // read blocks from good disks + int logical_bad_disk; + bool empty = false; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (shift_table[shift][k] == bad_disk) { + logical_bad_disk = k; + continue; + } + for (int l = 0; l < BLOCK_SIZE; ++l) { + int c = fgetc (disks[shift_table[shift][k]]); + if (c == ' ') { + fgetc (disks[shift_table[shift][k]]); + empty = true; + } else { + ungetc (c, disks[shift_table[shift][k]]); + fscanf (disks[shift_table[shift][k]], "%02hhX", + &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } + } fgetc (disks[shift_table[shift][k]]); + } + + if (empty) { // address empty + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], " "); + } fprintf (disks[bad_disk], "\n"); + continue; + } + + // compute lost block + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00; + for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) { + if (k == logical_bad_disk) continue; + for (int l = 0; l < BLOCK_SIZE; ++l) + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] ^= + block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]; + } + + // write lost block + for (int l = 0; l < BLOCK_SIZE; ++l) { + fprintf (disks[bad_disk], "%02hhX", + block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]); + } fprintf (disks[bad_disk], "\n"); + } +} + +static void +open_disks (uint8_t address) +{ + uint16_t bad_disks = 0; + for (int i = 0; i < DISK_COUNT; ++i) { + char filename[] = "disk0"; + filename[strlen (filename) - 1] += i; + disks[i] = fopen (filename, "r+"); + if (!disks[i]) { // disk file was deleted + disks[i] = fopen (filename, "w+"); + if (!disks[i]) { + fprintf (stderr, "ERROR: unable to open file: %s\n", filename); + exit (EXIT_FAILURE); + } + + fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename); + bad_disks |= 1 << i; + } else { // disk file wasn't deleted + fseek (disks[i], 0, SEEK_END); + if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format + fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename); + fclose (disks[i]); + disks[i] = fopen (filename, "w+"); + bad_disks |= 1 << i; + } else rewind (disks[i]); + } + } + + // there were bad disks + int bad_disk_count = POPCOUNT (bad_disks); + if (bad_disk_count == 1) { // recompute lost disk + fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n"); + int bad_disk = CTZ (bad_disks); + recompute_bad_disk (bad_disk); + } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) { + fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n"); + int bad_disk0 = CTZ (bad_disks); + int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0)); + recompute_bad_disk (bad_disk0); + recompute_bad_disk (bad_disk1); + } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost + fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n"); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < DISK_SIZE; ++j) { + for (int k = 0; k < BLOCK_SIZE; ++k) { + fputs (" ", disks[i]); + } fputs ("\n", disks[i]); + } + } + } + + // position head for writing/reading message + for (int i = 0; i < DISK_COUNT; ++i) + fseek (disks[i], address*LINE_SIZE, SEEK_SET); +} + +static void +close_disks (void) +{ + for (int i = 0; i < DISK_COUNT; ++i) + fclose (disks[i]); +} + +int +main (void) +{ + fprintf (stderr, "INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...\n"); + + // check disk integrity on startup + open_disks (0); + close_disks ( ); + + for (;;) { + char *line = NULL; + size_t line_size = 0; + char *head; + int assigned; + int scanned; + + // read whole line + printf ("> "); + scanned = getline (&line, &line_size, stdin); + if (scanned == -1) + exit (EXIT_SUCCESS); + else if (scanned == 1) + continue; + head = line; + + uint8_t address; { // scan address + assigned = sscanf (head, "%hhx%n", &address, &scanned); + if (assigned != 1 || address >= DISK_SIZE || scanned > 2) { + fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n"); + continue; + } head += scanned; + } + + enum command command = COMMAND_NONE; { // scan command + while (*head == ' ') head += 1; + if (!strncmp (head, "read", 4)) { + head += 4; + command = COMMAND_READ; + } else if (!strncmp (head, "write", 5)) { + head += 5; + command = COMMAND_WRITE; + } + if (!isspace(*head)) + command = COMMAND_NONE; + } + + switch (command) { + case COMMAND_NONE: { + fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n"); + continue; + } break; + case COMMAND_READ: { + // parse out message + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE]; + int shift = address % (DISK_COUNT/2); + + while (isspace (*head)) { + head += 1; + if (*head == '\n' || + *head == '\r') { + *head = '\0'; + } + } if (*head) { + fprintf (stderr, "ERROR: trailing junk after command: %s", head); + continue; + } + + open_disks (address); + int c = fgetc (disks[0]); + if (c == ' ') { + close_disks (); + printf ("No data stored!\n"); + break; + } ungetc (c, disks[0]); + + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[2*i + j]); + fscanf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + + for (int i = 0; i < DISK_COUNT; ++i) { + if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue; + for (int j = 0; j < BLOCK_SIZE; ++j) + printf ("%02hhX", block_bytes[2*i + j]); + } printf ("\n"); + } break; + case COMMAND_WRITE: { + uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message + uint8_t *write_head = block_bytes; + int message_size = 0; + + while (*head == ' ' || + *head == '\t') ++head; + const char *invalid = NULL; + size_t len = 0; + for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) { + if (!strchr ("0123456789abcdefABCDEF", *c)) { + invalid = c; + break; + } len += 1; + } if (invalid) { + fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid); + break; + } if (len != 2*MESSAGE_SIZE) { + fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len); + break; + } + + while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 && + message_size < MESSAGE_SIZE) { + head += scanned; + message_size += 1; + write_head += 1; + if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0) + write_head += BLOCK_SIZE; + } + } + + int shift = address % (DISK_COUNT/2); + + // compute parity of first cluster + for (int i = 0; i < DISK_COUNT/2 - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j]; + } + + // compute parity of second cluster + for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j]; + } + + // write needed blocks in each file in the necessary order + open_disks (address); + for (int i = 0; i < DISK_COUNT; ++i) { + for (int j = 0; j < BLOCK_SIZE; ++j) + fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]); + fprintf (disks[shift_table[shift][i]], "\n"); + } close_disks (); + } break; + } free (line); + } return EXIT_SUCCESS; +} -- cgit v1.3.1