aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore2
-rw-r--r--README.org359
-rw-r--r--UNLICENSE24
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty23
-rw-r--r--doc/gost/gost-7-32-counters.sty37
-rw-r--r--doc/gost/gost-7-32-headings.sty98
-rw-r--r--doc/gost/gost-7-32-lists.sty15
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/ox-init.el32
-rw-r--r--doc/raid0.pngbin0 -> 19955 bytes
-rw-r--r--doc/raid5.pngbin0 -> 25288 bytes
-rw-r--r--doc/raid50.pngbin0 -> 11928 bytes
-rw-r--r--doc/report.org269
-rw-r--r--doc/setup.org40
-rw-r--r--doc/spbstu-report.cls73
-rw-r--r--doc/task.org137
-rw-r--r--makefile54
-rw-r--r--src/raid-4-poly-10b-7d.c337
-rw-r--r--src/raid-4-poly-8b-6d.c304
-rw-r--r--src/raid-4-poly-8b-7d.c333
-rw-r--r--src/raid-4-xor-10b-3d.c249
-rw-r--r--src/raid-4-xor-10b-6d.c279
-rw-r--r--src/raid-4-xor-10b-7d.c285
-rw-r--r--src/raid-4-xor-12b-4d.c289
-rw-r--r--src/raid-4-xor-12b-5d.c284
-rw-r--r--src/raid-4-xor-12b-7d.c264
-rw-r--r--src/raid-4-xor-14b-4d.c298
-rw-r--r--src/raid-4-xor-14b-5d.c293
-rw-r--r--src/raid-4-xor-14b-8d.c283
-rw-r--r--src/raid-4-xor-8b-8d.c286
-rw-r--r--src/raid-5-poly-14b-4d.c294
-rw-r--r--src/raid-5-xor-12b-3d.c329
-rw-r--r--src/raid-5-xor-12b-5d.c341
-rw-r--r--src/raid-5-xor-12b-6d.c380
-rw-r--r--src/raid-50-poly-12b-6d.c312
-rw-r--r--src/raid-50-poly-8b-6d.c305
-rw-r--r--src/raid-50-xor-12b-6d.c328
-rw-r--r--src/raid-50-xor-8b-6d.c328
41 files changed, 7746 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..23f832b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
1*.html
2*.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 @@
1#+title: RAID 50 simulation
2#+subtitle: with message size of 8 bytes and 6 disks
3#+date: 2024H1
4
5* Task
6:PROPERTIES:
7:CUSTOM_ID: task
8:END:
9#+begin_note
10This is a machine translation.[fn:1]
11#+end_note
12
13Each student individually needs to develop an application that
14simulates the operation of a RAID array at levels 6 and 50 (5+0) with
15a specified size of the original message and the number of disks. The
16application performs read and write operations on the message at the
17specified address (a linear array of strings with indices from 0 to
1863). A table with task options is attached to the email, where one "+"
19symbol indicates one available option. Distribute them among
20yourselves in such a way that each person gets their own variant. The
21work must be completed in the form of an executable application file,
22a report, and an archive with the source code.
23
24The parameters for the task variants are from the table.
251) Array type: RAID 6 or RAID 50 (5+0). Information about these levels
26 in a simple and accessible form with explanatory images:
27 https://en.wikipedia.org/wiki/Standard_RAID_levels. RAID 6 Arrays
28 must restore data in case of failure of any two disks, RAID 50
29 arrays -- in case of failure of any one disk.
302) Redundancy calculation: XOR and/or POLY. XOR -- calculating the
31 value of a redundancy block using the "exclude or" operation for a
32 pair of blocks. In case of a larger and/or an odd number of blocks
33 messages can use a hierarchical XOR calculation., adding a fixed
34 service value (for example, a set of "1" according to the block
35 size) and any other techniques you choose discretion. POLY --
36 calculating the value of the redundancy block with using polynomial
37 expressions (for example, a pair of polynomials the first level is
38 A-B+C-D+E=X and A+2B-3C+4D-5E=Y for a RAID 6 array of seven disks,
39 where A..E are the blocks that make up the original message, X and
40 Y are redundancy blocks).
413) Message size: 8, 10, 12, 14 bytes. This is the size of the
42 original (whole) message to be written to the array and read from
43 the array. Message This size is specified by the user when
44 selecting a write operation, and the same size messages are given
45 to the user when selecting a read operation.
464) Number of disks: 3, 4, 5, 6, 7, 8, 10. This is the total number
47 disks in the array for writing message blocks and redundancy
48 blocks.
49
50Comments on the table.
511) You can, if you wish, choose a more complex RAID array
52 configuration, such as RAID 60 (6+0), if you’re interested, but
53 this must be согласован with me.
542) You can, if you wish, choose any other method of calculating
55 redundancy blocks, if you’re interested, but this must be
56 согласован. with me. You also need to be sure that the chosen
57 method allows you to fully restore the original message in case of
58 loss. any two blocks for RAID 6/60 (any message block + any block
59 redundancy, any two message blocks, two redundancy blocks). The
60 hierarchical calculation of XOR is demonstrated by the following
61 example. Let's give a RAID 5 array on five disks and the message
62 12345678(hex). Then the message blocks will be: 12, 34, 56, 78. We
63 count the XOR separately for the first pair of blocks: 12 XOR 34 =
64 26, separately for the second pair blocks: 56 XOR 78 = 2E, then
65 count the XOR for these two results: 26 XOR 2E = 08 -- we will
66 write this value in the block. redundancy. Now, if we lose any
67 message block (for example, 34), we will restore it. First, let's
68 check which original pair the block is missing from and calculate
69 the XOR of the remaining pair: 56 XOR 78 = 2E, now we count the XOR
70 of our redundancy block with the resulting result: 08 XOR 2E = 26
71 -- got the XOR of the first pair of values, now we find the lost
72 block from this value and the saved one. message block: 26 XOR 12
73 = 34 — the message block is restored, we can fully reconstruct the
74 original message. Adding a fixed service value can help, for
75 example, if the number of blocks is odd. Let’s say we have a RAID
76 5 array on four disks and the message is 123456(hex). Then the
77 message blocks will be: 12, 34, 56. You can add a service value,
78 for example, FF as of a fixed “virtual” block and completely repeat
79 the algorithm described above. Or you can do it differently:
80 calculate the XOR for the first pair of message blocks, then
81 calculate the XOR of the resulting value and the remaining message
82 block. That is: 12 XOR 34 = 26, 26 XOR 56 = 70 — this value will be
83 written to the redundancy block.
843) After analyzing the message size and the number of disks, you can
85 see that the message is not always "divided" into an integer number
86 of blocks. This should not bother you, because you can always
87 adopt rules according to which you will supplement the message
88 block with seniors. zeros so that all blocks have the same size.
89 For example, let given a RAID 6 array on five disks and a 5 byte
90 message (Martin: If we take ASCII, not hex...): 12345(hex). Given
91 that two disks will be used for redundancy when writing the
92 message, we need to divide the original message into three blocks:
93 12, 34, 5. The last block can be supplemented with a leading zero
94 to get the value 05, which will be written to the disk.
954) Do not forget that the parity in RAID 5 and 6 arrays, as well as in
96 their derivatives, is distributed. That is, when accessing each
97 next "row", the blocks of messages and redundancy will be They can
98 be arranged in different order. You can use a simple technique:
99 create a placement matrix and select a row of the matrix on based
100 on dividing the address modulo the number of disks. For example,
101 let there will be a RAID 5 array on four disks. For him, the
102 matrix of block placements can be as follows (here BS is a message
103 block, BI is a block redundancy).
104
105Your application can use either of two approaches as disks: text files
106(one disk is one file, one message block -- one line of the file) or a
107database (one disk - one table, one message block - one table entry)
108at your discretion. Files and tables must be named
109
110* Documentation
111:PROPERTIES:
112:CUSTOM_ID: documentation
113:END:
114The exported report can be found at [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/latest/report.pdf][this link]].
115
116* Showcase
117:PROPERTIES:
118:CUSTOM_ID: showcase
119:END:
120A sample session of working with the program is provided; lines with
121comments start with =#=.[fn:2]
122#+begin_src text
123# Program start, there are no disk files
124INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...
125WARNING: found bad disk (missing): disk0
126WARNING: found bad disk (missing): disk1
127WARNING: found bad disk (missing): disk2
128WARNING: found bad disk (missing): disk3
129WARNING: found bad disk (missing): disk4
130WARNING: found bad disk (missing): disk5
131ERROR: too many bad disks, reinitializing the array with new disks...
132# At this point, the disk files already exist.
133> 0 asdf
134ERROR: invalid command, must be on of (read, write)
135> 0 read asdf
136ERROR: trailing junk after command: asdf
137> 0 write
138ERROR: expected 16 hex digits for message, received 0
139> 0 write 112233445566778
140ERROR: expected 16 hex digits for message, received 15
141> 0 write 11223344556677888
142ERROR: expected 16 hex digits for message, received 17
143> 0 write asdf
144ERROR: message contains invalid character `s'
145> 0 write -10
146ERROR: message contains invalid character `-'
147>
148> 0 write 1122334455667788
149> 1 write 1122334455667788
150> 2 write 1122334455667788
151> 0 read
1521122334455667788
153> 1 read
1541122334455667788
155> 2 read
1561122334455667788
157>
158# Manualy damaged the disk2 file
159> 0 read
160WARNING: found bad disk (corrupted): disk2
161INFO: there is just 1 bad disk, recomputing it...
1621122334455667788
163>
164# Manualy damaged the disk4 file
165> 1 read
166WARNING: found bad disk (corrupted): disk4
167INFO: there is just 1 bad disk, recomputing it...
1681122334455667788
169>
170# Manualy damaged disk0 and disk5 files => we can recover
171> 2 read
172WARNING: found bad disk (corrupted): disk0
173WARNING: found bad disk (corrupted): disk5
174INFO: there are 2 bad disk in separate clusters, recomputing them...
1751122334455667788
176>
177# Manualy damaged disk0 and disk1 files => we can't recover
178> 0 read
179WARNING: found bad disk (corrupted): disk0
180WARNING: found bad disk (corrupted): disk1
181ERROR: too many bad disks, reinitializing the array with new disks...
182No data stored!
183>
184# No message has been recorded at address 0x1F yet
185> 1F read
186No data stored!
187>
188# Attempt to access an address outside the allowed range
189> 40 read
190ERROR: address not in set [0x00; 0x40)
191> AA read
192ERROR: address not in set [0x00; 0x40)
193> 100 read
194ERROR: address not in set [0x00; 0x40)
195> interrupt
196#+end_src
197
198* Releases
199- [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/latest/][latest]]
200- [[https://git.michalec.dev/files/uni/term-04/supercomp-arch/lab/releases/][all]]
201
202* Unlicense
203:PROPERTIES:
204:CUSTOM_ID: unlicense
205:END:
206#+include: UNLICENSE verse
207
208* Footnotes
209:PROPERTIES:
210:CUSTOM_ID: footnotes
211:END:
212[fn:1] Original text:
213#+HTML: <i>
214#+begin_quote
215Каждому студенту индивидуально необходимо разработать приложение,
216моделирующее работу RAID-массива уровней 6 и 50 (5+0) с заданными
217размером исходного сообщения и числом дисков. Приложение выполняет
218операции чтения и записи сообщения по указываемому адресу (линейный
219массив строк с индексами от 0 до 63). К письму приложена таблица с
220вариантами заданий, где один символ "+" обозначает один доступный для
221выбора вариант. Распределите их между собой таким образом, чтобы
222каждому достался свой вариант. Работа должна быть выполнена в виде
223исполняемого файла приложения, отчёта, архива с исходным кодом.
224
225Параметры вариантов задания из таблицы.
2261) Тип массива: RAID 6 или RAID 50 (5+0). Информация об этих уровнях
227 в простой и доступной форме с поясняющими изображениями:
228 https://en.wikipedia.org/wiki/Standard_RAID_levels. Массивы RAID 6
229 должны восстанавливать данные при выходе из строя любых двух
230 дисков, массивы RAID 50 -- при выходе из строя любого одного диска.
2312) Подсчёт избыточности: XOR и/или POLY. XOR -- подсчёт значения
232 блока избыточности с использованием операции "исключающего или" для
233 пары блоков. В случае большего и/или нечётного количества блоков
234 сообщения можно использовать иерархическое вычисление XOR,
235 добавление фиксированного служебного значения (например, набор "1"
236 соответственно размеру блока) и любые другие приёмы на ваше
237 усмотрение. POLY -- подсчёт значения блока избыточности с
238 использованием полиномиальных выражений (например, пара полиномов
239 первого уровня вида A-B+C-D+E=X и A+2B-3C+4D-5E=Y для массива RAID
240 6 из семи дисков, где A..E -- блоки, составляющие исходное
241 сообщение, X и Y -- блоки избыточности).
2423) Размер сообщения: 8, 10, 12, 14 байт. Это размер исходного (целого)
243 сообщения для записи на массив и читаемого с массива. Сообщение
244 такого размера указывает пользователь при выборе операции записи и
245 такого же размера сообщения выдаются пользователю при выборе
246 операции чтения.
2474) Количество дисков: 3, 4, 5, 6, 7, 8, 10. Это общее количество
248 дисков в массиве для записи блоков сообщения и блоков избыточности.
249
250Комментарии по таблице.
2511) Вы можете, по желанию, выбрать более сложный вариант массива RAID
252 60 (6+0), если вам это интересно, но это необходимо согласовать со
253 мной.
2542) Вы можете, по желанию, выбрать любой другой способ подсчёта блоков
255 избыточности, если вам это интересно, но это необходимо согласовать
256 со мной. Также вы должны быть уверены, что выбранный способ
257 позволяет вам полностью восстановить исходное сообщение при потере
258 любых двух блоков для RAID 6/60 (любой блок сообщения + любой блок
259 избыточности, любые два блока сообщения, два блока избыточности).
260 Иерархическое вычисление XOR демонстрируется следующим примером.
261 Пусть дан массив RAID 5 на пяти дисках и сообщение 12345678(hex).
262 Тогда блоки сообщения будут: 12, 34, 56, 78. Считаем XOR отдельно
263 для первой пары блоков: 12 XOR 34 = 26, отдельно -- для второй пары
264 блоков: 56 XOR 78 = 2E, затем считаем XOR для этих двух
265 результатов: 26 XOR 2E = 08 -- это значение и запишем в блок
266 избыточности. Теперь при потере любого блока сообщения
267 (например, 34) восстановим его. Сначала проверим, из какой
268 исходной пары пропал блок и посчитаем XOR оставшейся пары: 56 XOR
269 78 = 2E, теперь считаем XOR нашего блока избыточности с полученным
270 результатом: 08 XOR 2E = 26 -- получили XOR первой пары значений,
271 теперь находим потерянный блок из этого значения и сохранившегося
272 блока сообщения: 26 XOR 12 = 34 -- блок сообщения восстановлен,
273 можем полностью собрать исходное сообщение. Добавление
274 фиксированного служебного значения может помочь, например, если
275 количество блоков нечётное. Пусть дан массив RAID 5 на четырёх
276 дисках сообщение 123456(hex). Тогда блоки сообщения будут: 12,
277 34, 56. Можно добавить служебное значение, например, FF в качестве
278 фиксированного "виртуального" блока и полностью повторить описанный
279 выше алгоритм. А можно и поступить иначе: вычислять XOR для первой
280 пары блоков сообщения, затем вычислять XOR полученного значения и
281 оставшегося блока сообщения. То есть: 12 XOR 34 = 26, 26 XOR 56 =
282 70 -- это значение и запишем в блок избыточности.
2833) Проанализировав размер сообщения и количество дисков, вы можете
284 увидеть, что сообщение не всегда "делится" на целое число блоков.
285 Это не должно вас смущать, поскольку вы всегда можете принять
286 правила, по которым будете дополнять блок сообщения старшими
287 нулями, чтобы все блоки имели одинаковый размер. Например, пусть
288 дан массив RAID 6 на пяти дисках и сообщение размером 5 байт (Мартин:
289 если брать ascii, а не hex...): 12345(hex). Учитывая, что два
290 диска при записи сообщения будут задействованы под избыточность,
291 нам необходимо разделить исходное сообщение на три блока: 12,
292 34, 5. Последний блок можно дополнить старшим нулём, чтобы получить
293 значение 05, которое и будет записано на диск.
2944) Не забывайте, что чётность в массивах RAID 5 и 6, как и в
295 производных от них, распределённая. То есть, при обращении к
296 каждой следующей "строке" блоки сообщений и избыточности будут
297 располагаться в разном порядке. Вы можете использовать простой
298 приём: создать матрицу размещений и выбирать строку матрицы на
299 основе деления адреса по модулю от числа дисков. Например, пусть
300 будет массив RAID 5 на четырёх дисках. Для него матрица размещений
301 блоков может быть такой (здесь БС -- блок сообщения, БИ -- блок
302 избыточности).
303
304В качестве дисков ваше приложение может использовать любой из двух
305подходов: текстовые файлы (один диск -- один файл, один блок сообщения
306-- одна строка файла) или базу данных (один диск -- одина таблица,
307один блок сообщения -- одна запись таблицы) на ваше усмотрение. Файлы
308и таблицы должны быть проименованы как disk0..disk9, файлы должны
309располагаться в рабочем каталоге приложения и не блокироваться для
310записи в процессе его работы (чтобы можно было очистить содержимое
311любого файла или удалить его, моделируя выход диска из строя).
312
313Примеры пользовательских операций (массив RAID 5 на трёх дисках):
314
315=> 00 write 3d6c= (адрес: 00, операция: запись, сообщение: 3D6C, блок
316сообщения для записи на диск 0: 3D, блок сообщения для записи на диск
3171: 6C, блок избыточности для записи на диск 2 -- арифметическая сумма
3183В+6С: A9);
319
320=> 01 write 519a= (адрес: 01, операция: запись, сообщение: 519A, блок
321сообщения для записи на диск 0: 51, блок избыточности для записи на
322диск 2 -- арифметическая сумма 51+9A: EB, блок сообщения для записи на
323диск 1: 9A);
324
325... удаляем содержимое файла или таблицы "disk0";
326
327=> 00 read= (адрес: 00, операция: чтение, диск 0: пусто, диск 1: блок
328сообщения 6C, диск 2: блок избыточности A9, вычисляем блок сообщения
329диска 0: A9-6C=3D, собираем сообщение: 3D6C).
330
331Графика, анимации, счётчики -- ничего этого не нужно, простое
332консольное приложение. При использовании базы данных необходимо
333отдельно приложить файлы сценариев создания таблиц, в качестве
334диалектов допустимы T-SQL и MySQL.
335#+end_quote
336#+HTML: </i>
337
338[fn:2] I've actually implemented all of these configurations:
339- [[file:../tree/src/raid-4-poly-10b-7d.c][raid-4-poly-10b-7d]]
340- [[file:../tree/src/raid-4-poly-8b-6d.c][raid-4-poly-8b-6d]]
341- [[file:../tree/src/raid-4-poly-8b-7d.c][raid-4-poly-8b-7d]]
342- [[file:../tree/src/raid-4-xor-10b-3d.c][raid-4-xor-10b-3d]]
343- [[file:../tree/src/raid-4-xor-10b-6d.c][raid-4-xor-10b-6d]]
344- [[file:../tree/src/raid-4-xor-10b-7d.c][raid-4-xor-10b-7d]]
345- [[file:../tree/src/raid-4-xor-12b-4d.c][raid-4-xor-12b-4d]]
346- [[file:../tree/src/raid-4-xor-12b-5d.c][raid-4-xor-12b-5d]]
347- [[file:../tree/src/raid-4-xor-12b-7d.c][raid-4-xor-12b-7d]]
348- [[file:../tree/src/raid-4-xor-14b-4d.c][raid-4-xor-14b-4d]]
349- [[file:../tree/src/raid-4-xor-14b-5d.c][raid-4-xor-14b-5d]]
350- [[file:../tree/src/raid-4-xor-14b-8d.c][raid-4-xor-14b-8d]]
351- [[file:../tree/src/raid-4-xor-8b-8d.c][raid-4-xor-8b-8d]]
352- [[file:../tree/src/raid-5-poly-14b-4d.c][raid-5-poly-14b-4d]]
353- [[file:../tree/src/raid-5-xor-12b-3d.c][raid-5-xor-12b-3d]]
354- [[file:../tree/src/raid-5-xor-12b-5d.c][raid-5-xor-12b-5d]]
355- [[file:../tree/src/raid-5-xor-12b-6d.c][raid-5-xor-12b-6d]]
356- [[file:../tree/src/raid-50-poly-12b-6d.c][raid-50-poly-12b-6d]]
357- [[file:../tree/src/raid-50-poly-8b-6d.c][raid-50-poly-8b-6d]]
358- [[file:../tree/src/raid-50-xor-12b-6d.c][raid-50-xor-12b-6d]]
359- [[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 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
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 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\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 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, skip=0pt, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, justification=centering}
20
21\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}}
22\addto\captionsrussian{\renewcommand{\mintedname}{Листинг}}
23\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 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\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 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9%
10% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
11%
12\titleformat{\section}[block]{\newpage\cleardoublepage\large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
13\titlespacing{\section}{0cm}{0cm}{0.5cm}
14
15\titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{}
16\titlespacing{\subsection}{0cm}{0.5cm}{0.5cm}
17
18\titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent]
19\titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm}
20
21%
22% Make special headings, that have their own formatting rules:
23% - centered
24% - all-caps
25% - bold
26%
27% Only three of them must appear in TOC: introduction, conclusion and references
28%
29\newcommand{\introduction}{
30 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
31 \begin{center}
32 \bfseries\large
33 ВВЕДЕНИЕ
34 \end{center}
35}
36
37\newcommand{\conclusion}{
38 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
39 \begin{center}
40 \bfseries\large
41 ЗАКЛЮЧЕНИЕ
42 \end{center}
43}
44
45\newcommand{\references}{
46 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
47 \begin{center}
48 \bfseries\large
49 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
50 \end{center}
51}
52
53\newcommand{\essay}{
54 \begin{center}
55 \bfseries\large
56 РЕФЕРАТ
57 \end{center}
58}
59
60\newcommand{\definitions}{
61 \begin{center}
62 \bfseries\large
63 ОПРЕДЕЛЕНИЯ
64 \end{center}
65}
66
67\newcommand{\abbreviations}{
68 \begin{center}
69 \bfseries\large
70 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
71 \end{center}
72}
73
74\newcommand{\defsabbrs}{
75 \begin{center}
76 \bfseries\large
77 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
78 \end{center}
79}
80
81%
82% Appendices headings. Appendices have autoincrementing number,
83% that is represented with russian letter.
84% This heading must appear in TOC
85%
86\newcounter{appendixcnt}
87\setcounter{appendixcnt}{1}
88
89\renewcommand{\appendix}[1]{
90 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
91 \begin{center}
92 \bfseries\large
93 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
94
95 #1
96 \end{center}
97 \stepcounter{appendixcnt}
98}
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 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11
12\setlist[enumerate, 2]{label=\alphRus*)}
13
14\setlist[1]{wide=\parindent}
15\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 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\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 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3%% \RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black
14]{hyperref}
15
16%
17% Set custom font styles
18%
19%% \renewcommand{\cftsecfont}{\normalfont}
20%% \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
21%% \renewcommand{\cftsecpagefont}{\normalsize}
22%% \renewcommand{\cfttoctitlefont}{\hfill\large\bfseries}
23%% \renewcommand{\cftaftertoctitle}{\hfill\hfill}
24%% \renewcommand{\cfttoctitlefont}{\hfill\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31%% \setlength{\cftbeforesecskip}{0cm}
32%% \setlength{\cftbeforesubsecskip}{0cm}
33%% \setlength{\cftbeforesubsubsecskip}{0cm}
34%% \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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\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 @@
1;;; ox-init --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(require 'oc-bibtex)
13
14(setq org-latex-src-block-backend 'minted)
15
16(setq org-latex-bib-compiler "biber")
17
18(setq org-latex-remove-logfiles nil)
19
20(setq org-latex-caption-above '(table src-block special-block))
21
22(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
23 "%bib %b"
24 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
25(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
26 ("\\section{%s}" . "\\usection{%s}")
27 ("\\subsection{%s}" . "\\subsection*{%s}")
28 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
29 ("\\paragraph{%s}" . "\\paragraph*{%s}")
30 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
31
32;;; ox-init.el ends here
diff --git a/doc/raid0.png b/doc/raid0.png
new file mode 100644
index 0000000..451f892
--- /dev/null
+++ b/doc/raid0.png
Binary files differ
diff --git a/doc/raid5.png b/doc/raid5.png
new file mode 100644
index 0000000..02a4a9a
--- /dev/null
+++ b/doc/raid5.png
Binary files differ
diff --git a/doc/raid50.png b/doc/raid50.png
new file mode 100644
index 0000000..8a0a824
--- /dev/null
+++ b/doc/raid50.png
Binary files 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 @@
1#+TITLE: Разработка приложения, моделирующего работу RAID 50 с заданным размером исходного сообщения --- 8 байт и 6 дисками
2#+AUTHOR: Михалец Мартин
3#+LATEX_HEADER: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ}
4#+LATEX_HEADER: \subject{по дисциплине «Архитектура суперкомпьютеров»}
5#+LATEX_HEADER: \reviewertitle{}\reviewer{Чуватов Михаил Владимирович}
6#+DATE: 2024
7
8#+SETUPFILE: setup.org
9#+LATEX: \sloppy
10
11* Введение
12:PROPERTIES:
13:UNNUMBERED: t
14:END:
15В данном отчёте представлено описание шестой лабораторной работы в
16которой необходимо было разработать приложение, моделирующее работу
17RAID-массива уровня 50 (5+0) с заданными размером исходного сообщения
18и числом дисков. Приложение выполняет операции чтения и записи
19сообщения по указываем адресу. Работа должна быть выполнена в виде
20исполняемого файла приложения, отчёта и архива с исходным кодом. В качестве дисков приложение использует текстовые файлы: =disk0=, =disk1=, =disk2=, =disk3=, =disk4=, =disk5=.
21
22*Выбранный вариант:*
23- Тип массива --- RAID 50
24- Подсчет избыточности --- XOR
25- Размер сообщения --- 8 байт
26- Количество дисков --- 8
27- Представление дисков --- текстовые файлы
28
29* Математическое описание
30** RAID
31RAID (/Reduntant Array of Independent Disks --- избыточный массив
32самостоятельных/независимых дисков/) --- это технология объединения
33двух и более накопителей в единый логический элемент с целью повышения
34производительности и, или, отказоустойчивости отдельно взятого
35элемента/-ов массива.
36
37Избыточные данные по-другому называют дополнительными. Для их
38хранения нужун какой-то объем. Выделяемый объем для этих данных в
39массивах называется аналогично --- избыточным. Избыточность массива
40--- это наличие такого объема, чем больше который, тем больше у
41массива избыточности, что в свою очередь обеспечивает
42отказоустойчивость.
43
44Простыми словами, RAID-массив --- это несколько дисков соединенные в
45единый диск с выделением места под хранение информации для исправления
46ошибок в данных.
47
48Накопители в массив можно объединять по-разному, и на вы выходе
49получать разные массивы со своими достоинствами и недостатками, от
50которых будет зависеть выбор для разных сценариев. Каждый такой
51массив еще называется уровнем.
52
53#+LATEX: \newpage\cleardoublepage
54** RAID 0
55RAID 0 (также /stripe/ или /striped volume/) равномерно распределяет
56данные (/полосы/) по двум или более дискам без дополнительной избыточной
57информации. Поскольку RAID 0 не обеспечивает отказоустойчивости,
58отказ одного диска приведет к сбою всего массива из-за распределения
59данных по всем дискам. Обычно такая конфигурация реализуется для
60повышения пропускной способности, хотя его также можно использовать
61как способ создания большого логического тома из двух или больше
62физических дисков (см. рисунок [[raid0]]).
63
64#+name: raid0
65#+caption: Схема RAID 0 на 2 дисках
66#+attr_latex: :float nil :height 10cm
67[[./raid0.png]]
68
69#+LATEX: \newpage\cleardoublepage
70** RAID 5
71RAID 5 состоит из чередования на уровне блоков с распределенной четностью. Информация о четности распределяется между дисками. Для работы требуется присутствие всех дисков, кроме одного. При сбое одного диска последующие операции чтения могут быть рассчитаны на основе распределенной четности таким образом, чтобы данные не были потеряны. Для применения RAID 5 требуется не менее трёх дисков.
72
73В массиве дисководов RAID 5 существует множество компоновок данных и четности в зависимости от последовательности записи на диски, то есть:
74- Последовательность блоков банных, записываемых слева направо или
75 справа налево на дисковом массиве, с дисков от 0 до n.
76- Разложение блока четности в начале или конце полосы.
77- Расположение первого блока полосы относительно чётности предыдущей
78 полосы.
79
80На рисунке [[raid5]] показаны блоки данных, записанные слева направо, блок
81чётности в конце полосы и первый блок следующей полосы не на том же
82диске, что и блок чётности предыдущей полосы. Его можно обозначить
83как левосторонний асинхронный макет RAID 5. В синхронной компоновке
84первый блок данных следующей полосы записывается на тот же диск, что и блок чётности предыдущей полосы.
85
86#+name: raid5
87#+caption: Схема RAID 5 на 4 дисках
88#+attr_latex: :float nil :height 10cm
89[[./raid5.png]]
90
91#+LATEX: \newpage\cleardoublepage
92** RAID 50
93RAID 50 --- объединение обычно двух, или более, массивов RAID 5 в
94полосу, т.е. комбинация RAID 5 и RAID 0 (см. рисунок [[raid50]]), частично
95исправляющая главный недостаток RAID 5 --- малая пропускная
96способность записи данных за счет параллельного использования
97нескольких таких массивов. Общая ёмкость массива уменьшается на
98ёмкость двух дисков, но, в отличие от RAID 6, без потери данных такой
99массив переносит отказ при потере одного диска на RAID 5 массив.
100Минимальное необходимое число дисков для создания массива RAID 50
101равно 6. Наряду с RAID 10, это наиболее рекомендуемый уровень RAID
102для использования в приложениях, где требуется высокая
103производительность в сочетании с приемлемой надёжностью.
104
105#+name: raid50
106#+caption: Схема RAID 50 на 6 дисках
107#+attr_latex: :float nil :height 10cm
108[[./raid50.png]]
109
110* Особенности реализации
111** Представление дисков
112В данной работе в качестве дисков используются текстовые файлы. Один
113файл --- один диск. Программа сама обеспечивает присутствие файлов
114дисков в правильном формате, пересчитывая поврежденные или удаленные
115файлы дисков, если это возможно, иначе она заново инициализирует все
116файлы дисков. Каждый диск может хранить до 64 (=0x40=) блоков и каждый
117блок хранит 2Б. Блоки и адреса в программе представляются в
118шестнадцатеричной системе счисления. Адрес блока --- номер строки в
119файле. Если на определённом адресе блок не записан, то на его месте
120хранится служебное значение из пробелов, чтобы отличить записан блок
121от блока нулей.
122
123#+name: shift-tbl
124#+caption: Зависимость диска блока от адреса сообщения
125#+attr_latex: :float nil :align r|ccc|ccc| :font \ttfamily
126| addr % 3 | disk0 | disk1 | disk2 | disk3 | disk4 | disk5 |
127|----------+-------+-------+-------+-------+-------+-------|
128| 0 | БС1 | БС2 | БИ1 | БС3 | БС4 | БИ2 |
129| 1 | БС1 | БИ1 | БС2 | БС3 | БИ2 | БС4 |
130| 2 | БИ1 | БС1 | БС2 | БИ2 | БС3 | БС4 |
131
132По таблицы [[shift-tbl]] видно, что первая половина сообщения всегда на
133дисках первого массива, а вторая на дисках второго, причем на каждом
134из дисков хранится либо избыточная информация либо 1/4 сообщения,
135откуда и получается размер блока 2Б.
136
137** Запись сообщения
138Команда записи сообщения имеет следующую штатную форму: =АА write
139Б0Б1Б2Б3Б4Б5Б6Б7=, где =AA= --- адрес, =Бx= x-ый байт сообщения. При
140успешном запуске команды =write= сначала проверяются диски на
141исправность с устранением неисправностей, дальше отдельно для обоих
142пар блоков сообщения считается их четность, и в итоге все блоки
143записываются в ответствующие адресу файлы (см. таблицу [[shift-tbl]]).
144
145** Чтение сообщения
146Команда чтения сообщения имеет следующую штатную форму: =АА read=,
147печатая =Б0Б1Б2Б3Б4Б5Б6Б7=, где =AA= --- адрес, =Бx= x-ый байт сообщения.
148При успешном запуске команды =read= сначала проверяются диски на
149исправность с устранением неисправностей, дальше считаются блоки
150сообщения из ответствующих адресу файлов (см. таблицу [[shift-tbl]]).
151
152Есть несколько случаев сборки сообщения:
1531. Массивы целы --- блоки сообщения считываются как есть.
1542. Выход из строя одного диска --- у подмассива, у которого вышел диск
155 из строя считываются блоки исправных дисков и для получения
156 последнего неисправного блока между ними выполняется операция XOR.
157 С другого, целого, подмассива блоки считываются как в пункте 1.
1583. Выход из строя двух дисков на отдельных массивах --- блоки
159 считаются с обоих подмассивов как они считались в пункте 2 с
160 единственного неисправного.
1614. Выход из строя двух или более дисков одного из массивов --- в этом
162 случае не получится собрать ни одного сообщения, потеря информации.
163
164* Результаты работы
165Приводится примерочный сеанс работы с программой, строки с
166комментариями сеанса начинаются с =#=.
167#+begin_src text
168# Запуск программы, файлов дисков нет
169INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...
170WARNING: found bad disk (missing): disk0
171WARNING: found bad disk (missing): disk1
172WARNING: found bad disk (missing): disk2
173WARNING: found bad disk (missing): disk3
174WARNING: found bad disk (missing): disk4
175WARNING: found bad disk (missing): disk5
176ERROR: too many bad disks, reinitializing the array with new disks...
177# На этот момент файлы дисков ужу существуют
178> 0 asdf
179ERROR: invalid command, must be on of (read, write)
180> 0 read asdf
181ERROR: trailing junk after command: asdf
182> 0 write
183ERROR: expected 16 hex digits for message, received 0
184> 0 write 112233445566778
185ERROR: expected 16 hex digits for message, received 15
186> 0 write 11223344556677888
187ERROR: expected 16 hex digits for message, received 17
188> 0 write asdf
189ERROR: message contains invalid character `s'
190> 0 write -10
191ERROR: message contains invalid character `-'
192>
193> 0 write 1122334455667788
194> 1 write 1122334455667788
195> 2 write 1122334455667788
196> 0 read
1971122334455667788
198> 1 read
1991122334455667788
200> 2 read
2011122334455667788
202>
203# Мануальное повреждение файла disk2
204> 0 read
205WARNING: found bad disk (corrupted): disk2
206INFO: there is just 1 bad disk, recomputing it...
2071122334455667788
208>
209# Мануальное повреждение файла disk4
210> 1 read
211WARNING: found bad disk (corrupted): disk4
212INFO: there is just 1 bad disk, recomputing it...
2131122334455667788
214>
215# Мануальное повреждение файлов disk0 и disk5 => можно востановить
216> 2 read
217WARNING: found bad disk (corrupted): disk0
218WARNING: found bad disk (corrupted): disk5
219INFO: there are 2 bad disk in separate clusters, recomputing them...
2201122334455667788
221>
222# Мануальное повреждение файлов disk0 и disk1 => некак востановить
223> 0 read
224WARNING: found bad disk (corrupted): disk0
225WARNING: found bad disk (corrupted): disk1
226ERROR: too many bad disks, reinitializing the array with new disks...
227No data stored!
228>
229# По адресу 0x1F пока не было записано сообщение
230> 1F read
231No data stored!
232>
233# Попытка обращения к адресу за пределами
234> 40 read
235ERROR: address not in set [0x00; 0x40)
236> AA read
237ERROR: address not in set [0x00; 0x40)
238> 100 read
239ERROR: address not in set [0x00; 0x40)
240> interrupt
241#+end_src
242
243* Заключение
244:PROPERTIES:
245:UNNUMBERED: t
246:END:
247В результате данной работы было разработано приложение --- модель RAID
24850 с 6 дисками и размером сообщения 6 байт, а именно консольная
249программа с двумя командами =read= и =write=, написанная на языке
250программирования Си (=-std=gnu99=). Программа успешно хранит информацию
251в файлах массива RAID 50, выводит необходимые сообщения и
252восстанавливает диски в случае их неисправности.
253
254* Используемая литература
255:PROPERTIES:
256:UNNUMBERED: t
257:END:
2581. Standard RAID levels --- Википедия // URL:
259 [[https://en.wikipedia.org/wiki/Standard_RAID_levels]] (Дата обращения:
260 22.05.2024)
2612. Nested RAID levels --- Википедия // URL:
262 [[https://en.wikipedia.org/wiki/Nested_RAID_levels]] (Дата обращения:
263 22.05.2024)
264
265# Local Variables:
266# org-confirm-babel-evaluate: nil
267# org-export-async-init-file: "ox-init.el"
268# org-export-in-background: t
269# 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 @@
1#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline
2#+OPTIONS: author:t broken-links:nil c:nil creator:nil
3#+OPTIONS: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+OPTIONS: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+OPTIONS: timestamp:nil title:t toc:t todo:nil |:t
6#+SELECT_TAGS: export
7#+EXCLUDE_TAGS: noexport
8#+CREATOR: Emacs 29.1 (Org mode 9.6.9)
9#+BIBLIOGRAPHY: biblio.bib
10#+CITE_EXPORT: biblatex
11#+LATEX_COMPILER: xelatex
12#+LATEX_CLASS: spbstu-report
13# #+LATEX_CLASS_OPTIONS: [draft]
14#+LATEX_HEADER: \usepackage{enumitem}
15#+LATEX_HEADER: \usepackage{array}
16#+LATEX_HEADER: \newcolumntype{C}{>{$}c<{$}} % math-mode version of "c" column type
17#+LATEX_HEADER: \usepackage{float}
18#+LATEX_HEADER: \usepackage{tikz}
19#+LATEX_HEADER: \usepackage{pgfplots}
20#+LATEX_HEADER: \pgfplotsset{compat=1.18}
21#+LATEX_HEADER: \usepackage{afterpage}
22#+LATEX_HEADER: \usepackage{minted}
23#+LATEX_HEADER: \usemintedstyle{bw}
24#+LATEX_HEADER: \setminted{baselinestretch=1,linenos,breaklines}
25#+LATEX_HEADER: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
26#+LATEX_HEADER: \usepackage{algorithm}
27#+LATEX_HEADER: \usepackage{algpseudocode}
28#+LATEX_HEADER: \makeatletter
29#+LATEX_HEADER: \renewcommand{\ALG@name}{Алгоритм}
30#+LATEX_HEADER: \makeatother
31#+LATEX_HEADER: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
32#+LATEX_HEADER: \setmainfont{Times New Roman}
33#+LATEX_HEADER: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff]
34#+LATEX_HEADER: \newcommand*{\myref}[2]{\hyperref[{#1}]{{#2}~\ref*{#1}}}
35#+LATEX_HEADER: \newcommand{\hlabel}{\phantomsection\label}
36#+LATEX_HEADER: \newcommand*{\fullref}[1]{\hyperref[{#1}]{\autoref*{#1} \nameref*{#1}}}
37#+LATEX_HEADER: \setlength{\abovecaptionskip}{5pt}
38#+LATEX_HEADER: \setlength{\belowcaptionskip}{0pt}
39#+LATEX_HEADER: \hypersetup{hidelinks}
40#+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 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18
19\newcommand{\usection}[1]{\section*{#1}\addcontentsline{toc}{section}{#1}}
20
21\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
22\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
23\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
24\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
25\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
26\renewcommand{\maketitle}{
27 \begin{titlepage}
28 \begin{center}
29 \vspace{2cm}
30 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
31
32 \normalsize{Федеральное государственное автономное
33 образовательное учреждение высшего образования
34 \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
35
36 \vspace{0.5cm}
37 \normalsize{Институт компьютерных наук и кибербезопасности}
38
39 \normalsize{Высшая школа технологии искусственного интеллекта}
40
41 \normalsize{Направление 02.03.03 Математическое обеспечение и администрирование информационных систем}
42
43 \vspace{2cm}
44 \LARGE{ОТЧЁТ}
45
46 \normalsize{\@reportof}
47
48 \large{\@subject}
49
50 \large{\textit{\@title}}
51 \end{center}
52
53 \vspace{3cm}
54 \small{
55 \begin{tabular}{lrrl}
56 \!\!\!Студент, & \hspace{2cm} & & \\
57 \!\!\!группы 5130203/20002 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
58 \!\!\!Преподаватель, & \hspace{2cm} & \\
59 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
60 &&\hspace{5cm}
61 \end{tabular}
62 \begin{flushright}
63 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
64 \end{flushright}
65 }
66
67 \vspace*{\fill}
68 \begin{center}
69 \small{Санкт-Петербург, \@date}
70 \end{center}
71 \end{titlepage}
72 \setcounter{page}{2}
73}
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 @@
1Добрый день.
2
3Формулирование задания затянулось в связи с тем, что на выходных мне
4всё ещё присылали для проверки программы из предыдущей работы и это
5были не только те, кому предоставлялось время до конца выходных, но и
6все остальные, кто должен был закончить работу раньше. Тем не менее,
7удалось сформулировать новое и последнее практическое задание. В этот
8раз для двух направлений задания или варианты заданий будут
9различными. Ниже текст задания для студентов направления МКН.
10
11Итак, каждому студенту индивидуально необходимо разработать
12приложение, моделирующее работу RAID-массива уровней 6 и 50 (5+0) с
13заданными размером исходного сообщения и числом дисков. Приложение
14выполняет операции чтения и записи сообщения по указываемому адресу
15(линейный массив строк с индексами от 0 до 63). К письму приложена
16таблица с вариантами заданий, где один символ "+" обозначает один
17доступный для выбора вариант. Распределите их между собой таким
18образом, чтобы каждому достался свой вариант. Работа должна быть
19выполнена в виде исполняемого файла приложения, отчёта, архива с
20исходным кодом.
21
22Дата и время завершения приёма работ и отчётов: 23:59 24.05.2024.
23
24Параметры вариантов задания из таблицы.
251) Тип массива: RAID 6 или RAID 50 (5+0). Информация об этих уровнях
26 в простой и доступной форме с поясняющими изображениями:
27 https://en.wikipedia.org/wiki/Standard_RAID_levels. Массивы RAID 6
28 должны восстанавливать данные при выходе из строя любых двух
29 дисков, массивы RAID 50 -- при выходе из строя любого одного диска.
302) Подсчёт избыточности: XOR и/или POLY. XOR -- подсчёт значения
31 блока избыточности с использованием операции "исключающего или" для
32 пары блоков. В случае большего и/или нечётного количества блоков
33 сообщения можно использовать иерархическое вычисление XOR,
34 добавление фиксированного служебного значения (например, набор "1"
35 соответственно размеру блока) и любые другие приёмы на ваше
36 усмотрение. POLY -- подсчёт значения блока избыточности с
37 использованием полиномиальных выражений (например, пара полиномов
38 первого уровня вида A-B+C-D+E=X и A+2B-3C+4D-5E=Y для массива RAID
39 6 из семи дисков, где A..E -- блоки, составляющие исходное
40 сообщение, X и Y -- блоки избыточности).
413) Размер сообщения: 8, 10, 12, 14 байт. Это размер исходного (целого)
42 сообщения для записи на массив и читаемого с массива. Сообщение
43 такого размера указывает пользователь при выборе операции записи и
44 такого же размера сообщения выдаются пользователю при выборе
45 операции чтения.
464) Количество дисков: 3, 4, 5, 6, 7, 8, 10. Это общее количество
47 дисков в массиве для записи блоков сообщения и блоков избыточности.
48
49Комментарии по таблице.
501) Вы можете, по желанию, выбрать более сложный вариант массива RAID
51 60 (6+0), если вам это интересно, но это необходимо согласовать со
52 мной.
532) Вы можете, по желанию, выбрать любой другой способ подсчёта блоков
54 избыточности, если вам это интересно, но это необходимо согласовать
55 со мной. Также вы должны быть уверены, что выбранный способ
56 позволяет вам полностью восстановить исходное сообщение при потере
57 любых двух блоков для RAID 6/60 (любой блок сообщения + любой блок
58 избыточности, любые два блока сообщения, два блока избыточности).
59 Иерархическое вычисление XOR демонстрируется следующим примером.
60 Пусть дан массив RAID 5 на пяти дисках и сообщение 12345678(hex).
61 Тогда блоки сообщения будут: 12, 34, 56, 78. Считаем XOR отдельно
62 для первой пары блоков: 12 XOR 34 = 26, отдельно -- для второй пары
63 блоков: 56 XOR 78 = 2E, затем считаем XOR для этих двух
64 результатов: 26 XOR 2E = 08 -- это значение и запишем в блок
65 избыточности. Теперь при потере любого блока сообщения
66 (например, 34) восстановим его. Сначала проверим, из какой
67 исходной пары пропал блок и посчитаем XOR оставшейся пары: 56 XOR
68 78 = 2E, теперь считаем XOR нашего блока избыточности с полученным
69 результатом: 08 XOR 2E = 26 -- получили XOR первой пары значений,
70 теперь находим потерянный блок из этого значения и сохранившегося
71 блока сообщения: 26 XOR 12 = 34 -- блок сообщения восстановлен,
72 можем полностью собрать исходное сообщение. Добавление
73 фиксированного служебного значения может помочь, например, если
74 количество блоков нечётное. Пусть дан массив RAID 5 на четырёх
75 дисках сообщение 123456(hex). Тогда блоки сообщения будут: 12,
76 34, 56. Можно добавить служебное значение, например, FF в качестве
77 фиксированного "виртуального" блока и полностью повторить описанный
78 выше алгоритм. А можно и поступить иначе: вычислять XOR для первой
79 пары блоков сообщения, затем вычислять XOR полученного значения и
80 оставшегося блока сообщения. То есть: 12 XOR 34 = 26, 26 XOR 56 =
81 70 -- это значение и запишем в блок избыточности.
823) Проанализировав размер сообщения и количество дисков, вы можете
83 увидеть, что сообщение не всегда "делится" на целое число блоков.
84 Это не должно вас смущать, поскольку вы всегда можете принять
85 правила, по которым будете дополнять блок сообщения старшими
86 нулями, чтобы все блоки имели одинаковый размер. Например, пусть
87 дан массив RAID 6 на пяти дисках и сообщение размером 5 байт (Мартин:
88 если брать ascii, а не hex...): 12345(hex). Учитывая, что два
89 диска при записи сообщения будут задействованы под избыточность,
90 нам необходимо разделить исходное сообщение на три блока: 12,
91 34, 5. Последний блок можно дополнить старшим нулём, чтобы получить
92 значение 05, которое и будет записано на диск.
934) Не забывайте, что чётность в массивах RAID 5 и 6, как и в
94 производных от них, распределённая. То есть, при обращении к
95 каждой следующей "строке" блоки сообщений и избыточности будут
96 располагаться в разном порядке. Вы можете использовать простой
97 приём: создать матрицу размещений и выбирать строку матрицы на
98 основе деления адреса по модулю от числа дисков. Например, пусть
99 будет массив RAID 5 на четырёх дисках. Для него матрица размещений
100 блоков может быть такой (здесь БС -- блок сообщения, БИ -- блок
101 избыточности).
102
103В качестве дисков ваше приложение может использовать любой из двух
104подходов: текстовые файлы (один диск -- один файл, один блок сообщения
105-- одна строка файла) или базу данных (один диск -- одина таблица,
106один блок сообщения -- одна запись таблицы) на ваше усмотрение. Файлы
107и таблицы должны быть проименованы как disk0..disk9, файлы должны
108располагаться в рабочем каталоге приложения и не блокироваться для
109записи в процессе его работы (чтобы можно было очистить содержимое
110любого файла или удалить его, моделируя выход диска из строя).
111
112Примеры пользовательских операций (массив RAID 5 на трёх дисках):
113
114=> 00 write 3d6c= (адрес: 00, операция: запись, сообщение: 3D6C, блок
115сообщения для записи на диск 0: 3D, блок сообщения для записи на диск
1161: 6C, блок избыточности для записи на диск 2 -- арифметическая сумма
1173В+6С: A9);
118
119=> 01 write 519a= (адрес: 01, операция: запись, сообщение: 519A, блок
120сообщения для записи на диск 0: 51, блок избыточности для записи на
121диск 2 -- арифметическая сумма 51+9A: EB, блок сообщения для записи на
122диск 1: 9A);
123
124... удаляем содержимое файла или таблицы "disk0";
125
126=> 00 read= (адрес: 00, операция: чтение, диск 0: пусто, диск 1: блок
127сообщения 6C, диск 2: блок избыточности A9, вычисляем блок сообщения
128диска 0: A9-6C=3D, собираем сообщение: 3D6C).
129
130Графика, анимации, счётчики -- ничего этого не нужно, простое
131консольное приложение. При использовании базы данных необходимо
132отдельно приложить файлы сценариев создания таблиц, в качестве
133диалектов допустимы T-SQL и MySQL.
134
135При наличии вопросов предлагаю провести очные встречи, например, в
136среду 08.05.2024, предварительно согласовав их накануне, во вторник
13707.05.2024.
diff --git a/makefile b/makefile
new file mode 100644
index 0000000..830d209
--- /dev/null
+++ b/makefile
@@ -0,0 +1,54 @@
1all: \
2raid-50-xor-8b-6d \
3raid-50-xor-8b-6d.exe \
4raid-50-xor-12b-6d \
5raid-50-xor-12b-6d.exe \
6raid-50-poly-8b-6d \
7raid-50-poly-8b-6d.exe \
8raid-50-poly-12b-6d \
9raid-50-poly-12b-6d.exe \
10raid-4-xor-12b-7d \
11raid-4-xor-12b-7d.exe \
12raid-4-xor-12b-4d \
13raid-4-xor-12b-4d.exe \
14raid-4-xor-12b-5d \
15raid-4-xor-12b-5d.exe \
16raid-4-xor-14b-4d \
17raid-4-xor-14b-4d.exe \
18raid-4-xor-14b-5d \
19raid-4-xor-14b-5d.exe \
20raid-4-xor-14b-8d \
21raid-4-xor-14b-8d.exe \
22raid-4-xor-10b-3d \
23raid-4-xor-10b-3d.exe \
24raid-4-xor-10b-6d \
25raid-4-xor-10b-6d.exe \
26raid-4-xor-10b-7d \
27raid-4-xor-10b-7d.exe \
28raid-4-xor-8b-8d \
29raid-4-xor-8b-8d.exe \
30raid-4-poly-10b-7d \
31raid-4-poly-10b-7d.exe \
32raid-4-poly-8b-7d \
33raid-4-poly-8b-7d.exe \
34raid-4-poly-8b-6d \
35raid-4-poly-8b-6d.exe \
36raid-5-xor-12b-3d \
37raid-5-xor-12b-3d.exe \
38raid-5-xor-12b-5d \
39raid-5-xor-12b-5d.exe \
40raid-5-xor-12b-6d \
41raid-5-xor-12b-6d.exe \
42raid-5-poly-14b-4d \
43raid-5-poly-14b-4d.exe
44
45%: src/%.c
46 gcc -std=gnu99 -ggdb3 -D_GNU_SOURCE -o $@ $<
47
48%.exe: src/%.c
49 gcc-cross-x86_64-w64-mingw32-toolchain -- x86_64-w64-mingw32-gcc \
50 -std=gnu99 -ggdb3 -D_GNU_SOURCE \
51 -L gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/lib/ \
52 -I gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/include/ \
53 -B gcc-cross-x86_64-w64-mingw32-toolchain-13.3.0/lib/ \
54 -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 @@
1// kira
2// M1M2 M3M4 M5M6 M7M8 M9MA 0000 P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <unistd.h>
6#include <stdint.h>
7#include <stdbool.h>
8#include <string.h>
9#include <ctype.h>
10#include <locale.h>
11
12#define DISK_COUNT 7
13#define MESSAGE_SIZE 10
14#define BLOCK_SIZE 2
15#define PADDING_SIZE 2
16
17// uint8_t coefficients[DISK_COUNT - 1] = { 1, 3, 5, 7, 11, 13 };
18uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1, 1 };
19
20#define DISK_SIZE 0x40
21
22#define POPCOUNT __builtin_popcount
23#define CTZ __builtin_ctz
24
25enum command {
26 COMMAND_NONE,
27 COMMAND_WRITE,
28 COMMAND_READ,
29};
30
31FILE *disks[DISK_COUNT];
32
33#ifndef WIN32
34#define LINE_SIZE 5
35#else
36#define LINE_SIZE 6
37static ssize_t
38getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
39 register char c;
40 register char *cs = NULL;
41 register int length = 0;
42 while ((c = getc (stream)) != EOF) {
43 cs = (char *) realloc (cs, ++length + 1);
44 if ((*(cs + length - 1) = c) == '\n') {
45 *(cs + length) = '\0';
46 break;
47 }
48 }
49
50 // return the allocated memory if lineptr is null
51 if ((*lineptr) == NULL) {
52 *lineptr = cs;
53 } else {
54 // check if enough memory is allocated
55 if ((length + 1) < *n)
56 *lineptr = (char *) realloc (*lineptr, length + 1);
57 memcpy (*lineptr, cs, length);
58 free (cs);
59 }
60
61 return (ssize_t) (*n = strlen (*lineptr));
62}
63#endif
64
65static void
66open_disks (uint8_t address)
67{
68 uint16_t bad_disks = 0;
69 for (int i = 0; i < DISK_COUNT; ++i) {
70 char filename[6];
71 snprintf (filename, 6, "disk%d", i);
72 disks[i] = fopen (filename, "r+");
73 if (!disks[i]) { // disk file was deleted
74 disks[i] = fopen (filename, "w+");
75 if (!disks[i]) {
76 fprintf (stderr, "ERROR - unable to open file: %s\n", filename);
77 exit (EXIT_FAILURE);
78 }
79
80 fprintf (stderr, "WARNING - found bad disk that is missing: %s\n", filename);
81 bad_disks |= 1 << i;
82 } else { // disk file wasn't deleted
83 fseek (disks[i], 0, SEEK_END);
84 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
85 fprintf (stderr, "WARNING - found corrupted disk: %s\n", filename);
86 bad_disks |= 1 << i;
87 fclose (disks[i]);
88 disks[i] = fopen (filename, "w+");
89 } else rewind (disks[i]);
90 }
91 }
92
93 // there were bad disks
94 int bad_disk_count = POPCOUNT (bad_disks);
95 if (bad_disk_count == 1) { // recompute lost disk
96 fprintf (stderr, "NOTICE - only 1 bad disk, recomputing it again \n");
97 int bad_disk = CTZ (bad_disks);
98
99 for (int j = 0; j < DISK_SIZE; ++j) {
100 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
101
102 // read blocks from good disks
103 bool empty = false;
104 for (int k = 0; k < DISK_COUNT; ++k) {
105 if (k == bad_disk) continue;
106
107 int c = fgetc (disks[k]);
108 if (c == ' ') {
109 empty = true;
110 fgetc (disks[k]);
111
112 fgetc (disks[k]);
113 fgetc (disks[k]);
114 } else {
115 ungetc (c, disks[k]);
116 for (int l = 0; l < BLOCK_SIZE; ++l) {
117 fscanf (disks[k], "%02hhX", &block_bytes[k*BLOCK_SIZE + l]);
118 }
119 }
120
121 fgetc (disks[k]);
122 }
123
124 if (empty) {
125 fprintf (disks[bad_disk], " \n");
126 continue;
127 }
128
129 // compute lost block
130 if (bad_disk == DISK_COUNT - 1) { // lost parity
131 for (int l = 0; l < BLOCK_SIZE; ++l)
132 block_bytes[bad_disk*BLOCK_SIZE + l] = 0x00;
133 for (int k = 0; k < DISK_COUNT - 1; ++k) {
134 for (int l = 0; l < BLOCK_SIZE; ++l)
135 block_bytes[bad_disk*BLOCK_SIZE + l] +=
136 coefficients[k]*block_bytes[k*BLOCK_SIZE + l];
137 }
138 } else { // lost data
139 for (int l = 0; l < BLOCK_SIZE; ++l)
140 block_bytes[bad_disk*BLOCK_SIZE + l] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + l]/coefficients[bad_disk];
141 for (int k = 0; k < DISK_COUNT - 1; ++k) {
142 if (k == bad_disk) continue;
143 for (int l = 0; l < BLOCK_SIZE; ++l)
144 block_bytes[bad_disk*BLOCK_SIZE + l] -=
145 coefficients[k]*block_bytes[k*BLOCK_SIZE + l]/coefficients[bad_disk];
146 }
147 }
148
149 // write lost block
150 for (int l = 0; l < BLOCK_SIZE; ++l)
151 fprintf (disks[bad_disk], "%02hhX", block_bytes[bad_disk*BLOCK_SIZE + l]);
152 fprintf (disks[bad_disk], "\n");
153 }
154 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
155 fprintf (stderr, "ERROR - more than one bad disks, reinitializing the array with new disks \n");
156
157 for (int i = 0; i < DISK_COUNT; ++i) {
158 for (int j = 0; j < DISK_SIZE; ++j)
159 fputs (" \n", disks[i]);
160 }
161 }
162
163 // position head for writing/reading message
164 for (int i = 0; i < DISK_COUNT; ++i)
165 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
166}
167
168static void
169close_disks (void)
170{
171 for (int i = 0; i < DISK_COUNT; ++i)
172 fclose (disks[i]);
173}
174
175int
176main (void)
177{
178 fprintf (stderr, "Initialization RAID 4 with POLY parity on 7 disks. The message size is 10 bytes. \n");
179 // check disk integrity on startup
180 open_disks (0);
181 close_disks ( );
182
183 for (;;) {
184 char *head;
185 int assigned;
186 int scanned;
187
188 // read whole line
189 printf ("> ");
190 char *line = NULL;
191 size_t line_size = 0;
192 scanned = getline (&line, &line_size, stdin);
193 if (scanned == -1)
194 exit (EXIT_SUCCESS);
195 else if (scanned == 1)
196 continue;
197 head = line;
198
199 uint8_t address; { // scan address
200 assigned = sscanf (head, "%hhx%n", &address, &scanned);
201 if (assigned != 1 || address >= DISK_SIZE) {
202 fprintf(stderr, "ERROR - address not in set [0x00; 0x40) \n");
203 continue;
204 } head += scanned;
205 }
206
207 enum command command; { // scan command
208 while (*head == ' ') head += 1;
209 if (!strncmp (head, "read", 4)) {
210 head += 4;
211 command = COMMAND_READ;
212 } else if (!strncmp (head, "write", 5)) {
213 head += 5;
214 command = COMMAND_WRITE;
215 }
216 if (!isspace(*head))
217 command = COMMAND_NONE;
218 }
219
220 switch (command) {
221 case COMMAND_NONE: {
222 fprintf(stderr, "ERROR - there is no such command, try entering read or write \n");
223 continue;
224 } break;
225 case COMMAND_READ: {
226 uint8_t message[MESSAGE_SIZE];
227 uint8_t parity [ BLOCK_SIZE];
228 uint8_t padding[PADDING_SIZE];
229
230 while (isspace (*head)) {
231 head += 1;
232 if (*head == '\n' ||
233 *head == '\r') {
234 *head = '\0';
235 }
236 }
237 if (*head) {
238 fprintf (stderr, "ERROR - extraneous data after the message: %s", head);
239 continue;
240 }
241
242 open_disks (address);
243
244 int c = fgetc (disks[0]);
245 if (c == ' ') {
246 close_disks ();
247 printf ("The line is empty \n");
248 break;
249 } ungetc (c, disks[0]);
250
251 // parse out message
252 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
253 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
254 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
255 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
256 fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]);
257 fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]);
258 fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
259 close_disks ();
260
261 printf ("%02hhX%02hhX "
262 "%02hhX%02hhX "
263 "%02hhX%02hhX "
264 "%02hhX%02hhX "
265 "%02hhX%02hhX\n",
266 message[0x0], message[0x1],
267 message[0x2], message[0x3],
268 message[0x4], message[0x5],
269 message[0x6], message[0x7],
270 message[0x8], message[0x9]);
271 } break;
272 case COMMAND_WRITE: {
273 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
274 int message_size = 0;
275
276
277 while (*head == ' ' ||
278 *head == '\t') ++head;
279 const char *invalid = NULL;
280 size_t len = 0;
281 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
282 if (!strchr ("0123456789abcdefABCDEF", *c)) {
283 invalid = c;
284 break;
285 } len += 1;
286 } if (invalid) {
287 fprintf (stderr, "ERROR - message contains invalid character `%c'\n", *invalid);
288 break;
289 } if (len != 2*MESSAGE_SIZE) {
290 fprintf (stderr, "ERROR - expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
291 break;
292 }
293
294 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
295 message_size < MESSAGE_SIZE) {
296 head += scanned;
297 message_size += 1;
298 }
299 }
300
301 uint8_t padding[PADDING_SIZE] = {0};
302
303 // compute parity
304 uint8_t parity[BLOCK_SIZE] = {
305 coefficients[0]*message[0x0] +
306 coefficients[1]*message[0x2] +
307 coefficients[2]*message[0x4] +
308 coefficients[3]*message[0x6] +
309 coefficients[4]*message[0x8] +
310 coefficients[5]*padding[0x0],
311
312 coefficients[0]*message[0x1] +
313 coefficients[1]*message[0x3] +
314 coefficients[2]*message[0x5] +
315 coefficients[3]*message[0x7] +
316 coefficients[4]*message[0x9] +
317 coefficients[5]*padding[0x1],
318 };
319
320 // write blocks
321 open_disks (address); // open disk files, ensuring their integrity
322 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
323 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
324 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
325 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
326 fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]);
327 fprintf (disks[5], "%02hhX%02hhX\n", padding[0x0], padding[0x1]);
328 fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
329 close_disks ();
330 } break;
331 }
332 free (line);
333 line = NULL;
334 }
335
336 return EXIT_SUCCESS;
337}
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 @@
1// jasmin
2// M1M2 M3M4 M5M6 M7M8 0000 P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 6
11#define MESSAGE_SIZE 8
12#define PARITY_SIZE 2
13#define BLOCK_SIZE 2
14#define PADDING_SIZE 2
15
16uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1 };
17
18#define DISK_SIZE 0x40
19
20#define POPCOUNT __builtin_popcount
21#define CTZ __builtin_ctz
22
23enum command {
24 COMMAND_WRITE,
25 COMMAND_READ,
26};
27
28FILE *disks[DISK_COUNT];
29
30#ifndef WIN32
31#define LINE_SIZE 5
32#else
33#define LINE_SIZE 6
34static ssize_t
35getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
36 register char c;
37 register char *cs = NULL;
38 register int length = 0;
39 while ((c = getc (stream)) != EOF) {
40 cs = (char *) realloc (cs, ++length + 1);
41 if ((*(cs + length - 1) = c) == '\n') {
42 *(cs + length) = '\0';
43 break;
44 }
45 }
46
47 // return the allocated memory if lineptr is null
48 if ((*lineptr) == NULL) {
49 *lineptr = cs;
50 } else {
51 // check if enough memory is allocated
52 if ((length + 1) < *n)
53 *lineptr = (char *) realloc (*lineptr, length + 1);
54 memcpy (*lineptr, cs, length);
55 free (cs);
56 }
57
58 return (ssize_t) (*n = strlen (*lineptr));
59}
60#endif
61
62static void
63open_disks (uint8_t address)
64{
65 uint16_t bad_disks = 0;
66 for (int i = 0; i < DISK_COUNT; ++i) {
67 char filename[] = "disk0";
68 filename[strlen (filename) - 1] += i;
69 disks[i] = fopen (filename, "r+");
70 if (!disks[i]) { // disk file was deleted
71 disks[i] = fopen (filename, "w+");
72 if (!disks[i]) {
73 fprintf (stderr, "The file was not opened:( %s\n", filename);
74 exit (EXIT_FAILURE);
75 }
76
77 fprintf (stderr, "Missing disk:(: %s\n", filename);
78 bad_disks |= 1 << i;
79 } else { // disk file wasn't deleted
80 fseek (disks[i], 0, SEEK_END);
81 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
82 fprintf (stderr, "Corrupted disk: %s\n", filename);
83 bad_disks |= 1 << i;
84 fclose (disks[i]);
85 disks[i] = fopen (filename, "w+");
86 } else rewind (disks[i]);
87 }
88 }
89
90 // there were bad disks
91 int bad_disk_count = POPCOUNT (bad_disks);
92 if (bad_disk_count == 1) { // recompute lost disk
93 fprintf (stderr, "There is only 1 faulty disk, I'm recalculating it again \n");
94 int bad_disk = CTZ (bad_disks);
95
96 for (int j = 0; j < DISK_SIZE; ++j) {
97 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
98
99 // read blocks from good disks
100 bool empty = false;
101 for (int k = 0; k < DISK_COUNT; ++k) {
102 if (k == bad_disk) continue;
103
104 int c = fgetc (disks[k]);
105 if (c == ' ') {
106 empty = true;
107 fgetc (disks[k]);
108
109 fgetc (disks[k]);
110 fgetc (disks[k]);
111 } else {
112 ungetc (c, disks[k]);
113 fscanf (disks[k], "%02hhX%02hhX", &block_bytes[k*BLOCK_SIZE + 0], &block_bytes[k*BLOCK_SIZE + 1]);
114 } fgetc (disks[k]);
115 }
116
117 if (empty) {
118 fprintf (disks[bad_disk], " \n");
119 continue;
120 }
121
122 // compute lost block
123 if (bad_disk == DISK_COUNT - 1) { // lost parity
124 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
125 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
126 for (int k = 0; k < DISK_COUNT - 1; ++k) {
127 for (int l = 0; l < PARITY_SIZE; ++l)
128 block_bytes[bad_disk*BLOCK_SIZE + l] +=
129 coefficients[k]*block_bytes[k*BLOCK_SIZE + l];
130 }
131 } else { // lost data
132 block_bytes[bad_disk*BLOCK_SIZE + 0] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + 0];
133 block_bytes[bad_disk*BLOCK_SIZE + 1] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + 1];
134 for (int k = 0; k < DISK_COUNT - 1; ++k) {
135 if (k == bad_disk) continue;
136 for (int l = 0; l < PARITY_SIZE; ++l)
137 block_bytes[bad_disk*BLOCK_SIZE + l] -=
138 coefficients[k]*block_bytes[k*BLOCK_SIZE + l];
139 }
140 }
141
142 // write lost block
143 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
144 block_bytes[bad_disk*BLOCK_SIZE + 0],
145 block_bytes[bad_disk*BLOCK_SIZE + 1]);
146 }
147 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
148 fprintf (stderr, "Too many damaged disks, reinitialization of the array with new disks...\n");
149
150 for (int i = 0; i < DISK_COUNT; ++i) {
151 for (int j = 0; j < DISK_SIZE; ++j)
152 fputs (" \n", disks[i]);
153 }
154 }
155
156 // position head for writing/reading message
157 for (int i = 0; i < DISK_COUNT; ++i)
158 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
159}
160
161static void
162close_disks (void)
163{
164 for (int i = 0; i < DISK_COUNT; ++i)
165 fclose (disks[i]);
166}
167
168int
169main (void)
170{
171 fprintf (stderr, "Starting RAID 4 with POLY on 7 disks using 12-byte messages...\n");
172 // check disk integrity on startup
173 open_disks (0);
174 close_disks ( );
175
176 for (;;) {
177 char *line = NULL;
178 size_t line_size = 0;
179 const char *head;
180 int assigned;
181 int scanned;
182
183 // read whole line
184 printf ("> ");
185 scanned = getline (&line, &line_size, stdin);
186 if (scanned == -1)
187 exit (EXIT_SUCCESS);
188 else if (scanned == 1)
189 continue;
190 head = line;
191
192 uint8_t address; { // scan address
193 assigned = sscanf (head, "%hhx%n", &address, &scanned);
194 if (assigned != 1 || address >= DISK_SIZE) {
195 fprintf(stderr, "The address is not specified [0x00; 0x40)\n");
196 continue;
197 } head += scanned;
198 }
199
200 enum command command; { // scan command
201 char command_buffer[6] = {0};
202 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
203 if (assigned != 1 ||
204 (!strncmp (command_buffer, "read", 4) &&
205 !strncmp (command_buffer, "write", 5))) {
206 fprintf(stderr, "Command not specified (read; write)\n");
207 continue;
208 } head += scanned;
209 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
210 }
211
212 switch (command) {
213 case COMMAND_READ: {
214 uint8_t message[MESSAGE_SIZE];
215 uint8_t parity [ PARITY_SIZE];
216 uint8_t padding[PADDING_SIZE];
217
218 // parse out message
219 open_disks (address);
220
221 int c = fgetc (disks[0]);
222 if (c == ' ') {
223 close_disks ();
224 printf ("There is no message\n");
225 break;
226 } ungetc (c, disks[0]);
227
228 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
229 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
230 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
231 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
232 fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]);
233 fscanf (disks[5], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
234 close_disks ();
235
236 printf ("%02hhX%02hhX "
237 "%02hhX%02hhX "
238 "%02hhX%02hhX "
239 "%02hhX%02hhX\n",
240 message[0x0], message[0x1],
241 message[0x2], message[0x3],
242 message[0x4], message[0x5],
243 message[0x6], message[0x7]);
244 } break;
245 case COMMAND_WRITE: {
246 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
247 int message_size = 0;
248
249 while (*head == ' ' ||
250 *head == '\t') ++head;
251 const char *invalid = NULL;
252 size_t len = 0;
253 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
254 if (!strchr ("0123456789abcdefABCDEF", *c)) {
255 invalid = c;
256 break;
257 } len += 1;
258 } if (invalid) {
259 fprintf (stderr, "Message contains invalid character `%c'\n", *invalid);
260 break;
261 } if (len != 2*MESSAGE_SIZE) {
262 fprintf (stderr, "Expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
263 break;
264 }
265
266 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
267 message_size < MESSAGE_SIZE) {
268 head += scanned;
269 message_size += 1;
270 }
271 }
272
273 // compute parity
274 uint8_t padding[PADDING_SIZE] = {0};
275
276 uint8_t parity[PARITY_SIZE] = {
277 coefficients[0]*message[0x0] +
278 coefficients[1]*message[0x2] +
279 coefficients[2]*message[0x4] +
280 coefficients[3]*message[0x6] +
281 coefficients[4]*padding[0x0],
282
283 coefficients[0]*message[0x1] +
284 coefficients[1]*message[0x3] +
285 coefficients[2]*message[0x5] +
286 coefficients[3]*message[0x7] +
287 coefficients[4]*padding[0x1],
288 };
289
290 // write blocks
291 open_disks (address); // open disk files, ensuring their integrity
292 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
293 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
294 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
295 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
296 fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]);
297 fprintf (disks[5], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
298 close_disks ();
299 } break;
300 } free (line);
301 }
302
303 return EXIT_SUCCESS;
304}
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 @@
1// yana
2// M1M2 M3M4 M5M6 M7M8 0000 0000 P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <unistd.h>
6#include <stdint.h>
7#include <stdbool.h>
8#include <string.h>
9#include <ctype.h>
10#include <locale.h>
11
12#define DISK_COUNT 7
13#define MESSAGE_SIZE 8
14#define BLOCK_SIZE 2
15#define PADDING_SIZE 4
16
17// uint8_t coefficients[DISK_COUNT - 1] = { 1, 3, 5, 7, 11, 13 };
18uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, 1, 1, 1 };
19
20#define DISK_SIZE 0x40
21
22#define POPCOUNT __builtin_popcount
23#define CTZ __builtin_ctz
24
25enum command {
26 COMMAND_NONE,
27 COMMAND_WRITE,
28 COMMAND_READ,
29};
30
31FILE *disks[DISK_COUNT];
32
33#ifndef WIN32
34#define LINE_SIZE 5
35#else
36#define LINE_SIZE 6
37static ssize_t
38getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
39 register char c;
40 register char *cs = NULL;
41 register int length = 0;
42 while ((c = getc (stream)) != EOF) {
43 cs = (char *) realloc (cs, ++length + 1);
44 if ((*(cs + length - 1) = c) == '\n') {
45 *(cs + length) = '\0';
46 break;
47 }
48 }
49
50 // return the allocated memory if lineptr is null
51 if ((*lineptr) == NULL) {
52 *lineptr = cs;
53 } else {
54 // check if enough memory is allocated
55 if ((length + 1) < *n)
56 *lineptr = (char *) realloc (*lineptr, length + 1);
57 memcpy (*lineptr, cs, length);
58 free (cs);
59 }
60
61 return (ssize_t) (*n = strlen (*lineptr));
62}
63#endif
64
65static void
66open_disks (uint8_t address)
67{
68 uint16_t bad_disks = 0;
69 for (int i = 0; i < DISK_COUNT; ++i) {
70 char filename[6];
71 snprintf (filename, 6, "disk%d", i);
72 disks[i] = fopen (filename, "r+");
73 if (!disks[i]) { // disk file was deleted
74 disks[i] = fopen (filename, "w+");
75 if (!disks[i]) {
76 fprintf (stderr, "ERROR - unable to open file: %s\n", filename);
77 exit (EXIT_FAILURE);
78 }
79
80 fprintf (stderr, "WARNING - found bad disk that is missing: %s\n", filename);
81 bad_disks |= 1 << i;
82 } else { // disk file wasn't deleted
83 fseek (disks[i], 0, SEEK_END);
84 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
85 fprintf (stderr, "WARNING - found corrupted disk: %s\n", filename);
86 bad_disks |= 1 << i;
87 fclose (disks[i]);
88 disks[i] = fopen (filename, "w+");
89 } else rewind (disks[i]);
90 }
91 }
92
93 // there were bad disks
94 int bad_disk_count = POPCOUNT (bad_disks);
95 if (bad_disk_count == 1) { // recompute lost disk
96 fprintf (stderr, "NOTICE - only 1 bad disk, recomputing it again \n");
97 int bad_disk = CTZ (bad_disks);
98
99 for (int j = 0; j < DISK_SIZE; ++j) {
100 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
101
102 // read blocks from good disks
103 bool empty = false;
104 for (int k = 0; k < DISK_COUNT; ++k) {
105 if (k == bad_disk) continue;
106
107 int c = fgetc (disks[k]);
108 if (c == ' ') {
109 empty = true;
110 fgetc (disks[k]);
111
112 fgetc (disks[k]);
113 fgetc (disks[k]);
114 } else {
115 ungetc (c, disks[k]);
116 for (int l = 0; l < BLOCK_SIZE; ++l) {
117 fscanf (disks[k], "%02hhX", &block_bytes[k*BLOCK_SIZE + l]);
118 }
119 } fgetc (disks[k]);
120 }
121
122 if (empty) {
123 fprintf (disks[bad_disk], " \n");
124 continue;
125 }
126
127 // compute lost block
128 if (bad_disk == DISK_COUNT - 1) { // lost parity
129 for (int l = 0; l < BLOCK_SIZE; ++l)
130 block_bytes[bad_disk*BLOCK_SIZE + l] = 0x00;
131 for (int k = 0; k < DISK_COUNT - 1; ++k) {
132 for (int l = 0; l < BLOCK_SIZE; ++l)
133 block_bytes[bad_disk*BLOCK_SIZE + l] +=
134 coefficients[k]*block_bytes[k*BLOCK_SIZE + l];
135 }
136 } else { // lost data
137 for (int l = 0; l < BLOCK_SIZE; ++l)
138 block_bytes[bad_disk*BLOCK_SIZE + l] = block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + l]/coefficients[bad_disk];
139 for (int k = 0; k < DISK_COUNT - 1; ++k) {
140 if (k == bad_disk) continue;
141 for (int l = 0; l < BLOCK_SIZE; ++l)
142 block_bytes[bad_disk*BLOCK_SIZE + l] -=
143 coefficients[k]*block_bytes[k*BLOCK_SIZE + l]/coefficients[bad_disk];
144 // printf ("%02hhX\n", coefficients[k]*block_bytes[k*BLOCK_SIZE + 0]/coefficients[bad_disk]);
145 }
146 }
147
148 // write lost block
149 for (int l = 0; l < BLOCK_SIZE; ++l)
150 fprintf (disks[bad_disk], "%02hhX", block_bytes[bad_disk*BLOCK_SIZE + l]);
151 fprintf (disks[bad_disk], "\n");
152 }
153 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
154 fprintf (stderr, "ERROR - more than one bad disks, reinitializing the array with new disks \n");
155
156 for (int i = 0; i < DISK_COUNT; ++i) {
157 for (int j = 0; j < DISK_SIZE; ++j)
158 fputs (" \n", disks[i]);
159 }
160 }
161
162 // position head for writing/reading message
163 for (int i = 0; i < DISK_COUNT; ++i)
164 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
165}
166
167static void
168close_disks (void)
169{
170 for (int i = 0; i < DISK_COUNT; ++i)
171 fclose (disks[i]);
172}
173
174int
175main (void)
176{
177 fprintf (stderr, "Initialization RAID 4 on 7 disks. The message size is 8 bytes. \n");
178 // check disk integrity on startup
179 open_disks (0);
180 close_disks ( );
181
182 for (;;) {
183 char *head;
184 int assigned;
185 int scanned;
186
187 // read whole line
188 printf ("> ");
189 char *line = NULL;
190 size_t line_size = 0;
191 scanned = getline (&line, &line_size, stdin);
192 if (scanned == -1)
193 exit (EXIT_SUCCESS);
194 else if (scanned == 1)
195 continue;
196 head = line;
197
198 uint8_t address; { // scan address
199 assigned = sscanf (head, "%hhu%n", &address, &scanned);
200 if (assigned != 1 || address >= DISK_SIZE) {
201 fprintf(stderr, "ERROR - address not in set [0; 64) \n");
202 continue;
203 } head += scanned;
204 }
205
206 enum command command; { // scan command
207 while (*head == ' ') head += 1;
208 if (!strncmp (head, "read", 4)) {
209 head += 4;
210 command = COMMAND_READ;
211 } else if (!strncmp (head, "write", 5)) {
212 head += 5;
213 command = COMMAND_WRITE;
214 }
215 if (!isspace(*head))
216 command = COMMAND_NONE;
217 }
218
219 switch (command) {
220 case COMMAND_NONE: {
221 fprintf(stderr, "ERROR - there is no such command, try entering read or write \n");
222 continue;
223 } break;
224 case COMMAND_READ: {
225 uint8_t message[MESSAGE_SIZE];
226 uint8_t parity [ BLOCK_SIZE];
227 uint8_t padding[PADDING_SIZE];
228
229 while (isspace (*head)) {
230 head += 1;
231 if (*head == '\n' ||
232 *head == '\r') {
233 *head = '\0';
234 }
235 }
236 if (*head) {
237 fprintf (stderr, "ERROR - extraneous data after the message: %s", head);
238 continue;
239 }
240
241 open_disks (address);
242
243 int c = fgetc (disks[0]);
244 if (c == ' ') {
245 close_disks ();
246 printf ("The line is empty \n");
247 break;
248 } ungetc (c, disks[0]);
249
250 // parse out message
251 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
252 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
253 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
254 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
255 fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]);
256 fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x2], &padding[0x3]);
257 fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
258 close_disks ();
259
260 printf ("%02hhX%02hhX "
261 "%02hhX%02hhX "
262 "%02hhX%02hhX "
263 "%02hhX%02hhX\n",
264 message[0x0], message[0x1],
265 message[0x2], message[0x3],
266 message[0x4], message[0x5],
267 message[0x6], message[0x7]);
268 } break;
269 case COMMAND_WRITE: {
270 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
271 int message_size = 0;
272
273 while (*head == ' ' ||
274 *head == '\t') ++head;
275 const char *invalid = NULL;
276 size_t len = 0;
277 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
278 if (!strchr ("0123456789abcdefABCDEF", *c)) {
279 invalid = c;
280 break;
281 } len += 1;
282 } if (invalid) {
283 fprintf (stderr, "ERROR - message contains invalid character `%c'\n", *invalid);
284 break;
285 } if (len != 2*MESSAGE_SIZE) {
286 fprintf (stderr, "ERROR - expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
287 break;
288 }
289
290 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
291 message_size < MESSAGE_SIZE) {
292 head += scanned;
293 message_size += 1;
294 }
295 }
296
297 uint8_t padding[PADDING_SIZE] = {0};
298
299 // compute parity
300 uint8_t parity[BLOCK_SIZE] = {
301 coefficients[0]*message[0x0] +
302 coefficients[1]*message[0x2] +
303 coefficients[2]*message[0x4] +
304 coefficients[3]*message[0x6] +
305 coefficients[4]*padding[0x0] +
306 coefficients[5]*padding[0x2],
307
308 coefficients[0]*message[0x1] +
309 coefficients[1]*message[0x3] +
310 coefficients[2]*message[0x5] +
311 coefficients[3]*message[0x7] +
312 coefficients[4]*padding[0x1] +
313 coefficients[5]*padding[0x3],
314 };
315
316 // write blocks
317 open_disks (address); // open disk files, ensuring their integrity
318 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
319 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
320 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
321 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
322 fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]);
323 fprintf (disks[5], "%02hhX%02hhX\n", padding[0x2], padding[0x3]);
324 fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
325 close_disks ();
326 } break;
327 }
328 free (line);
329 line = NULL;
330 }
331
332 return EXIT_SUCCESS;
333}
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 @@
1// gdluck
2// M1M2M3M4M5 M6M7M8M9MA P1P2P3P4P5
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <string.h>
7#include <ctype.h>
8
9#define DISK_COUNT 3
10#define MESSAGE_SIZE 10
11#define BLOCK_SIZE 5
12
13#define DISK_SIZE 0x40
14
15#define POPCOUNT __builtin_popcount
16#define CTZ __builtin_ctz
17
18enum command {
19 COMMAND_WRITE,
20 COMMAND_READ,
21};
22
23FILE *disks[DISK_COUNT];
24
25#ifndef WIN32
26#define LINE_SIZE 11
27#else
28#define LINE_SIZE 12
29static ssize_t
30getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
31 register char c;
32 register char *cs = NULL;
33 register int length = 0;
34 while ((c = getc (stream)) != EOF) {
35 cs = (char *) realloc (cs, ++length + 1);
36 if ((*(cs + length - 1) = c) == '\n') {
37 *(cs + length) = '\0';
38 break;
39 }
40 }
41
42 // return the allocated memory if lineptr is null
43 if ((*lineptr) == NULL) {
44 *lineptr = cs;
45 } else {
46 // check if enough memory is allocated
47 if ((length + 1) < *n)
48 *lineptr = (char *) realloc (*lineptr, length + 1);
49 memcpy (*lineptr, cs, length);
50 free (cs);
51 }
52
53 return (ssize_t) (*n = strlen (*lineptr));
54}
55#endif
56
57static void
58open_disks (uint8_t address)
59{
60 uint16_t bad_disks = 0;
61 for (int i = 0; i < DISK_COUNT; ++i) {
62 char filename[] = "disk0";
63 filename[strlen (filename) - 1] += i;
64 disks[i] = fopen (filename, "r+");
65 if (!disks[i]) { // disk file was deleted
66 disks[i] = fopen (filename, "w+");
67 if (!disks[i]) {
68 fprintf (stderr, "error: can't open the file: %s\n", filename);
69 exit (EXIT_FAILURE);
70 }
71
72 fprintf (stderr, "warning: a bad disk has been found (missing): %s\n", filename);
73 bad_disks |= 1 << i;
74 } else { // disk file wasn't deleted
75 fseek (disks[i], 0, SEEK_END);
76 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
77 fprintf (stderr, "warning: a bad disk has been found (corrupted): %s\n", filename);
78 bad_disks |= 1 << i;
79 } rewind (disks[i]);
80 }
81 }
82
83 // there were bad disks
84 int bad_disk_count = POPCOUNT (bad_disks);
85 if (bad_disk_count == 1) { // recompute lost disk
86 fprintf (stderr, "information: there is only 1 bad disk, recomputing it...\n");
87 int bad_disk = CTZ (bad_disks);
88
89 for (int j = 0; j < DISK_SIZE; ++j) {
90 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
91
92 // read blocks from good disks
93 for (int k = 0; k < DISK_COUNT; ++k) {
94 if (k == bad_disk) continue;
95 fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX\n",
96 &block_bytes[k*BLOCK_SIZE + 0],
97 &block_bytes[k*BLOCK_SIZE + 1],
98 &block_bytes[k*BLOCK_SIZE + 2],
99 &block_bytes[k*BLOCK_SIZE + 3],
100 &block_bytes[k*BLOCK_SIZE + 4]);
101 }
102
103 // compute lost block
104 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
105 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
106 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
107 block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00;
108 block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00;
109 for (int k = 0; k < DISK_COUNT; ++k) {
110 if (k == bad_disk) continue;
111 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
112 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
113 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
114 block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3];
115 block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4];
116 }
117
118 // write lost block
119 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX\n",
120 block_bytes[bad_disk*BLOCK_SIZE + 0],
121 block_bytes[bad_disk*BLOCK_SIZE + 1],
122 block_bytes[bad_disk*BLOCK_SIZE + 2],
123 block_bytes[bad_disk*BLOCK_SIZE + 3],
124 block_bytes[bad_disk*BLOCK_SIZE + 4]);
125 }
126 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
127 fprintf (stderr, "error: too many damaged disks, reinitializing the array with new disks...\n");
128
129 for (int i = 0; i < DISK_COUNT; ++i) {
130 for (int j = 0; j < DISK_SIZE; ++j)
131 fputs ("0000000000\n", disks[i]);
132 }
133 }
134
135 // position head for writing/reading message
136 for (int i = 0; i < DISK_COUNT; ++i)
137 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
138}
139
140static void
141close_disks (void)
142{
143 for (int i = 0; i < DISK_COUNT; ++i)
144 fclose (disks[i]);
145}
146
147int
148main (void)
149{
150 fprintf (stderr, "information: initializing RAID 4 on 3 disks with 10 byte messages...\n");
151 // check disk integrity on startup
152 open_disks (0);
153 close_disks ( );
154
155 for (;;) {
156 char *line = NULL;
157 size_t line_size = 0;
158 const char *head;
159 int assigned;
160 int scanned;
161
162 // read whole line
163 printf ("> ");
164 scanned = getline (&line, &line_size, stdin);
165 if (scanned == -1)
166 exit (EXIT_SUCCESS);
167 else if (scanned == 1)
168 continue;
169 head = line;
170
171 uint8_t address; { // scan address
172 assigned = sscanf (head, "%hhx%n", &address, &scanned);
173 if (assigned != 1 || address >= DISK_SIZE) {
174 fprintf(stderr, "error: the address is not in set [0x00; 0x40)\n");
175 continue;
176 } head += scanned;
177 }
178
179 enum command command; { // scan command
180 char command_buffer[6] = {0};
181 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
182 if (assigned != 1 ||
183 (!strncmp (command_buffer, "read", 4) &&
184 !strncmp (command_buffer, "write", 5))) {
185 fprintf(stderr, "error: the command is not in set (read; write)\n");
186 continue;
187 } head += scanned;
188 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
189 }
190
191 switch (command) {
192 case COMMAND_READ: {
193 uint8_t message[MESSAGE_SIZE];
194 uint8_t parity [ BLOCK_SIZE];
195
196 // parse out message
197 open_disks (address);
198 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4]);
199 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x5], &message[0x6], &message[0x7], &message[0x8], &message[0x9]);
200 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4]);
201 close_disks ();
202
203 printf ("%02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX%02hhX\n",
204 message[0x0], message[0x1], message[0x2], message[0x3], message[0x4],
205 message[0x5], message[0x6], message[0x7], message[0x8], message[0x9]);
206 } break;
207 case COMMAND_WRITE: {
208 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
209 int message_size = 0;
210 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
211 message_size < MESSAGE_SIZE) {
212 head += scanned;
213 message_size += 1;
214 }
215
216 if (message_size != MESSAGE_SIZE) {
217 fprintf (stderr, "error: the message is too short, expected %d bytes, received %d\n",
218 MESSAGE_SIZE, message_size);
219 continue;
220 }
221
222 while (isspace (*head)) ++head;
223 if (*head) {
224 fprintf (stderr, "error: junk after message: %c...\n", *head);
225 continue;
226 }
227 }
228
229 // compute parity
230 uint8_t parity[BLOCK_SIZE] = {
231 message[0x0] ^ message[0x5],
232 message[0x1] ^ message[0x6],
233 message[0x2] ^ message[0x7],
234 message[0x3] ^ message[0x8],
235 message[0x4] ^ message[0x9],
236 };
237
238 // write blocks
239 open_disks (address); // open disk files, ensuring their integrity
240 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4]);
241 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x5], message[0x6], message[0x7], message[0x8], message[0x9]);
242 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4]);
243 close_disks ();
244 } break;
245 } free (line);
246 }
247
248 return EXIT_SUCCESS;
249}
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 @@
1// Darya
2// M1M2 M3M4 M5M6 M7M8 M9MA P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 6
11#define MESSAGE_SIZE 10
12#define PARITY_SIZE 2
13#define BLOCK_SIZE 2
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_NONE,
22 COMMAND_WRITE,
23 COMMAND_READ,
24};
25
26FILE *disks[DISK_COUNT];
27
28#ifndef WIN32
29#define LINE_SIZE 5
30#else
31#define LINE_SIZE 6
32static ssize_t
33getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
34 register char c;
35 register char *cs = NULL;
36 register int length = 0;
37 while ((c = getc (stream)) != EOF) {
38 cs = (char *) realloc (cs, ++length + 1);
39 if ((*(cs + length - 1) = c) == '\n') {
40 *(cs + length) = '\0';
41 break;
42 }
43 }
44
45 // return the allocated memory if lineptr is null
46 if ((*lineptr) == NULL) {
47 *lineptr = cs;
48 } else {
49 // check if enough memory is allocated
50 if ((length + 1) < *n)
51 *lineptr = (char *) realloc (*lineptr, length + 1);
52 memcpy (*lineptr, cs, length);
53 free (cs);
54 }
55
56 return (ssize_t) (*n = strlen (*lineptr));
57}
58#endif
59
60static void
61open_disks (uint8_t address)
62{
63 uint16_t bad_disks = 0;
64 for (int i = 0; i < DISK_COUNT; ++i) {
65 char filename[] = "disk0";
66 filename[strlen (filename) - 1] += i;
67 disks[i] = fopen (filename, "r+");
68 if (!disks[i]) { // disk file was deleted
69 disks[i] = fopen (filename, "w+");
70 if (!disks[i]) {
71 fprintf (stderr, "ERROR: the file could not be opened: %s\n", filename);
72 exit (EXIT_FAILURE);
73 }
74
75 fprintf (stderr, "WARNING: an inaccessible disk has been detected %s\n", filename);
76 bad_disks |= 1 << i;
77 } else { // disk file wasn't deleted
78 fseek (disks[i], 0, SEEK_END);
79 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
80 fprintf (stderr, "WARNING: a corrupted disk has been detected: %s\n", filename);
81 bad_disks |= 1 << i;
82 } rewind (disks[i]);
83 }
84 }
85
86 // there were bad disks
87 int bad_disk_count = POPCOUNT (bad_disks);
88 if (bad_disk_count == 1) { // recompute lost disk
89 fprintf (stderr, "INFORMATION: there is only 1 inaccessible disk, a re-calculation is being performed.\n");
90 int bad_disk = CTZ (bad_disks);
91
92 for (int j = 0; j < DISK_SIZE; ++j) {
93 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
94
95 // read blocks from good disks
96 bool empty = false;
97 for (int k = 0; k < DISK_COUNT; ++k) {
98 if (k == bad_disk) continue;
99 int c = fgetc (disks[k]);
100 if (c == ' ') {
101 fgetc (disks[k]);
102
103 fgetc (disks[k]);
104 fgetc (disks[k]);
105 empty = true;
106 } else {
107 ungetc (c, disks[k]);
108 fscanf (disks[k], "%02hhX%02hhX",
109 &block_bytes[k*BLOCK_SIZE + 0],
110 &block_bytes[k*BLOCK_SIZE + 1]);
111 } fgetc (disks[k]);
112 }
113
114 if (empty) { // address empty
115 fprintf (disks[bad_disk], " \n");
116 continue;
117 }
118
119 // compute lost block
120 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
121 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
122 for (int k = 0; k < DISK_COUNT; ++k) {
123 if (k == bad_disk) continue;
124 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0];
125 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1];
126 }
127
128 // write lost block
129 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
130 block_bytes[bad_disk*BLOCK_SIZE + 0],
131 block_bytes[bad_disk*BLOCK_SIZE + 1]);
132 }
133 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
134 fprintf (stderr, "ERROR: there are too many inaccessible disks, the array is being initialized with new disks.\n");
135
136 for (int i = 0; i < DISK_COUNT; ++i) {
137 for (int j = 0; j < DISK_SIZE; ++j)
138 fputs (" \n", disks[i]);
139 }
140 }
141
142 // position head for writing/reading message
143 for (int i = 0; i < DISK_COUNT; ++i)
144 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
145}
146
147static void
148close_disks (void)
149{
150 for (int i = 0; i < DISK_COUNT; ++i)
151 fclose (disks[i]);
152}
153
154int
155main (void)
156{
157 fprintf (stderr, "INFORMATION: initialization of RAID 4 on 6 disks with messages of 10 bytes in length. \n");
158 // check disk integrity on startup
159 open_disks (0);
160 close_disks ( );
161
162 for (;;) {
163 char *line = NULL;
164 size_t line_size = 0;
165 const char *head;
166 int assigned;
167 int scanned;
168
169 // read whole line
170 printf ("> ");
171 scanned = getline (&line, &line_size, stdin);
172 if (scanned == -1)
173 exit (EXIT_SUCCESS);
174 else if (scanned == 1)
175 continue;
176 head = line;
177
178 uint8_t address; { // scan address
179 assigned = sscanf (head, "%hhx%n", &address, &scanned);
180 if (assigned != 1 || address >= DISK_SIZE) {
181 fprintf(stderr, "ERROR: the address is not in the range [0x00; 0x40)\n");
182 continue;
183 } head += scanned;
184 }
185
186 enum command command; { // scan command
187 while (*head == ' ') head += 1;
188 if (!strncmp (head, "read", 4)) {
189 head += 4;
190 command = COMMAND_READ;
191 } else if (!strncmp (head, "write", 5)) {
192 head += 5;
193 command = COMMAND_WRITE;
194 }
195 if (!isspace(*head))
196 command = COMMAND_NONE;
197 }
198
199 switch (command) {
200 case COMMAND_NONE: {
201 fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n");
202 continue;
203 } break;
204 case COMMAND_READ: {
205 uint8_t message[MESSAGE_SIZE];
206 uint8_t parity [ PARITY_SIZE];
207
208 // parse out message
209 open_disks (address);
210 int c = fgetc (disks[0]);
211 if (c == ' ') {
212 close_disks ();
213 printf ("EMPTY!\n");
214 break;
215 } ungetc (c, disks[0]);
216 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
217 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
218 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
219 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
220 fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]);
221 fscanf (disks[5], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
222 close_disks ();
223
224 printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n",
225 message[0x0], message[0x1],
226 message[0x2], message[0x3],
227 message[0x4], message[0x5],
228 message[0x6], message[0x7],
229 message[0x8], message[0x9]);
230 } break;
231 case COMMAND_WRITE: {
232 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
233 int message_size = 0;
234
235 while (*head == ' ' ||
236 *head == '\t') ++head;
237 const char *invalid = NULL;
238 size_t len = 0;
239 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
240 if (!strchr ("0123456789abcdefABCDEF", *c)) {
241 invalid = c;
242 break;
243 } len += 1;
244 } if (invalid) {
245 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
246 break;
247 } if (len != 2*MESSAGE_SIZE) {
248 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
249 break;
250 }
251
252 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
253 message_size < MESSAGE_SIZE) {
254 head += scanned;
255 message_size += 1;
256 }
257 }
258
259 // compute parity
260 uint8_t parity[PARITY_SIZE] = {
261 message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8],
262 message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9],
263 };
264
265 // write blocks
266 open_disks (address); // open disk files, ensuring their integrity
267 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
268 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
269 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
270 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
271 fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]);
272 fprintf (disks[5], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
273 close_disks ();
274 } break;
275 } free (line);
276 }
277
278 return EXIT_SUCCESS;
279}
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 @@
1// kira
2// M1M2 M3M4 M5M6 M7M8 M9MA 0000 P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 7
11#define MESSAGE_SIZE 10
12#define PARITY_SIZE 2
13#define BLOCK_SIZE 2
14#define PADDING_SIZE 2
15
16#define DISK_SIZE 0x40
17
18#define POPCOUNT __builtin_popcount
19#define CTZ __builtin_ctz
20
21enum command {
22 COMMAND_NONE,
23 COMMAND_WRITE,
24 COMMAND_READ,
25};
26
27FILE *disks[DISK_COUNT];
28
29#ifndef WIN32
30#define LINE_SIZE 5
31#else
32#define LINE_SIZE 6
33static ssize_t
34getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
35 register char c;
36 register char *cs = NULL;
37 register int length = 0;
38 while ((c = getc (stream)) != EOF) {
39 cs = (char *) realloc (cs, ++length + 1);
40 if ((*(cs + length - 1) = c) == '\n') {
41 *(cs + length) = '\0';
42 break;
43 }
44 }
45
46 // return the allocated memory if lineptr is null
47 if ((*lineptr) == NULL) {
48 *lineptr = cs;
49 } else {
50 // check if enough memory is allocated
51 if ((length + 1) < *n)
52 *lineptr = (char *) realloc (*lineptr, length + 1);
53 memcpy (*lineptr, cs, length);
54 free (cs);
55 }
56
57 return (ssize_t) (*n = strlen (*lineptr));
58}
59#endif
60
61static void
62open_disks (uint8_t address)
63{
64 uint16_t bad_disks = 0;
65 for (int i = 0; i < DISK_COUNT; ++i) {
66 char filename[] = "disk0";
67 filename[strlen (filename) - 1] += i;
68 disks[i] = fopen (filename, "r+");
69 if (!disks[i]) { // disk file was deleted
70 disks[i] = fopen (filename, "w+");
71 if (!disks[i]) {
72 fprintf (stderr, "error: can't open the file: %s\n", filename);
73 exit (EXIT_FAILURE);
74 }
75
76 fprintf (stderr, "warning: a bad disk has been found (missing): %s\n", filename);
77 bad_disks |= 1 << i;
78 } else { // disk file wasn't deleted
79 fseek (disks[i], 0, SEEK_END);
80 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
81 fprintf (stderr, "warning: a bad disk has been found (corrupted): %s\n", filename);
82 bad_disks |= 1 << i;
83 } rewind (disks[i]);
84 }
85 }
86
87 // there were bad disks
88 int bad_disk_count = POPCOUNT (bad_disks);
89 if (bad_disk_count == 1) { // recompute lost disk
90 fprintf (stderr, "information: there is only 1 bad disk, recomputing it...\n");
91 int bad_disk = CTZ (bad_disks);
92
93 for (int j = 0; j < DISK_SIZE; ++j) {
94 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
95
96 // read blocks from good disks
97 bool empty = false;
98 for (int k = 0; k < DISK_COUNT; ++k) {
99 if (k == bad_disk) continue;
100 int c = fgetc (disks[k]);
101 if (c == ' ') {
102 fgetc (disks[k]);
103
104 fgetc (disks[k]);
105 fgetc (disks[k]);
106 empty = true;
107 } else {
108 ungetc (c, disks[k]);
109 fscanf (disks[k], "%02hhX%02hhX",
110 &block_bytes[k*BLOCK_SIZE + 0],
111 &block_bytes[k*BLOCK_SIZE + 1]);
112 } fgetc (disks[k]);
113 }
114
115 if (empty) { // address empty
116 fprintf (disks[bad_disk], " \n");
117 continue;
118 }
119
120 // compute lost block
121 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
122 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
123 for (int k = 0; k < DISK_COUNT; ++k) {
124 if (k == bad_disk) continue;
125 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0];
126 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1];
127 }
128
129 // write lost block
130 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
131 block_bytes[bad_disk*BLOCK_SIZE + 0],
132 block_bytes[bad_disk*BLOCK_SIZE + 1]);
133 }
134 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
135 fprintf (stderr, "error: too many damaged disks, reinitializing the array with new disks...\n");
136
137 for (int i = 0; i < DISK_COUNT; ++i) {
138 for (int j = 0; j < DISK_SIZE; ++j)
139 fputs (" \n", disks[i]);
140 }
141 }
142
143 // position head for writing/reading message
144 for (int i = 0; i < DISK_COUNT; ++i)
145 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
146}
147
148static void
149close_disks (void)
150{
151 for (int i = 0; i < DISK_COUNT; ++i)
152 fclose (disks[i]);
153}
154
155int
156main (void)
157{
158 fprintf (stderr, "information: initializing RAID 4 on 7 disks with 10 byte messages...\n");
159 // check disk integrity on startup
160 open_disks (0);
161 close_disks ( );
162
163 for (;;) {
164 char *line = NULL;
165 size_t line_size = 0;
166 const char *head;
167 int assigned;
168 int scanned;
169
170 // read whole line
171 printf ("> ");
172 scanned = getline (&line, &line_size, stdin);
173 if (scanned == -1)
174 exit (EXIT_SUCCESS);
175 else if (scanned == 1)
176 continue;
177 head = line;
178
179 uint8_t address; { // scan address
180 assigned = sscanf (head, "%hhx%n", &address, &scanned);
181 if (assigned != 1 || address >= DISK_SIZE) {
182 fprintf(stderr, "error: the address is not in set [0x00; 0x40)\n");
183 continue;
184 } head += scanned;
185 }
186
187 enum command command; { // scan command
188 while (*head == ' ') head += 1;
189 if (!strncmp (head, "read", 4)) {
190 head += 4;
191 command = COMMAND_READ;
192 } else if (!strncmp (head, "write", 5)) {
193 head += 5;
194 command = COMMAND_WRITE;
195 }
196 if (!isspace(*head))
197 command = COMMAND_NONE;
198 }
199
200 switch (command) {
201 case COMMAND_NONE: {
202 fprintf(stderr, "Invalid command, must be on of (read, write)\n");
203 continue;
204 } break;
205 case COMMAND_READ: {
206 uint8_t message[MESSAGE_SIZE];
207 uint8_t parity [ PARITY_SIZE];
208 uint8_t padding[PADDING_SIZE];
209
210 // parse out message
211 open_disks (address);
212 int c = fgetc (disks[0]);
213 if (c == ' ') {
214 close_disks ();
215 printf ("no data at this address!\n");
216 break;
217 } ungetc (c, disks[0]);
218 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
219 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
220 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
221 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
222 fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]);
223 fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]);
224 fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
225 close_disks ();
226
227 printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n",
228 message[0x0], message[0x1],
229 message[0x2], message[0x3],
230 message[0x4], message[0x5],
231 message[0x6], message[0x7],
232 message[0x8], message[0x9]);
233 } break;
234 case COMMAND_WRITE: {
235 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
236 int message_size = 0;
237
238 while (*head == ' ' ||
239 *head == '\t') ++head;
240 const char *invalid = NULL;
241 size_t len = 0;
242 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
243 if (!strchr ("0123456789abcdefABCDEF", *c)) {
244 invalid = c;
245 break;
246 } len += 1;
247 } if (invalid) {
248 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
249 break;
250 } if (len != 2*MESSAGE_SIZE) {
251 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
252 break;
253 }
254
255 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
256 message_size < MESSAGE_SIZE) {
257 head += scanned;
258 message_size += 1;
259 }
260 }
261
262 uint8_t padding[PADDING_SIZE] = {0};
263
264 // compute parity
265 uint8_t parity[PARITY_SIZE] = {
266 message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ padding[0x0],
267 message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ padding[0x1],
268 };
269
270 // write blocks
271 open_disks (address); // open disk files, ensuring their integrity
272 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
273 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
274 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
275 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
276 fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]);
277 fprintf (disks[5], "%02hhX%02hhX\n", padding[0x0], padding[0x1]);
278 fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
279 close_disks ();
280 } break;
281 } free (line);
282 }
283
284 return EXIT_SUCCESS;
285}
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 @@
1// Dash
2// M1M2M3M4 M5M6M7M8 M9MAMBMC P1P2P3P4
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 4
11#define MESSAGE_SIZE 12
12#define PARITY_SIZE 4
13#define BLOCK_SIZE 4
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 9
29#else
30#define LINE_SIZE 10
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "ERROR! Try another file \n");
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "WARNING: MISSING DISK\n");
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "WARNING: CORRUPTED DISK \n");
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "INFO: detected only one faulty disk; recalculating it\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104
105 fgetc (disks[k]);
106 fgetc (disks[k]);
107
108 fgetc (disks[k]);
109 fgetc (disks[k]);
110 empty = true;
111 } else {
112 ungetc (c, disks[k]);
113 fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX",
114 &block_bytes[k*BLOCK_SIZE + 0],
115 &block_bytes[k*BLOCK_SIZE + 1],
116 &block_bytes[k*BLOCK_SIZE + 2],
117 &block_bytes[k*BLOCK_SIZE + 3]);
118 } fgetc (disks[k]);
119 }
120
121 if (empty) { // address empty
122 fprintf (disks[bad_disk], " \n");
123 continue;
124 }
125
126 // compute lost block
127 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
128 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
129 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
130 block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00;
131 for (int k = 0; k < DISK_COUNT; ++k) {
132 if (k == bad_disk) continue;
133 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
134 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
135 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
136 block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3];
137 }
138
139 // write lost block
140 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX\n",
141 block_bytes[bad_disk*BLOCK_SIZE + 0],
142 block_bytes[bad_disk*BLOCK_SIZE + 1],
143 block_bytes[bad_disk*BLOCK_SIZE + 2],
144 block_bytes[bad_disk*BLOCK_SIZE + 3]);
145 }
146 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
147 fprintf (stderr, "ERROR: Exceeding the maximum number of faulty disks.\n");
148
149 for (int i = 0; i < DISK_COUNT; ++i) {
150 char filename[] = "disk0";
151 filename[strlen (filename) - 1] += i;
152 fclose (disks[i]);
153 disks[i] = fopen (filename, "w+");
154 for (int j = 0; j < DISK_SIZE; ++j)
155 fputs (" \n", disks[i]);
156 }
157 }
158
159 // position head for writing/reading message
160 for (int i = 0; i < DISK_COUNT; ++i)
161 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
162}
163
164static void
165close_disks (void)
166{
167 for (int i = 0; i < DISK_COUNT; ++i)
168 fclose (disks[i]);
169}
170
171int
172main (void)
173{
174 fprintf (stderr, "INFO: Setting up RAID 4 with 4 disks, each handling 12-byte messages \n");
175 // check disk integrity on startup
176 open_disks (0);
177 close_disks ( );
178
179 for (;;) {
180 char *line = NULL;
181 size_t line_size = 0;
182
183 const char *head;
184 int assigned;
185 int scanned;
186
187 // read whole line
188 printf ("> ");
189 scanned = getline (&line, &line_size, stdin);
190 if (scanned == -1)
191 exit (EXIT_SUCCESS);
192 else if (scanned == 1)
193 continue;
194 head = line;
195
196 uint8_t address; { // scan address
197 assigned = sscanf (head, "%hhx%n", &address, &scanned);
198 if (assigned != 1 || address >= DISK_SIZE) {
199 fprintf(stderr, "ERROR: outside the range [0x00; 0x40) \n");
200 continue;
201 } head += scanned;
202 }
203
204 enum command command; { // scan command
205 char command_buffer[6] = {0};
206 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
207 if (assigned != 1 ||
208 (!strncmp (command_buffer, "read", 4) &&
209 !strncmp (command_buffer, "write", 5))) {
210 fprintf(stderr, "ERROR: The provided command is not valid. Please use either 'read' or 'write\n");
211 continue;
212 } head += scanned;
213 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
214 }
215
216 switch (command) {
217 case COMMAND_READ: {
218 uint8_t message[MESSAGE_SIZE];
219 uint8_t parity [ PARITY_SIZE];
220
221 // parse out message
222 open_disks (address);
223 int c = fgetc (disks[0]);
224 if (c == ' ') {
225 close_disks ();
226 printf ("No data!\n");
227 break;
228 } ungetc (c, disks[0]);
229 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3]);
230 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x4], &message[0x5], &message[0x6], &message[0x7]);
231 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x8], &message[0x9], &message[0xA], &message[0xB]);
232 fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3]);
233 close_disks ();
234
235 printf ("%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX\n",
236 message[0x0], message[0x1], message[0x2], message[0x3],
237 message[0x4], message[0x5], message[0x6], message[0x7],
238 message[0x8], message[0x9], message[0xA], message[0xB]);
239 } break;
240 case COMMAND_WRITE: {
241 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
242 int message_size = 0;
243
244 while (*head == ' ' ||
245 *head == '\t') ++head;
246 const char *invalid = NULL;
247 size_t len = 0;
248 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
249 if (!strchr ("0123456789abcdefABCDEF", *c)) {
250 invalid = c;
251 break;
252 } len += 1;
253 } if (invalid) {
254 fprintf (stderr, "ERROR: message contains invalid character '%c'\n", *invalid);
255 break;
256 } if (len != 2*MESSAGE_SIZE) {
257 fprintf (stderr, "ERROR: expected %d hex-digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
258 break;
259 }
260
261 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
262 message_size < MESSAGE_SIZE) {
263 head += scanned;
264 message_size += 1;
265 }
266 }
267
268 // compute parity
269 uint8_t parity[PARITY_SIZE] = {
270 message[0x0] ^ message[0x4] ^ message[0x8],
271 message[0x1] ^ message[0x5] ^ message[0x9],
272 message[0x2] ^ message[0x6] ^ message[0xA],
273 message[0x3] ^ message[0x7] ^ message[0xB],
274 };
275
276 // write blocks
277 open_disks (address); // open disk files, ensuring their integrity
278 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3]);
279 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", message[0x4], message[0x5], message[0x6], message[0x7]);
280 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", message[0x8], message[0x9], message[0xA], message[0xB]);
281 fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3]);
282 close_disks ();
283 } break;
284 }
285 free (line);
286 }
287
288 return EXIT_SUCCESS;
289}
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 @@
1// Dash
2// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 5
11#define MESSAGE_SIZE 12
12#define PARITY_SIZE 3
13#define BLOCK_SIZE 3
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 7
29#else
30#define LINE_SIZE 8
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104
105 fgetc (disks[k]);
106 fgetc (disks[k]);
107 empty = true;
108 } else {
109 ungetc (c, disks[k]);
110 fscanf (disks[k], "%02hhX%02hhX%02hhX",
111 &block_bytes[k*BLOCK_SIZE + 0],
112 &block_bytes[k*BLOCK_SIZE + 1],
113 &block_bytes[k*BLOCK_SIZE + 2]);
114 } fgetc (disks[k]);
115 }
116
117 // compute lost block
118 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
119 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
120 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
121 for (int k = 0; k < DISK_COUNT; ++k) {
122 if (k == bad_disk) continue;
123 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
124 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
125 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
126 }
127
128 if (empty) { // address empty
129 fprintf (disks[bad_disk], " \n");
130 continue;
131 }
132
133 // write lost block
134 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n",
135 block_bytes[bad_disk*BLOCK_SIZE + 0],
136 block_bytes[bad_disk*BLOCK_SIZE + 1],
137 block_bytes[bad_disk*BLOCK_SIZE + 2]);
138 }
139 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
140 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
141
142 for (int i = 0; i < DISK_COUNT; ++i) {
143 char filename[] = "disk0";
144 filename[strlen (filename) - 1] += i;
145 fclose (disks[i]);
146 disks[i] = fopen (filename, "w+");
147 for (int j = 0; j < DISK_SIZE; ++j)
148 fputs (" \n", disks[i]);
149 }
150 }
151
152 // position head for writing/reading message
153 for (int i = 0; i < DISK_COUNT; ++i)
154 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
155}
156
157static void
158close_disks (void)
159{
160 for (int i = 0; i < DISK_COUNT; ++i)
161 fclose (disks[i]);
162}
163
164int
165main (void)
166{
167 fprintf (stderr, "INFO: initializing RAID 4 on 4 disks with 12 byte messages...\n");
168 // check disk integrity on startup
169 open_disks (0);
170 close_disks ( );
171
172 for (;;) {
173 char *line = NULL;
174 size_t line_size = 0;
175
176 const char *head;
177 int assigned;
178 int scanned;
179
180 // read whole line
181 printf ("> ");
182 scanned = getline (&line, &line_size, stdin);
183 if (scanned == -1)
184 exit (EXIT_SUCCESS);
185 else if (scanned == 1)
186 continue;
187 head = line;
188
189 uint8_t address; { // scan address
190 assigned = sscanf (head, "%hhx%n", &address, &scanned);
191 if (assigned != 1 || address >= DISK_SIZE) {
192 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
193 continue;
194 } head += scanned;
195 }
196
197 enum command command; { // scan command
198 char command_buffer[6] = {0};
199 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
200 if (assigned != 1 ||
201 (!strncmp (command_buffer, "read", 4) &&
202 !strncmp (command_buffer, "write", 5))) {
203 fprintf(stderr, "ERROR: command not in set (read; write)\n");
204 continue;
205 } head += scanned;
206 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
207 }
208
209 switch (command) {
210 case COMMAND_READ: {
211 uint8_t message[MESSAGE_SIZE];
212 uint8_t parity [ PARITY_SIZE];
213
214 // parse out message
215 open_disks (address);
216 int c = fgetc (disks[0]);
217 if (c == ' ') {
218 close_disks ();
219 printf ("Empty!\n");
220 break;
221 } ungetc (c, disks[0]);
222 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
223 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
224 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
225 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
226 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
227 close_disks ();
228
229 printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX %02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n",
230 message[0x0], message[0x1], message[0x2],
231 message[0x3], message[0x4], message[0x5],
232 message[0x6], message[0x7], message[0x8],
233 message[0x9], message[0xA], message[0xB]);
234 } break;
235 case COMMAND_WRITE: {
236 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
237 int message_size = 0;
238
239 while (*head == ' ' ||
240 *head == '\t') ++head;
241 const char *invalid = NULL;
242 size_t len = 0;
243 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
244 if (!strchr ("0123456789abcdefABCDEF", *c)) {
245 invalid = c;
246 break;
247 } len += 1;
248 } if (invalid) {
249 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
250 break;
251 } if (len != 2*MESSAGE_SIZE) {
252 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
253 break;
254 }
255
256 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
257 message_size < MESSAGE_SIZE) {
258 head += scanned;
259 message_size += 1;
260 }
261 }
262
263 // compute parity
264 uint8_t parity[PARITY_SIZE] = {
265 message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9],
266 message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA],
267 message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB],
268 };
269
270 // write blocks
271 open_disks (address); // open disk files, ensuring their integrity
272 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
273 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
274 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
275 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
276 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
277 close_disks ();
278 } break;
279 }
280 free (line);
281 }
282
283 return EXIT_SUCCESS;
284}
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 @@
1// Dash
2// M1M2 M3M4 M5M6 M7M8 M9MA MBMC P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 7
11#define MESSAGE_SIZE 12
12#define PARITY_SIZE 2
13#define BLOCK_SIZE 2
14#define DISK_SIZE 0x40
15
16#define POPCOUNT __builtin_popcount
17#define CTZ __builtin_ctz
18
19#ifndef WIN32
20#define LINE_SIZE 5
21#else
22#define LINE_SIZE 6
23static ssize_t
24getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
25 register char c;
26 register char *cs = NULL;
27 register int length = 0;
28 while ((c = getc (stream)) != EOF) {
29 cs = (char *) realloc (cs, ++length + 1);
30 if ((*(cs + length - 1) = c) == '\n') {
31 *(cs + length) = '\0';
32 break;
33 }
34 }
35
36 // return the allocated memory if lineptr is null
37 if ((*lineptr) == NULL) {
38 *lineptr = cs;
39 } else {
40 // check if enough memory is allocated
41 if ((length + 1) < *n)
42 *lineptr = (char *) realloc (*lineptr, length + 1);
43 memcpy (*lineptr, cs, length);
44 free (cs);
45 }
46
47 return (ssize_t) (*n = strlen (*lineptr));
48}
49#endif
50
51enum command {
52 COMMAND_WRITE,
53 COMMAND_READ,
54};
55
56FILE *disks[DISK_COUNT];
57
58static void
59open_disks (uint8_t address)
60{
61 uint16_t bad_disks = 0;
62 for (int i = 0; i < DISK_COUNT; ++i) {
63 char filename[] = "disk0";
64 filename[strlen (filename) - 1] += i;
65 disks[i] = fopen (filename, "r+");
66 if (!disks[i]) {
67 disks[i] = fopen (filename, "w+");
68 if (!disks[i]) {
69 fprintf (stderr, "Error: can't open file: %s\n", filename);
70 exit (EXIT_FAILURE);
71 }
72
73 fprintf (stderr, "Warning: found bad disk (missing): %s\n", filename);
74 bad_disks |= 1 << i;
75 } else {
76 fseek (disks[i], 0, SEEK_END);
77 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) {
78 fprintf (stderr, "Warning: found bad disk (corrupted): %s\n", filename);
79 bad_disks |= 1 << i;
80 } rewind (disks[i]);
81 }
82 }
83
84 int bad_disk_count = POPCOUNT (bad_disks);
85 if (bad_disk_count == 1) {
86 fprintf (stderr, "there is just 1 bad disk, recomputing it\n");
87 int bad_disk = CTZ (bad_disks);
88
89 for (int j = 0; j < DISK_SIZE; ++j) {
90 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
91
92 bool empty = false;
93 for (int k = 0; k < DISK_COUNT; ++k) {
94 if (k == bad_disk) continue;
95 int c = fgetc (disks[k]);
96 if (c == ' ') {
97 fgetc (disks[k]);
98 fgetc (disks[k]);
99 fgetc (disks[k]);
100 empty = true;
101 } else {
102 ungetc (c, disks[k]);
103 fscanf (disks[k], "%02hhX%02hhX",
104 &block_bytes[k*BLOCK_SIZE + 0],
105 &block_bytes[k*BLOCK_SIZE + 1]);
106 } fgetc (disks[k]);
107 }
108
109 if (empty) {
110 fprintf (disks[bad_disk], " \n");
111 continue;
112 }
113
114 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
115 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
116 for (int k = 0; k < DISK_COUNT; ++k) {
117 if (k == bad_disk) continue;
118 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*2 + 0];
119 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*2 + 1];
120 }
121
122 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
123 block_bytes[bad_disk*BLOCK_SIZE + 0],
124 block_bytes[bad_disk*BLOCK_SIZE + 1]);
125 }
126 } else if (bad_disk_count > 1) {
127 fprintf (stderr, "Error: too many bad disks, reinitializing the array with new disks\n");
128
129 for (int i = 0; i < DISK_COUNT; ++i) {
130 for (int j = 0; j < DISK_SIZE; ++j)
131 fputs (" \n", disks[i]);
132 }
133 }
134
135 for (int i = 0; i < DISK_COUNT; ++i)
136 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
137}
138
139static void
140close_disks (void)
141{
142 for (int i = 0; i < DISK_COUNT; ++i)
143 fclose (disks[i]);
144}
145
146int
147main (void)
148{
149 fprintf (stderr, "initializing RAID 4 on 7 disks with 12 byte messages\n");
150 open_disks (0);
151 close_disks ( );
152
153 for (;;) {
154 char *line = NULL;
155 size_t line_size = 0;
156
157 const char *head;
158 int assigned;
159 int scanned;
160
161 printf ("> ");
162 scanned = getline (&line, &line_size, stdin);
163 if (scanned == -1)
164 exit (EXIT_SUCCESS);
165 else if (scanned == 1)
166 continue;
167 head = line;
168
169 uint8_t address; {
170 assigned = sscanf (head, "%hhx%n", &address, &scanned);
171 if (assigned != 1 || address >= DISK_SIZE) {
172 fprintf(stderr, "Error: address not in set [0x00; 0x40)\n");
173 continue;
174 } head += scanned;
175 }
176
177 enum command command; {
178 char command_buffer[6] = {0};
179 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
180 if (assigned != 1 ||
181 (!strncmp (command_buffer, "read", 4) &&
182 !strncmp (command_buffer, "write", 5))) {
183 fprintf(stderr, "Error: command not in set (use commands write, read)\n");
184 continue;
185 } head += scanned;
186 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
187 }
188
189 switch (command) {
190 case COMMAND_READ: {
191 uint8_t message[MESSAGE_SIZE];
192 uint8_t parity [ PARITY_SIZE];
193
194 open_disks (address);
195 int c = fgetc (disks[0]);
196 if (c == ' ') {
197 close_disks ();
198 printf ("There is no data\n");
199 break;
200 } ungetc (c, disks[0]);
201 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
202 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
203 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
204 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
205 fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]);
206 fscanf (disks[5], "%02hhX%02hhX\n", &message[0xA], &message[0xB]);
207 fscanf (disks[6], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
208 close_disks ();
209
210 printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n",
211 message[0x0], message[0x1],
212 message[0x2], message[0x3],
213 message[0x4], message[0x5],
214 message[0x6], message[0x7],
215 message[0x8], message[0x9],
216 message[0xA], message[0xB]);
217 } break;
218 case COMMAND_WRITE: {
219 uint8_t message[MESSAGE_SIZE] = {0}; {
220 int message_size = 0;
221
222 while (*head == ' ' ||
223 *head == '\t') ++head;
224 const char *invalid = NULL;
225 size_t len = 0;
226 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
227 if (!strchr ("0123456789abcdefABCDEF", *c)) {
228 invalid = c;
229 break;
230 } len += 1;
231 } if (invalid) {
232 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
233 break;
234 } if (len != 2*MESSAGE_SIZE) {
235 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
236 break;
237 }
238 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
239 message_size < MESSAGE_SIZE) {
240 head += scanned;
241 message_size += 1;
242 }
243 }
244
245 uint8_t parity[PARITY_SIZE] = {
246 message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ message[0xA],
247 message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ message[0xB],
248 };
249
250 open_disks (address);
251 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
252 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
253 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
254 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
255 fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]);
256 fprintf (disks[5], "%02hhX%02hhX\n", message[0xA], message[0xB]);
257 fprintf (disks[6], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
258 close_disks ();
259 } break;
260 } free (line);
261 }
262
263 return EXIT_SUCCESS;
264}
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 @@
1// Dash
2// M1M2M3M4M5 M6M7M8M9MA MBMCMDME00 P1P2P3P4P5
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 4
11#define MESSAGE_SIZE 14
12#define PARITY_SIZE 5
13#define BLOCK_SIZE 5
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 11
29#else
30#define LINE_SIZE 12
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "mistake: the file could not be opened: %s\n", filename);
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "warning: a faulty disk has been found or the disk is missing: %s\n", filename);
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "warning: a faulty/damaged disk has been detected: %s\n", filename);
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "message: only one faulty disk has been detected, I am detecting it\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104
105 fgetc (disks[k]);
106 fgetc (disks[k]);
107
108 fgetc (disks[k]);
109 fgetc (disks[k]);
110
111 fgetc (disks[k]);
112 fgetc (disks[k]);
113 empty = true;
114 } else {
115 ungetc (c, disks[k]);
116 fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX",
117 &block_bytes[k*BLOCK_SIZE + 0],
118 &block_bytes[k*BLOCK_SIZE + 1],
119 &block_bytes[k*BLOCK_SIZE + 2],
120 &block_bytes[k*BLOCK_SIZE + 3],
121 &block_bytes[k*BLOCK_SIZE + 4]);
122 } fgetc (disks[k]);
123 }
124
125 if (empty) { // address empty
126 fprintf (disks[bad_disk], " \n");
127 continue;
128 }
129
130 // compute lost block
131 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
132 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
133 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
134 block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00;
135 block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00;
136 for (int k = 0; k < DISK_COUNT; ++k) {
137 if (k == bad_disk) continue;
138 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
139 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
140 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
141 block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3];
142 block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4];
143 }
144
145 // write lost block
146 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX\n",
147 block_bytes[bad_disk*BLOCK_SIZE + 0],
148 block_bytes[bad_disk*BLOCK_SIZE + 1],
149 block_bytes[bad_disk*BLOCK_SIZE + 2],
150 block_bytes[bad_disk*BLOCK_SIZE + 3],
151 block_bytes[bad_disk*BLOCK_SIZE + 4]);
152 }
153 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
154 fprintf (stderr, "mistake: there are too many bad disks, we are re-initializing arrays with new disks\n");
155
156 for (int i = 0; i < DISK_COUNT; ++i) {
157 char filename[] = "disk0";
158 filename[strlen (filename) - 1] += i;
159 fclose (disks[i]);
160 disks[i] = fopen (filename, "w+");
161 for (int j = 0; j < DISK_SIZE; ++j)
162 fputs (" \n", disks[i]);
163 }
164 }
165
166 // position head for writing/reading message
167 for (int i = 0; i < DISK_COUNT; ++i)
168 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
169}
170
171static void
172close_disks (void)
173{
174 for (int i = 0; i < DISK_COUNT; ++i)
175 fclose (disks[i]);
176}
177
178int
179main (void)
180{
181 fprintf (stderr, "message: Initializing RAID 4 with XOR and 14 byte messages on 4 disks\n");
182 // check disk integrity on startup
183 open_disks (0);
184 close_disks ( );
185
186 for (;;) {
187 const char *head;
188 int assigned;
189 int scanned;
190
191 // read whole line
192 printf ("> ");
193 char *line = NULL;
194 size_t line_size = 0;
195 scanned = getline (&line, &line_size, stdin);
196 if (scanned == -1)
197 exit (EXIT_SUCCESS);
198 else if (scanned == 1)
199 continue;
200 head = line;
201
202 uint8_t address; { // scan address
203 assigned = sscanf (head, "%hhX%n", &address, &scanned);
204 if (assigned != 1 || address >= DISK_SIZE) {
205 fprintf(stderr, "mistake: the address must belong to [0x00; 0x40)\n");
206 continue;
207 } head += scanned;
208 }
209
210 enum command command; { // scan command
211 char command_buffer[6] = {0};
212 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
213 if (assigned != 1 ||
214 (!strncmp (command_buffer, "read", 4) &&
215 !strncmp (command_buffer, "write", 5))) {
216 fprintf(stderr, "mistake: only the read and write commands are available\n");
217 continue;
218 } head += scanned;
219 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
220 }
221
222 switch (command) {
223 case COMMAND_READ: {
224 uint8_t message[MESSAGE_SIZE];
225 uint8_t parity [ PARITY_SIZE];
226 uint8_t reserved[1];
227
228 // parse out message
229 open_disks (address);
230 int c = fgetc (disks[0]);
231 if (c == ' ') {
232 close_disks ();
233 printf ("No data!\n");
234 break;
235 } ungetc (c, disks[0]);
236 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message [0x4]);
237 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x5], &message[0x6], &message[0x7], &message[0x8], &message [0x9]);
238 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0xA], &message[0xB], &message[0xC], &message[0xD], &reserved[0x0]);
239 fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4]);
240 close_disks ();
241
242 printf ("%02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX\n",
243 message[0x0], message[0x1], message[0x2], message[0x3], message[0x4],
244 message[0x5], message[0x6], message[0x7], message[0x8], message[0x9],
245 message[0xA], message[0xB], message[0xC], message[0xD]);
246 } break;
247 case COMMAND_WRITE: {
248 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
249 int message_size = 0;
250
251 while (*head == ' ' ||
252 *head == '\t') ++head;
253 const char *invalid = NULL;
254 size_t len = 0;
255 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
256 if (!strchr ("0123456789abcdefABCDEF", *c)) {
257 invalid = c;
258 break;
259 } len += 1;
260 } if (invalid) {
261 fprintf (stderr, "mistake: message contains invalid character `%c'\n", *invalid);
262 break;
263 } if (len != 2*MESSAGE_SIZE) {
264 fprintf (stderr, "mistake: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
265 break;
266 }
267
268 while (sscanf (head, "%2hhX%n", &message[message_size], &scanned) == 1 &&
269 message_size < MESSAGE_SIZE) {
270 head += scanned;
271 message_size += 1;
272 }
273 }
274
275 uint8_t reserved[1] = {0};
276
277 // compute parity
278 uint8_t parity[PARITY_SIZE] = {
279 message[0x0] ^ message[0x5] ^ message [0xA],
280 message[0x1] ^ message[0x6] ^ message [0xB],
281 message[0x2] ^ message[0x7] ^ message [0xC],
282 message[0x3] ^ message[0x8] ^ message [0xD],
283 message[0x4] ^ message[0x9] ^ reserved[0x0],
284 };
285
286 // write blocks
287 open_disks (address); // open disk files, ensuring their integrity
288 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message [0x4]);
289 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x5], message[0x6], message[0x7], message[0x8], message [0x9]);
290 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0xA], message[0xB], message[0xC], message[0xD], reserved[0x0]);
291 fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4]);
292 close_disks ();
293 } break;
294 } free (line);
295 }
296
297 return EXIT_SUCCESS;
298}
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 @@
1// Dash
2// M1M2M3M4 M5M6M7M8 M9MAMBMC MDME0000 P1P2P3P4
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 5
11#define MESSAGE_SIZE 14
12#define PARITY_SIZE 4
13#define BLOCK_SIZE 4
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 9
29#else
30#define LINE_SIZE 10
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "ERROR: The program could not open the file you are trying to use: %s\n", filename);
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "WARNING: the system has detected that one of the disks in the array is missing: %s\n", filename);
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "WARNING: the system has detected that one of the disks in the array is corrupted: %s\n", filename);
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104
105 fgetc (disks[k]);
106 fgetc (disks[k]);
107
108 fgetc (disks[k]);
109 fgetc (disks[k]);
110 empty = true;
111 } else {
112 ungetc (c, disks[k]);
113 fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX",
114 &block_bytes[k*BLOCK_SIZE + 0],
115 &block_bytes[k*BLOCK_SIZE + 1],
116 &block_bytes[k*BLOCK_SIZE + 2],
117 &block_bytes[k*BLOCK_SIZE + 3]);
118 }
119 }
120
121 if (empty) { // address empty
122 fprintf (disks[bad_disk], " \n");
123 continue;
124 }
125
126 // compute lost block
127 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
128 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
129 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
130 block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00;
131 for (int k = 0; k < DISK_COUNT; ++k) {
132 if (k == bad_disk) continue;
133 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
134 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
135 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
136 block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3];
137 }
138
139 // write lost block
140 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX\n",
141 block_bytes[bad_disk*BLOCK_SIZE + 0],
142 block_bytes[bad_disk*BLOCK_SIZE + 1],
143 block_bytes[bad_disk*BLOCK_SIZE + 2],
144 block_bytes[bad_disk*BLOCK_SIZE + 3]);
145 }
146 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
147 fprintf (stderr, "ERROR: Too many drives in the array have failed and the system is trying to rebuild the array with new drives\n");
148
149 for (int i = 0; i < DISK_COUNT; ++i) {
150 char filename[] = "disk0";
151 filename[strlen (filename) - 1] += i;
152 fclose (disks[i]);
153 disks[i] = fopen (filename, "w+");
154 for (int j = 0; j < DISK_SIZE; ++j)
155 fputs (" \n", disks[i]);
156 }
157 }
158
159 // position head for writing/reading message
160 for (int i = 0; i < DISK_COUNT; ++i)
161 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
162}
163
164static void
165close_disks (void)
166{
167 for (int i = 0; i < DISK_COUNT; ++i)
168 fclose (disks[i]);
169}
170
171int
172main (void)
173{
174 fprintf (stderr, "INFO: initializing RAID 4 on 5 disks with 14 byte messages...\n");
175 // check disk integrity on startup
176 open_disks (0);
177 close_disks ( );
178
179 for (;;) {
180 char *line = NULL;
181 size_t line_size = 0;
182 const char *head;
183 int assigned;
184 int scanned;
185
186 // read whole line
187 printf ("> ");
188 scanned = getline (&line, &line_size, stdin);
189 if (scanned == -1)
190 exit (EXIT_SUCCESS);
191 else if (scanned == 1)
192 continue;
193 head = line;
194
195 uint8_t address; { // scan address
196 assigned = sscanf (head, "%hhx%n", &address, &scanned);
197 if (assigned != 1 || address >= DISK_SIZE) {
198 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
199 continue;
200 } head += scanned;
201 }
202
203 enum command command; { // scan command
204 char command_buffer[6] = {0};
205 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
206 if (assigned != 1 ||
207 (!strncmp (command_buffer, "read", 4) &&
208 !strncmp (command_buffer, "write", 5))) {
209 fprintf(stderr, "ERROR: command not in set (read; write)\n");
210 continue;
211 } head += scanned;
212 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
213 }
214
215 switch (command) {
216 case COMMAND_READ: {
217 uint8_t message[MESSAGE_SIZE];
218 uint8_t parity [ PARITY_SIZE];
219 uint8_t reserved[2];
220
221 // parse out message
222 open_disks (address);
223 int c = fgetc (disks[0]);
224 if (c == ' ') {
225 close_disks ();
226 printf ("No data!\n");
227 break;
228 } ungetc (c, disks[0]);
229 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message [0x2], &message [0x3]);
230 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x4], &message[0x5], &message [0x6], &message [0x7]);
231 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", &message[0x8], &message[0x9], &message [0xA], &message [0xB]);
232 fscanf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", &message[0xC], &message[0xD], &reserved[0x0], &reserved[0x1]);
233 fscanf (disks[4], "%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3]);
234 close_disks ();
235
236 printf ("%02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX\n",
237 message[0x0], message[0x1], message[0x2], message[0x3],
238 message[0x4], message[0x5], message[0x6], message[0x7],
239 message[0x8], message[0x9], message[0xA], message[0xB],
240 message[0xC], message[0xD]);
241 } break;
242 case COMMAND_WRITE: {
243 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
244 int message_size = 0;
245
246 while (*head == ' ' ||
247 *head == '\t') ++head;
248 const char *invalid = NULL;
249 size_t len = 0;
250 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
251 if (!strchr ("0123456789abcdefABCDEF", *c)) {
252 invalid = c;
253 break;
254 } len += 1;
255 } if (invalid) {
256 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
257 break;
258 } if (len != 2*MESSAGE_SIZE) {
259 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
260 break;
261 }
262
263 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
264 message_size < MESSAGE_SIZE) {
265 head += scanned;
266 message_size += 1;
267 }
268 }
269
270 uint8_t reserved[2] = {0};
271
272 // compute parity
273 uint8_t parity[PARITY_SIZE] = {
274 message[0x0] ^ message[0x4] ^ message[0x8] ^ message [0xC],
275 message[0x1] ^ message[0x5] ^ message[0x9] ^ message [0xD],
276 message[0x2] ^ message[0x6] ^ message[0xA] ^ reserved[0x0],
277 message[0x3] ^ message[0x7] ^ message[0xB] ^ reserved[0x1],
278 };
279
280 // write blocks
281 open_disks (address); // open disk files, ensuring their integrity
282 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message [0x2], message [0x3]);
283 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX\n", message[0x4], message[0x5], message [0x6], message [0x7]);
284 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX\n", message[0x8], message[0x9], message [0xA], message [0xB]);
285 fprintf (disks[3], "%02hhX%02hhX%02hhX%02hhX\n", message[0xC], message[0xD], reserved[0x0], reserved[0x1]);
286 fprintf (disks[4], "%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3]);
287 close_disks ();
288 } break;
289 } free (line);
290 }
291
292 return EXIT_SUCCESS;
293}
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 @@
1// Dash
2// M1M2 M3M4 M5M6 M7M8 M9MA MBMC MDME P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 8
11#define MESSAGE_SIZE 14
12#define PARITY_SIZE 2
13#define BLOCK_SIZE 2
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 5
29#else
30#define LINE_SIZE 6
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "file opening error: %s\n", filename);
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "missing disk is detected: %s\n", filename);
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "damaged disk is detected: %s\n", filename);
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "only 1 bad disk detected, recalculate it...\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104 empty = true;
105 } else {
106 ungetc (c, disks[k]);
107 fscanf (disks[k], "%02hhX%02hhX",
108 &block_bytes[k*BLOCK_SIZE + 0],
109 &block_bytes[k*BLOCK_SIZE + 1]);
110 } fgetc (disks[k]);
111 }
112
113 if (empty) { // address empty
114 fprintf (disks[bad_disk], " \n");
115 continue;
116 }
117
118 // compute lost block
119 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
120 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
121 for (int k = 0; k < DISK_COUNT; ++k) {
122 if (k == bad_disk) continue;
123 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
124 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
125 }
126
127 // write lost block
128 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
129 block_bytes[bad_disk*BLOCK_SIZE + 0],
130 block_bytes[bad_disk*BLOCK_SIZE + 1]);
131 }
132 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
133 fprintf (stderr, "many unsuitable disks are detected, the array is reinitialized with new disks...\n");
134
135 for (int i = 0; i < DISK_COUNT; ++i) {
136 char filename[] = "disk0";
137 filename[strlen (filename) - 1] += i;
138 fclose (disks[i]);
139 disks[i] = fopen (filename, "w+");
140 for (int j = 0; j < DISK_SIZE; ++j)
141 fputs (" \n", disks[i]);
142 }
143 }
144
145 // position head for writing/reading message
146 for (int i = 0; i < DISK_COUNT; ++i)
147 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
148}
149
150static void
151close_disks (void)
152{
153 for (int i = 0; i < DISK_COUNT; ++i)
154 fclose (disks[i]);
155}
156
157int
158main (void)
159{
160 fprintf (stderr, "RAID 4 initialization on 5 disks with 14-byte messages...\n");
161 // check disk integrity on startup
162 open_disks (0);
163 close_disks ( );
164
165 for (;;) {
166 char *line = NULL;
167 size_t line_size = 0;
168 const char *head;
169 int assigned;
170 int scanned;
171
172 // read whole line
173 printf ("> ");
174 scanned = getline (&line, &line_size, stdin);
175 if (scanned == -1)
176 exit (EXIT_SUCCESS);
177 else if (scanned == 1)
178 continue;
179 head = line;
180
181 uint8_t address; { // scan address
182 assigned = sscanf (head, "%hhx%n", &address, &scanned);
183 if (assigned != 1 || address >= DISK_SIZE) {
184 fprintf(stderr, "invalid address, use: [0x00; 0x40)\n");
185 continue;
186 } head += scanned;
187 }
188
189 enum command command; { // scan command
190 char command_buffer[6] = {0};
191 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
192 if (assigned != 1 ||
193 (!strncmp (command_buffer, "read", 4) &&
194 !strncmp (command_buffer, "write", 5))) {
195 fprintf(stderr, "command does not exist: expected (read/write)\n");
196 continue;
197 } head += scanned;
198 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
199 }
200
201 switch (command) {
202 case COMMAND_READ: {
203 uint8_t message[MESSAGE_SIZE];
204 uint8_t parity [ PARITY_SIZE];
205
206 // parse out message
207 open_disks (address);
208 int c = fgetc (disks[0]);
209 if (c == ' ') {
210 close_disks ();
211 printf ("Empty!\n");
212 break;
213 } ungetc (c, disks[0]);
214 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
215 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
216 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
217 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
218 fscanf (disks[4], "%02hhX%02hhX\n", &message[0x8], &message[0x9]);
219 fscanf (disks[5], "%02hhX%02hhX\n", &message[0xA], &message[0xB]);
220 fscanf (disks[6], "%02hhX%02hhX\n", &message[0xC], &message[0xD]);
221 fscanf (disks[7], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
222 close_disks ();
223
224 printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n",
225 message[0x0], message[0x1],
226 message[0x2], message[0x3],
227 message[0x4], message[0x5],
228 message[0x6], message[0x7],
229 message[0x8], message[0x9],
230 message[0xA], message[0xB],
231 message[0xC], message[0xD]);
232 } break;
233 case COMMAND_WRITE: {
234 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
235 int message_size = 0;
236
237 while (*head == ' ' ||
238 *head == '\t') ++head;
239 const char *invalid = NULL;
240 size_t len = 0;
241 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
242 if (!strchr ("0123456789abcdefABCDEF", *c)) {
243 invalid = c;
244 break;
245 } len += 1;
246 } if (invalid) {
247 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
248 break;
249 } if (len != 2*MESSAGE_SIZE) {
250 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
251 break;
252 }
253
254 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
255 message_size < MESSAGE_SIZE) {
256 head += scanned;
257 message_size += 1;
258 }
259 }
260
261 // compute parity
262 uint8_t parity[PARITY_SIZE] = {
263 message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ message[0x8] ^ message[0xA] ^ message[0xC],
264 message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ message[0x9] ^ message[0xB] ^ message[0xD],
265 };
266
267 // write blocks
268 open_disks (address); // open disk files, ensuring their integrity
269 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
270 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
271 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
272 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
273 fprintf (disks[4], "%02hhX%02hhX\n", message[0x8], message[0x9]);
274 fprintf (disks[5], "%02hhX%02hhX\n", message[0xA], message[0xB]);
275 fprintf (disks[6], "%02hhX%02hhX\n", message[0xC], message[0xD]);
276 fprintf (disks[7], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
277 close_disks ();
278 } break;
279 } free (line);
280 }
281
282 return EXIT_SUCCESS;
283}
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 @@
1// nguyen
2// M1M2 M3M4 M5M6 M7M8 0000 0000 0000 P1P2
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 8
11#define MESSAGE_SIZE 8
12#define BLOCK_SIZE 2
13#define PADDING_SIZE 6
14
15#define DISK_SIZE 0x40
16
17#define POPCOUNT __builtin_popcount
18#define CTZ __builtin_ctz
19
20enum command {
21 COMMAND_WRITE,
22 COMMAND_READ,
23};
24
25FILE *disks[DISK_COUNT];
26
27#ifndef WIN32
28#define LINE_SIZE 5
29#else
30#define LINE_SIZE 6
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59static void
60open_disks (uint8_t address)
61{
62 uint16_t bad_disks = 0;
63 for (int i = 0; i < DISK_COUNT; ++i) {
64 char filename[] = "disk0";
65 filename[strlen (filename) - 1] += i;
66 disks[i] = fopen (filename, "r+");
67 if (!disks[i]) { // disk file was deleted
68 disks[i] = fopen (filename, "w+");
69 if (!disks[i]) {
70 fprintf (stderr, "file opening error: %s\n", filename);
71 exit (EXIT_FAILURE);
72 }
73
74 fprintf (stderr, "missing disk is detected: %s\n", filename);
75 bad_disks |= 1 << i;
76 } else { // disk file wasn't deleted
77 fseek (disks[i], 0, SEEK_END);
78 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
79 fprintf (stderr, "damaged disk is detected: %s\n", filename);
80 bad_disks |= 1 << i;
81 } rewind (disks[i]);
82 }
83 }
84
85 // there were bad disks
86 int bad_disk_count = POPCOUNT (bad_disks);
87 if (bad_disk_count == 1) { // recompute lost disk
88 fprintf (stderr, "only 1 bad disk detected, recalculate it...\n");
89 int bad_disk = CTZ (bad_disks);
90
91 for (int j = 0; j < DISK_SIZE; ++j) {
92 uint8_t block_bytes[BLOCK_SIZE*DISK_COUNT];
93
94 // read blocks from good disks
95 bool empty = false;
96 for (int k = 0; k < DISK_COUNT; ++k) {
97 if (k == bad_disk) continue;
98 int c = fgetc (disks[k]);
99 if (c == ' ') {
100 fgetc (disks[k]);
101
102 fgetc (disks[k]);
103 fgetc (disks[k]);
104 empty = true;
105 } else {
106 ungetc (c, disks[k]);
107 fscanf (disks[k], "%02hhX%02hhX",
108 &block_bytes[k*BLOCK_SIZE + 0],
109 &block_bytes[k*BLOCK_SIZE + 1]);
110 } fgetc (disks[k]);
111 }
112
113 if (empty) { // address empty
114 for (int l = 0; l < BLOCK_SIZE; ++l) {
115 fprintf (disks[bad_disk], " ");
116 } fprintf (disks[bad_disk], "\n");
117 continue;
118 }
119
120 // compute lost block
121 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
122 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
123 for (int k = 0; k < DISK_COUNT; ++k) {
124 if (k == bad_disk) continue;
125 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
126 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
127 }
128
129 // write lost block
130 fprintf (disks[bad_disk], "%02hhX%02hhX\n",
131 block_bytes[bad_disk*BLOCK_SIZE + 0],
132 block_bytes[bad_disk*BLOCK_SIZE + 1]);
133 }
134 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
135 fprintf (stderr, "many unsuitable disks are detected, the array is reinitialized with new disks...\n");
136
137 for (int i = 0; i < DISK_COUNT; ++i) {
138 char filename[] = "disk0";
139 filename[strlen (filename) - 1] += i;
140 fclose (disks[i]);
141 disks[i] = fopen (filename, "w+");
142 for (int j = 0; j < DISK_SIZE; ++j)
143 fputs (" \n", disks[i]);
144 }
145 }
146
147 // position head for writing/reading message
148 for (int i = 0; i < DISK_COUNT; ++i)
149 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
150}
151
152static void
153close_disks (void)
154{
155 for (int i = 0; i < DISK_COUNT; ++i)
156 fclose (disks[i]);
157}
158
159int
160main (void)
161{
162 fprintf (stderr, "RAID 4 XOR initialization on 8 disks with 8-byte messages...\n");
163 // check disk integrity on startup
164 open_disks (0);
165 close_disks ( );
166
167 for (;;) {
168 char *line = NULL;
169 size_t line_size = 0;
170 const char *head;
171 int assigned;
172 int scanned;
173
174 // read whole line
175 printf ("> ");
176 scanned = getline (&line, &line_size, stdin);
177 if (scanned == -1)
178 exit (EXIT_SUCCESS);
179 else if (scanned == 1)
180 continue;
181 head = line;
182
183 uint8_t address; { // scan address
184 assigned = sscanf (head, "%hhx%n", &address, &scanned);
185 if (assigned != 1 || address >= DISK_SIZE) {
186 fprintf(stderr, "invalid address, use: [0x00; 0x40)\n");
187 continue;
188 } head += scanned;
189 }
190
191 enum command command; { // scan command
192 char command_buffer[6] = {0};
193 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
194 if (assigned != 1 ||
195 (!strncmp (command_buffer, "read", 4) &&
196 !strncmp (command_buffer, "write", 5))) {
197 fprintf(stderr, "command does not exist: expected (read/write)\n");
198 continue;
199 } head += scanned;
200 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
201 }
202
203 switch (command) {
204 case COMMAND_READ: {
205 uint8_t message[MESSAGE_SIZE];
206 uint8_t parity [ BLOCK_SIZE];
207 uint8_t padding[PADDING_SIZE];
208
209 // parse out message
210 open_disks (address);
211 int c = fgetc (disks[0]);
212 if (c == ' ') {
213 close_disks ();
214 printf ("EMPTY!\n");
215 break;
216 } ungetc (c, disks[0]);
217
218 fscanf (disks[0], "%02hhX%02hhX\n", &message[0x0], &message[0x1]);
219 fscanf (disks[1], "%02hhX%02hhX\n", &message[0x2], &message[0x3]);
220 fscanf (disks[2], "%02hhX%02hhX\n", &message[0x4], &message[0x5]);
221 fscanf (disks[3], "%02hhX%02hhX\n", &message[0x6], &message[0x7]);
222 fscanf (disks[4], "%02hhX%02hhX\n", &padding[0x0], &padding[0x1]);
223 fscanf (disks[5], "%02hhX%02hhX\n", &padding[0x2], &padding[0x3]);
224 fscanf (disks[6], "%02hhX%02hhX\n", &padding[0x4], &padding[0x5]);
225 fscanf (disks[7], "%02hhX%02hhX\n", &parity [0x0], &parity [0x1]);
226 close_disks ();
227
228 printf ("%02hhX%02hhX %02hhX%02hhX %02hhX%02hhX %02hhX%02hhX\n",
229 message[0x0], message[0x1],
230 message[0x2], message[0x3],
231 message[0x4], message[0x5],
232 message[0x6], message[0x7]);
233 } break;
234 case COMMAND_WRITE: {
235 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
236 int message_size = 0;
237
238 while (*head == ' ' ||
239 *head == '\t') ++head;
240 const char *invalid = NULL;
241 size_t len = 0;
242 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
243 if (!strchr ("0123456789abcdefABCDEF", *c)) {
244 invalid = c;
245 break;
246 } len += 1;
247 } if (invalid) {
248 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
249 break;
250 } if (len != 2*MESSAGE_SIZE) {
251 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
252 break;
253 }
254
255 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
256 message_size < MESSAGE_SIZE) {
257 head += scanned;
258 message_size += 1;
259 }
260 }
261
262 uint8_t padding[PADDING_SIZE] = {0};
263
264 // compute parity
265 uint8_t parity[BLOCK_SIZE] = {
266 message[0x0] ^ message[0x2] ^ message[0x4] ^ message[0x6] ^ padding[0x0] ^ padding[0x2] ^ padding[0x4],
267 message[0x1] ^ message[0x3] ^ message[0x5] ^ message[0x7] ^ padding[0x1] ^ padding[0x3] ^ padding[0x5],
268 };
269
270 // write blocks
271 open_disks (address); // open disk files, ensuring their integrity
272 fprintf (disks[0], "%02hhX%02hhX\n", message[0x0], message[0x1]);
273 fprintf (disks[1], "%02hhX%02hhX\n", message[0x2], message[0x3]);
274 fprintf (disks[2], "%02hhX%02hhX\n", message[0x4], message[0x5]);
275 fprintf (disks[3], "%02hhX%02hhX\n", message[0x6], message[0x7]);
276 fprintf (disks[4], "%02hhX%02hhX\n", padding[0x0], padding[0x1]);
277 fprintf (disks[5], "%02hhX%02hhX\n", padding[0x2], padding[0x3]);
278 fprintf (disks[6], "%02hhX%02hhX\n", padding[0x4], padding[0x5]);
279 fprintf (disks[7], "%02hhX%02hhX\n", parity [0x0], parity [0x1]);
280 close_disks ();
281 } break;
282 } free (line);
283 }
284
285 return EXIT_SUCCESS;
286}
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 @@
1// g, slock
2// M1M2M3M4M5 M6M7M8M9MA MBMCMDME00 P1P2P3P4P5
3// M1M2M3M4M5 M6M7M8M9MA P1P2P3P4P5 MBMCMDME00
4// M1M2M3M4M5 P1P2P3P4P5 M6M7M8M9MA MBMCMDME00
5// P1P2P3P4P5 M1M2M3M4M5 M6M7M8M9MA MBMCMDME00
6#include <stdlib.h>
7#include <stdio.h>
8#include <stdint.h>
9#include <stdbool.h>
10#include <string.h>
11#include <ctype.h>
12
13#define DISK_COUNT 4
14#define MESSAGE_SIZE 14
15#define PADDING_SIZE 1
16#define BLOCK_SIZE 5
17
18uint8_t coefficients[DISK_COUNT - 1] = { 1, 1, 1, };
19
20int shift_table[][DISK_COUNT] = {
21 { 0, 1, 2, 3, },
22 { 0, 1, 3, 2, },
23 { 0, 2, 3, 1, },
24 { 1, 2, 3, 0, },
25};
26
27#define DISK_SIZE 0x40
28#define POPCOUNT __builtin_popcount
29#define CTZ __builtin_ctz
30
31#ifndef WIN32
32#define LINE_SIZE (2*BLOCK_SIZE + 1)
33#else
34#define LINE_SIZE (2*BLOCK_SIZE + 2)
35static ssize_t
36getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
37 register char c;
38 register char *cs = NULL;
39 register int length = 0;
40 while ((c = getc (stream)) != EOF) {
41 cs = (char *) realloc (cs, ++length + 1);
42 if ((*(cs + length - 1) = c) == '\n') {
43 *(cs + length) = '\0';
44 break;
45 }
46 }
47
48 if ((*lineptr) == NULL) {
49 *lineptr = cs;
50 } else {
51 if ((length + 1) < *n)
52 *lineptr = (char *) realloc (*lineptr, length + 1);
53 memcpy (*lineptr, cs, length);
54 free (cs);
55 }
56
57 return (ssize_t) (*n = strlen (*lineptr));
58}
59#endif
60
61enum command {
62 COMMAND_WRITE,
63 COMMAND_READ,
64};
65
66FILE *disks[DISK_COUNT];
67
68static void
69recompute_bad_disk (int bad_disk)
70{
71 for (int j = 0; j < DISK_SIZE; ++j) {
72 uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE];
73 int shift = j % DISK_COUNT;
74 int logical_bad_disk;
75 bool empty = false;
76 for (int k = 0; k < DISK_COUNT; ++k) {
77 if (shift_table[shift][k] == bad_disk) {
78 logical_bad_disk = k;
79 continue;
80 }
81 for (int l = 0; l < BLOCK_SIZE; ++l) {
82 int c = fgetc (disks[shift_table[shift][k]]);
83 if (c == ' ') {
84 fgetc (disks[shift_table[shift][k]]);
85 empty = true;
86 } else {
87 ungetc (c, disks[shift_table[shift][k]]);
88 fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l)]);
89 }
90 } fgetc (disks[shift_table[shift][k]]);
91 }
92
93 if (empty) { // address empty
94 for (int l = 0; l < BLOCK_SIZE; ++l) {
95 fprintf (disks[bad_disk], " ");
96 } fprintf (disks[bad_disk], "\n");
97 continue;
98 } else if (logical_bad_disk % DISK_COUNT == DISK_COUNT - 1) { // lost parity
99 for (int l = 0; l < BLOCK_SIZE; ++l)
100 block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] = 0x00;
101 for (int k = 0, c = 0; k < DISK_COUNT; ++k) {
102 if (k == logical_bad_disk) continue;
103 for (int l = 0; l < BLOCK_SIZE; ++l)
104 block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] +=
105 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l)];
106 c += 1;
107 }
108 } else { // lost data
109 for (int l = 0; l < BLOCK_SIZE; ++l) {
110 block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] =
111 block_bytes[((DISK_COUNT - 1)*BLOCK_SIZE + l)];
112 }
113 for (int k = 0, c = 0; k < DISK_COUNT - 1; ++k) {
114 if (k == logical_bad_disk) continue;
115 for (int l = 0; l < BLOCK_SIZE; ++l)
116 block_bytes[(logical_bad_disk*BLOCK_SIZE + l)] -=
117 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l)];
118 c += 1;
119 }
120 }
121
122 for (int l = 0; l < BLOCK_SIZE; ++l) {
123 fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l)]);
124 } fprintf (disks[bad_disk], "\n");
125 }
126}
127
128static void
129open_disks (uint8_t address)
130{
131 uint16_t bad_disks = 0;
132 for (int i = 0; i < DISK_COUNT; ++i) {
133 char filename[] = "disk0";
134 filename[strlen (filename) - 1] += i;
135 disks[i] = fopen (filename, "r+");
136 if (!disks[i]) {
137 disks[i] = fopen (filename, "w+");
138 if (!disks[i]) {
139 fprintf (stderr, "Ошибка! Невозможно открыть файл: %s\n", filename);
140 exit (EXIT_FAILURE);
141 }
142
143 fprintf (stderr, "Предупреждение! Найден плохой диск: %s\n", filename);
144 bad_disks |= 1 << i;
145 } else { // disk file wasn't deleted
146 fseek (disks[i], 0, SEEK_END);
147 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
148 fprintf (stderr, "Предупреждение!Найден плохой диск: %s\n", filename);
149 fclose (disks[i]);
150 disks[i] = fopen (filename, "w+");
151 bad_disks |= 1 << i;
152 } else rewind (disks[i]);
153 }
154 }
155
156 int bad_disk_count = POPCOUNT (bad_disks);
157 if (bad_disk_count == 1) {
158 fprintf (stderr, "Повторный расчет, один диск плохой...\n");
159 int bad_disk = CTZ (bad_disks);
160 recompute_bad_disk (bad_disk);
161 } else if (bad_disk_count) {
162 fprintf (stderr, "Ошибка! Повторная инициализация массива с новыми дисками.\n");
163 for (int i = 0; i < DISK_COUNT; ++i) {
164 for (int j = 0; j < DISK_SIZE; ++j) {
165 for (int k = 0; k < BLOCK_SIZE; ++k) {
166 fputs (" ", disks[i]);
167 } fputs ("\n", disks[i]);
168 }
169 }
170 }
171
172 for (int i = 0; i < DISK_COUNT; ++i)
173 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
174}
175
176static void
177close_disks (void)
178{
179 for (int i = 0; i < DISK_COUNT; ++i)
180 fclose (disks[i]);
181}
182
183int
184main (void)
185{
186 fprintf (stderr, "Инициализация RAID 5 с POLY на 4 дисках с 14 байтовым сообщением.\n");
187
188 open_disks (0);
189 close_disks ( );
190
191 for (;;) {
192 char *line = NULL;
193 size_t line_size = 0;
194 const char *head;
195 int assigned;
196 int scanned;
197
198 printf ("> ");
199 scanned = getline (&line, &line_size, stdin);
200 if (scanned == -1)
201 exit (EXIT_SUCCESS);
202 else if (scanned == 1)
203 continue;
204 head = line;
205
206 uint8_t address; {
207 assigned = sscanf (head, "%hhu%n", &address, &scanned);
208 if (assigned != 1 || address >= DISK_SIZE) {
209 fprintf(stderr, "Ошибка! Адрес не входит в границы! [0; 64)\n");
210 continue;
211 } head += scanned;
212 }
213
214 enum command command; {
215 char command_buffer[6] = {0};
216 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
217 if (assigned != 1 ||
218 (!strncmp (command_buffer, "read", 4) &&
219 !strncmp (command_buffer, "write", 5))) {
220 fprintf(stderr, "Ошибка! Не корректная команда! (read; write)\n");
221 continue;
222 } head += scanned;
223 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
224 }
225
226 switch (command) {
227 case COMMAND_READ: {
228 uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE];
229 int shift = address % DISK_COUNT;
230 open_disks (address);
231 int c = fgetc (disks[0]);
232 if (c == ' ') {
233 close_disks ();
234 printf ("Пусто\n");
235 break;
236 } else ungetc (c, disks[0]);
237 for (int i = 0; i < DISK_COUNT; ++i) {
238 for (int j = 0; j < BLOCK_SIZE; ++j) {
239 fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[BLOCK_SIZE*i + j]);
240 }
241 } close_disks ();
242
243 for (int i = 0; i < DISK_COUNT - 1; ++i) {
244 for (int j = 0; j < BLOCK_SIZE; ++j) {
245 if (i == DISK_COUNT - 2 && j + PADDING_SIZE >= BLOCK_SIZE)
246 continue;
247 printf ("%02hhX", block_bytes[BLOCK_SIZE*i + j]);
248 }
249 printf (" ");
250 } printf ("\n");
251 } break;
252 case COMMAND_WRITE: {
253 uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + BLOCK_SIZE] = {0}; { // scan message
254 uint8_t *write_head = block_bytes;
255 int message_size = 0;
256 while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 &&
257 message_size < MESSAGE_SIZE) {
258 head += scanned;
259 message_size += 1;
260 write_head += 1;
261 if (message_size % ((DISK_COUNT - 1)*BLOCK_SIZE) == 0)
262 write_head += BLOCK_SIZE;
263 }
264
265 if (message_size != MESSAGE_SIZE) {
266 fprintf (stderr, "Ошибка! Сообщение слишком большое, ожидалось %d байт, восстановленно %d\n",
267 MESSAGE_SIZE, message_size);
268 continue;
269 }
270
271 while (isspace(*head)) ++head;
272 if (*head) {
273 fprintf (stderr, "Ошибка! Выводится мусор после сообщения: %c...\n", *head);
274 continue;
275 }
276 }
277
278 for (int i = 0; i < DISK_COUNT - 1; ++i) {
279 for (int j = 0; j < BLOCK_SIZE; ++j)
280 block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j];
281 }
282
283 int shift = address % DISK_COUNT;
284 open_disks (address);
285 for (int i = 0; i < DISK_COUNT; ++i) {
286 for (int j = 0; j < BLOCK_SIZE; ++j)
287 fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]);
288 fprintf (disks[shift_table[shift][i]], "\n");
289 } close_disks ();
290 } break;
291 } free (line);
292 }
293 return EXIT_SUCCESS;
294}
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 @@
1// North
2// M1M2M3M4M5M6 M7M8M9MAMBMC P1P2P3P4P5P6
3// M1M2M3M4M5M6 P1P2P3P4P5P6 M7M8M9MAMBMC
4// P1P2P3P4P5P6 M1M2M3M4M5M6 M7M8M9MAMBMC
5// M1M2M3M4M5M6 M7M8M9MAMBMC P1P2P3P4P5P6
6#include <stdlib.h>
7#include <stdio.h>
8#include <stdint.h>
9#include <stdbool.h>
10#include <string.h>
11#include <ctype.h>
12
13#define DISK_COUNT 3
14#define MESSAGE_SIZE 12
15#define PARITY_SIZE 6
16#define BLOCK_SIZE 6
17
18#define DISK_SIZE 0x40
19
20#define POPCOUNT __builtin_popcount
21#define CTZ __builtin_ctz
22
23enum command {
24 COMMAND_WRITE,
25 COMMAND_READ,
26};
27
28FILE *disks[DISK_COUNT];
29
30#ifndef WIN32
31#define LINE_SIZE 13
32#else
33#define LINE_SIZE 14
34static ssize_t
35getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
36 register char c;
37 register char *cs = NULL;
38 register int length = 0;
39 while ((c = getc (stream)) != EOF) {
40 cs = (char *) realloc (cs, ++length + 1);
41 if ((*(cs + length - 1) = c) == '\n') {
42 *(cs + length) = '\0';
43 break;
44 }
45 }
46
47 // return the allocated memory if lineptr is null
48 if ((*lineptr) == NULL) {
49 *lineptr = cs;
50 } else {
51 // check if enough memory is allocated
52 if ((length + 1) < *n)
53 *lineptr = (char *) realloc (*lineptr, length + 1);
54 memcpy (*lineptr, cs, length);
55 free (cs);
56 }
57
58 return (ssize_t) (*n = strlen (*lineptr));
59}
60#endif
61
62static void
63open_disks (uint8_t address)
64{
65 uint16_t bad_disks = 0;
66 for (int i = 0; i < DISK_COUNT; ++i) {
67 char filename[] = "disk0";
68 filename[strlen (filename) - 1] += i;
69 disks[i] = fopen (filename, "r+");
70 if (!disks[i]) { // disk file was deleted
71 disks[i] = fopen (filename, "w+");
72 if (!disks[i]) {
73 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
74 exit (EXIT_FAILURE);
75 }
76
77 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
78 bad_disks |= 1 << i;
79 } else { // disk file wasn't deleted
80 fseek (disks[i], 0, SEEK_END);
81 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
82 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
83 bad_disks |= 1 << i;
84 } rewind (disks[i]);
85 }
86 }
87
88 // there were bad disks
89 int bad_disk_count = POPCOUNT (bad_disks);
90 if (bad_disk_count == 1) { // recompute lost disk
91 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
92 int bad_disk = CTZ (bad_disks);
93
94 for (int j = 0; j < DISK_SIZE; ++j) {
95 uint8_t block_bytes[MESSAGE_SIZE + PARITY_SIZE];
96
97 // read blocks from good disks
98 bool empty = false;
99 for (int k = 0; k < DISK_COUNT; ++k) {
100 if (k == bad_disk) continue;
101 int c = fgetc (disks[k]);
102 if (c == ' ') {
103 fgetc (disks[k]);
104
105 fgetc (disks[k]);
106 fgetc (disks[k]);
107
108 fgetc (disks[k]);
109 fgetc (disks[k]);
110
111 fgetc (disks[k]);
112 fgetc (disks[k]);
113
114 fgetc (disks[k]);
115 fgetc (disks[k]);
116
117 fgetc (disks[k]);
118 fgetc (disks[k]);
119 empty = true;
120 } else {
121 ungetc (c, disks[k]);
122 fscanf (disks[k], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX",
123 &block_bytes[k*BLOCK_SIZE + 0],
124 &block_bytes[k*BLOCK_SIZE + 1],
125 &block_bytes[k*BLOCK_SIZE + 2],
126 &block_bytes[k*BLOCK_SIZE + 3],
127 &block_bytes[k*BLOCK_SIZE + 4],
128 &block_bytes[k*BLOCK_SIZE + 5]);
129 } fgetc (disks[k]);
130 }
131
132 if (empty) { // address empty
133 for (int l = 0; l < BLOCK_SIZE; ++l) {
134 fprintf (disks[bad_disk], " ");
135 } fprintf (disks[bad_disk], "\n");
136 continue;
137 }
138
139 // compute lost block
140 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
141 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
142 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
143 block_bytes[bad_disk*BLOCK_SIZE + 3] = 0x00;
144 block_bytes[bad_disk*BLOCK_SIZE + 4] = 0x00;
145 block_bytes[bad_disk*BLOCK_SIZE + 5] = 0x00;
146 for (int k = 0; k < DISK_COUNT; ++k) {
147 if (k == bad_disk) continue;
148 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
149 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
150 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
151 block_bytes[bad_disk*BLOCK_SIZE + 3] ^= block_bytes[k*BLOCK_SIZE + 3];
152 block_bytes[bad_disk*BLOCK_SIZE + 4] ^= block_bytes[k*BLOCK_SIZE + 4];
153 block_bytes[bad_disk*BLOCK_SIZE + 5] ^= block_bytes[k*BLOCK_SIZE + 5];
154 }
155
156 // write lost block
157 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n",
158 block_bytes[bad_disk*BLOCK_SIZE + 0],
159 block_bytes[bad_disk*BLOCK_SIZE + 1],
160 block_bytes[bad_disk*BLOCK_SIZE + 2],
161 block_bytes[bad_disk*BLOCK_SIZE + 3],
162 block_bytes[bad_disk*BLOCK_SIZE + 4],
163 block_bytes[bad_disk*BLOCK_SIZE + 5]);
164 }
165 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
166 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
167
168 for (int i = 0; i < DISK_COUNT; ++i) {
169 for (int j = 0; j < DISK_SIZE; ++j)
170 fputs (" \n", disks[i]);
171 }
172 }
173
174 // position head for writing/reading message
175 for (int i = 0; i < DISK_COUNT; ++i)
176 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
177}
178
179static void
180close_disks (void)
181{
182 for (int i = 0; i < DISK_COUNT; ++i)
183 fclose (disks[i]);
184}
185
186int
187main (void)
188{
189 fprintf (stderr, "INFO: initializing RAID 5 on 3 disks with 12 byte messages...\n");
190 // check disk integrity on startup
191 open_disks (0);
192 close_disks ( );
193
194 for (;;) {
195 char *line = NULL;
196 size_t line_size = 0;
197 const char *head;
198 int assigned;
199 int scanned;
200
201 // read whole line
202 printf ("> ");
203 scanned = getline (&line, &line_size, stdin);
204 if (scanned == -1)
205 exit (EXIT_SUCCESS);
206 else if (scanned == 1)
207 continue;
208 head = line;
209
210 uint8_t address; { // scan address
211 assigned = sscanf (head, "%hhx%n", &address, &scanned);
212 if (assigned != 1 || address >= DISK_SIZE) {
213 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
214 continue;
215 } head += scanned;
216 }
217
218 enum command command; { // scan command
219 char command_buffer[6] = {0};
220 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
221 if (assigned != 1 ||
222 (!strncmp (command_buffer, "read", 4) &&
223 !strncmp (command_buffer, "write", 5))) {
224 fprintf(stderr, "ERROR: command not in set (read; write)\n");
225 continue;
226 } head += scanned;
227 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
228 }
229
230 switch (command) {
231 case COMMAND_READ: {
232 uint8_t message[MESSAGE_SIZE];
233 uint8_t parity [ PARITY_SIZE];
234
235 // parse out message
236 open_disks (address);
237 int c = fgetc (disks[0]);
238 if (c == ' ') {
239 close_disks ();
240 printf ("No data stored!\n");
241 break;
242 } ungetc (c, disks[0]);
243
244 switch (address % 3) {
245 case 0:
246 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]);
247 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]);
248 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]);
249 break;
250 case 1:
251 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]);
252 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]);
253 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]);
254 break;
255 case 2:
256 fscanf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2], &parity [0x3], &parity [0x4], &parity [0x5]);
257 fscanf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2], &message[0x3], &message[0x4], &message[0x5]);
258 fscanf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8], &message[0x9], &message[0xA], &message[0xB]);
259 break;
260 } close_disks ();
261
262 printf ("%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX "
263 "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n",
264 message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5],
265 message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
266 } break;
267 case COMMAND_WRITE: {
268 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
269 int message_size = 0;
270
271 while (*head == ' ' ||
272 *head == '\t') ++head;
273 const char *invalid = NULL;
274 size_t len = 0;
275 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
276 if (!strchr ("0123456789abcdefABCDEF", *c)) {
277 invalid = c;
278 break;
279 } len += 1;
280 } if (invalid) {
281 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
282 break;
283 } if (len != 2*MESSAGE_SIZE) {
284 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
285 break;
286 }
287
288 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
289 message_size < MESSAGE_SIZE) {
290 head += scanned;
291 message_size += 1;
292 }
293 }
294
295 // compute parity
296 uint8_t parity[PARITY_SIZE] = {
297 message[0x0] ^ message[0x6],
298 message[0x1] ^ message[0x7],
299 message[0x2] ^ message[0x8],
300 message[0x3] ^ message[0x9],
301 message[0x4] ^ message[0xA],
302 message[0x5] ^ message[0xB],
303 };
304
305 // write blocks
306 open_disks (address); // open disk files, ensuring their integrity
307 switch (address % 3) {
308 case 0:
309 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]);
310 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
311 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]);
312 break;
313 case 1:
314 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]);
315 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]);
316 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
317 break;
318 case 2:
319 fprintf (disks[0], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2], parity [0x3], parity [0x4], parity [0x5]);
320 fprintf (disks[1], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5]);
321 fprintf (disks[2], "%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
322 break;
323 } close_disks ();
324 } break;
325 } free (line);
326 }
327
328 return EXIT_SUCCESS;
329}
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 @@
1// Жанг
2// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3
3#include <stdlib.h>
4#include <stdio.h>
5#include <stdint.h>
6#include <stdbool.h>
7#include <string.h>
8#include <ctype.h>
9
10#define DISK_COUNT 5
11#define MESSAGE_SIZE 12
12#define BLOCK_SIZE 3
13
14#define DISK_SIZE 0x40
15
16#define POPCOUNT __builtin_popcount
17#define CTZ __builtin_ctz
18
19enum command {
20 COMMAND_WRITE,
21 COMMAND_READ,
22};
23
24FILE *disks[DISK_COUNT];
25
26#ifndef WIN32
27#define LINE_SIZE 7
28#else
29#define LINE_SIZE 8
30static ssize_t
31getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
32 register char c;
33 register char *cs = NULL;
34 register int length = 0;
35 while ((c = getc (stream)) != EOF) {
36 cs = (char *) realloc (cs, ++length + 1);
37 if ((*(cs + length - 1) = c) == '\n') {
38 *(cs + length) = '\0';
39 break;
40 }
41 }
42
43 // return the allocated memory if lineptr is null
44 if ((*lineptr) == NULL) {
45 *lineptr = cs;
46 } else {
47 // check if enough memory is allocated
48 if ((length + 1) < *n)
49 *lineptr = (char *) realloc (*lineptr, length + 1);
50 memcpy (*lineptr, cs, length);
51 free (cs);
52 }
53
54 return (ssize_t) (*n = strlen (*lineptr));
55}
56#endif
57
58static void
59open_disks (uint8_t address)
60{
61 uint16_t bad_disks = 0;
62 for (int i = 0; i < DISK_COUNT; ++i) {
63 char filename[] = "disk0";
64 filename[strlen (filename) - 1] += i;
65 disks[i] = fopen (filename, "r+");
66 if (!disks[i]) { // disk file was deleted
67 disks[i] = fopen (filename, "w+");
68 if (!disks[i]) {
69 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
70 exit (EXIT_FAILURE);
71 }
72
73 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
74 bad_disks |= 1 << i;
75 } else { // disk file wasn't deleted
76 fseek (disks[i], 0, SEEK_END);
77 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
78 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
79 bad_disks |= 1 << i;
80 } rewind (disks[i]);
81 }
82 }
83
84 // there were bad disks
85 int bad_disk_count = POPCOUNT (bad_disks);
86 if (bad_disk_count == 1) { // recompute lost disk
87 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
88 int bad_disk = CTZ (bad_disks);
89
90 for (int j = 0; j < DISK_SIZE; ++j) {
91 uint8_t block_bytes[MESSAGE_SIZE + BLOCK_SIZE];
92
93 // read blocks from good disks
94 bool empty = false;
95 for (int k = 0; k < DISK_COUNT; ++k) {
96 if (k == bad_disk) continue;
97 int c = fgetc (disks[k]);
98 if (c == ' ') {
99 fgetc (disks[k]);
100
101 fgetc (disks[k]);
102 fgetc (disks[k]);
103
104 fgetc (disks[k]);
105 fgetc (disks[k]);
106 empty = true;
107 } else {
108 ungetc(c, disks[k]);
109 fscanf(disks[k], "%02hhX%02hhX%02hhX",
110 &block_bytes[k * BLOCK_SIZE + 0],
111 &block_bytes[k * BLOCK_SIZE + 1],
112 &block_bytes[k * BLOCK_SIZE + 2]);
113 } fgetc (disks[k]);
114 }
115
116 if (empty) { // address empty
117 for (int l = 0; l < BLOCK_SIZE; ++l) {
118 fprintf (disks[bad_disk], " ");
119 } fprintf (disks[bad_disk], "\n");
120 continue;
121 }
122
123 // compute lost block
124 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
125 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
126 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
127 for (int k = 0; k < DISK_COUNT; ++k) {
128 if (k == bad_disk) continue;
129 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
130 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
131 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
132 }
133
134 // write lost block
135 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n",
136 block_bytes[bad_disk*BLOCK_SIZE + 0],
137 block_bytes[bad_disk*BLOCK_SIZE + 1],
138 block_bytes[bad_disk*BLOCK_SIZE + 2]);
139 }
140 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
141 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
142
143 for (int i = 0; i < DISK_COUNT; ++i) {
144 for (int j = 0; j < DISK_SIZE; ++j)
145 fputs (" \n", disks[i]);
146 }
147 }
148
149 // position head for writing/reading message
150 for (int i = 0; i < DISK_COUNT; ++i)
151 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
152}
153
154static void
155close_disks (void)
156{
157 for (int i = 0; i < DISK_COUNT; ++i)
158 fclose (disks[i]);
159}
160
161int
162main (void)
163{
164 fprintf (stderr, "INFO: initializing RAID 5 XOR on 5 disks with 12 byte messages...\n");
165 // check disk integrity on startup
166 open_disks (0);
167 close_disks ( );
168
169 for (;;) {
170 char *line = NULL;
171 size_t line_size = 0;
172 const char *head;
173 int assigned;
174 int scanned;
175
176 // read whole line
177 printf ("> ");
178 scanned = getline (&line, &line_size, stdin);
179 if (scanned == -1)
180 exit (EXIT_SUCCESS);
181 else if (scanned == 1)
182 continue;
183 head = line;
184
185 uint8_t address; { // scan address
186 assigned = sscanf (head, "%hhx%n", &address, &scanned);
187 if (assigned != 1 || address >= DISK_SIZE) {
188 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
189 continue;
190 } head += scanned;
191 }
192
193 enum command command; { // scan command
194 char command_buffer[6] = {0};
195 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
196 if (assigned != 1 ||
197 (!strncmp (command_buffer, "read", 4) &&
198 !strncmp (command_buffer, "write", 5))) {
199 fprintf(stderr, "ERROR: command not in set (read; write)\n");
200 continue;
201 } head += scanned;
202 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
203 }
204
205 switch (command) {
206 case COMMAND_READ: {
207 uint8_t message[MESSAGE_SIZE];
208 uint8_t parity [ BLOCK_SIZE];
209
210 // parse out message
211 open_disks (address);
212 int c = fgetc (disks[0]);
213 if (c == ' ') {
214 close_disks ();
215 printf ("EMPTY!\n");
216 break;
217 } ungetc (c, disks[0]);
218
219 switch (address % 5) {
220 case 0:
221 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
222 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
223 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
224 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
225 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
226 break;
227 case 1:
228 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
229 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
230 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
231 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
232 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
233 break;
234 case 2:
235 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
236 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
237 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
238 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
239 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
240 break;
241 case 3:
242 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
243 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
244 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
245 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
246 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
247 break;
248 case 4:
249 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
250 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
251 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
252 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
253 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
254 break;
255 } close_disks ();
256
257 printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX "
258 "%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n",
259 message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5],
260 message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
261 } break;
262 case COMMAND_WRITE: {
263 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
264 int message_size = 0;
265
266 while (*head == ' ' ||
267 *head == '\t') ++head;
268 const char *invalid = NULL;
269 size_t len = 0;
270 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
271 if (!strchr ("0123456789abcdefABCDEF", *c)) {
272 invalid = c;
273 break;
274 } len += 1;
275 } if (invalid) {
276 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
277 break;
278 } if (len != 2*MESSAGE_SIZE) {
279 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
280 break;
281 }
282
283 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
284 message_size < MESSAGE_SIZE) {
285 head += scanned;
286 message_size += 1;
287 }
288 }
289
290 // compute parity
291 uint8_t parity[BLOCK_SIZE] = {
292 message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9],
293 message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA],
294 message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB],
295 };
296
297 // write blocks
298 open_disks (address); // open disk files, ensuring their integrity
299 switch (address % 5) {
300 case 0:
301 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
302 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
303 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
304 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
305 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
306 break;
307 case 1:
308 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
309 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
310 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
311 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
312 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
313 break;
314 case 2:
315 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
316 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
317 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
318 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
319 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
320 break;
321 case 3:
322 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
323 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
324 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
325 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
326 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
327 break;
328 case 4:
329 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
330 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
331 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
332 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
333 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
334 break;
335 } close_disks ();
336 } break;
337 } free (line);
338 }
339
340 return EXIT_SUCCESS;
341}
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 @@
1// M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000 P1P2P3
2// M1M2M3 M4M5M6 M7M8M9 MAMBMC P1P2P3 000000
3// M1M2M3 M4M5M6 M7M8M9 P1P2P3 MAMBMC 000000
4// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC 000000
5// M1M2M3 P1P2P3 M4M5M6 M7M8M9 MAMBMC 000000
6// P1P2P3 M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000
7// M1M2M3 M4M5M6 M7M8M9 MAMBMC 000000 P1P2P3
8#include <stdlib.h>
9#include <stdio.h>
10#include <stdint.h>
11#include <stdbool.h>
12#include <string.h>
13#include <ctype.h>
14
15#define DISK_COUNT 6
16#define MESSAGE_SIZE 12
17#define BLOCK_SIZE 3
18#define PADDING_SIZE 3
19#define PARITY_SIZE 3
20
21#define DISK_SIZE 0x40
22
23#define POPCOUNT __builtin_popcount
24#define CTZ __builtin_ctz
25
26enum command {
27 COMMAND_WRITE,
28 COMMAND_READ,
29};
30
31FILE *disks[DISK_COUNT];
32
33#ifndef WIN32
34#define LINE_SIZE (2*BLOCK_SIZE + 1)
35#else
36#define LINE_SIZE (2*BLOCK_SIZE + 2)
37static ssize_t
38getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
39 register char c;
40 register char *cs = NULL;
41 register int length = 0;
42 while ((c = getc (stream)) != EOF) {
43 cs = (char *) realloc (cs, ++length + 1);
44 if ((*(cs + length - 1) = c) == '\n') {
45 *(cs + length) = '\0';
46 break;
47 }
48 }
49
50 // return the allocated memory if lineptr is null
51 if ((*lineptr) == NULL) {
52 *lineptr = cs;
53 } else {
54 // check if enough memory is allocated
55 if ((length + 1) < *n)
56 *lineptr = (char *) realloc (*lineptr, length + 1);
57 memcpy (*lineptr, cs, length);
58 free (cs);
59 }
60
61 return (ssize_t) (*n = strlen (*lineptr));
62}
63#endif
64
65static void
66open_disks (uint8_t address)
67{
68 uint16_t bad_disks = 0;
69 for (int i = 0; i < DISK_COUNT; ++i) {
70 char filename[] = "disk0";
71 filename[strlen (filename) - 1] += i;
72 disks[i] = fopen (filename, "r+");
73 if (!disks[i]) { // disk file was deleted
74 disks[i] = fopen (filename, "w+");
75 if (!disks[i]) {
76 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
77 exit (EXIT_FAILURE);
78 }
79
80 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
81 bad_disks |= 1 << i;
82 } else { // disk file wasn't deleted
83 fseek (disks[i], 0, SEEK_END);
84 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
85 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
86 bad_disks |= 1 << i;
87 } rewind (disks[i]);
88 }
89 }
90
91 // there were bad disks
92 int bad_disk_count = POPCOUNT (bad_disks);
93 if (bad_disk_count == 1) { // recompute lost disk
94 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
95 int bad_disk = CTZ (bad_disks);
96
97 for (int j = 0; j < DISK_SIZE; ++j) {
98 uint8_t block_bytes[MESSAGE_SIZE + PADDING_SIZE + PARITY_SIZE] = {0};
99
100 // read blocks from good disks
101 bool empty = false;
102 for (int k = 0; k < DISK_COUNT; ++k) {
103 if (k == bad_disk) continue;
104 int c = fgetc (disks[k]);
105 if (c == ' ') {
106 fgetc (disks[k]);
107
108 fgetc (disks[k]);
109 fgetc (disks[k]);
110
111 fgetc (disks[k]);
112 fgetc (disks[k]);
113 empty = true;
114 } else {
115 ungetc(c, disks[k]);
116 fscanf(disks[k], "%02hhX%02hhX%02hhX",
117 &block_bytes[k * BLOCK_SIZE + 0],
118 &block_bytes[k * BLOCK_SIZE + 1],
119 &block_bytes[k * BLOCK_SIZE + 2]);
120 } fgetc (disks[k]);
121 }
122
123 if (empty) { // address empty
124 for (int l = 0; l < BLOCK_SIZE; ++l) {
125 fprintf (disks[bad_disk], " ");
126 } fprintf (disks[bad_disk], "\n");
127 continue;
128 }
129
130 // compute lost block
131 block_bytes[bad_disk*BLOCK_SIZE + 0] = 0x00;
132 block_bytes[bad_disk*BLOCK_SIZE + 1] = 0x00;
133 block_bytes[bad_disk*BLOCK_SIZE + 2] = 0x00;
134 for (int k = 0; k < DISK_COUNT; ++k) {
135 if (k == bad_disk) continue;
136 block_bytes[bad_disk*BLOCK_SIZE + 0] ^= block_bytes[k*BLOCK_SIZE + 0];
137 block_bytes[bad_disk*BLOCK_SIZE + 1] ^= block_bytes[k*BLOCK_SIZE + 1];
138 block_bytes[bad_disk*BLOCK_SIZE + 2] ^= block_bytes[k*BLOCK_SIZE + 2];
139 }
140
141 // write lost block
142 fprintf (disks[bad_disk], "%02hhX%02hhX%02hhX\n",
143 block_bytes[bad_disk*BLOCK_SIZE + 0],
144 block_bytes[bad_disk*BLOCK_SIZE + 1],
145 block_bytes[bad_disk*BLOCK_SIZE + 2]);
146 }
147 } else if (bad_disk_count > 1) { // replace all disks with empty ones, all data is lost
148 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
149
150 for (int i = 0; i < DISK_COUNT; ++i) {
151 for (int j = 0; j < DISK_SIZE; ++j)
152 fputs (" \n", disks[i]);
153 }
154 }
155
156 // position head for writing/reading message
157 for (int i = 0; i < DISK_COUNT; ++i)
158 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
159}
160
161static void
162close_disks (void)
163{
164 for (int i = 0; i < DISK_COUNT; ++i)
165 fclose (disks[i]);
166}
167
168int
169main (void)
170{
171 fprintf (stderr, "INFO: initializing RAID 5 XOR on 5 disks with 12 byte messages...\n");
172 // check disk integrity on startup
173 open_disks (0);
174 close_disks ( );
175
176 for (;;) {
177 char *line = NULL;
178 size_t line_size = 0;
179 const char *head;
180 int assigned;
181 int scanned;
182
183 // read whole line
184 printf ("> ");
185 scanned = getline (&line, &line_size, stdin);
186 if (scanned == -1)
187 exit (EXIT_SUCCESS);
188 else if (scanned == 1)
189 continue;
190 head = line;
191
192 uint8_t address; { // scan address
193 assigned = sscanf (head, "%hhx%n", &address, &scanned);
194 if (assigned != 1 || address >= DISK_SIZE) {
195 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
196 continue;
197 } head += scanned;
198 }
199
200 enum command command; { // scan command
201 char command_buffer[6] = {0};
202 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
203 if (assigned != 1 ||
204 (!strncmp (command_buffer, "read", 4) &&
205 !strncmp (command_buffer, "write", 5))) {
206 fprintf(stderr, "ERROR: command not in set (read; write)\n");
207 continue;
208 } head += scanned;
209 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
210 }
211
212 switch (command) {
213 case COMMAND_READ: {
214 uint8_t message[MESSAGE_SIZE];
215 uint8_t padding[PADDING_SIZE];
216 uint8_t parity [ PARITY_SIZE];
217
218 // parse out message
219 open_disks (address);
220 int c = fgetc (disks[0]);
221 if (c == ' ') {
222 close_disks ();
223 printf ("EMPTY!\n");
224 break;
225 } ungetc (c, disks[0]);
226
227 switch (address % DISK_COUNT) {
228 case 0:
229 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
230 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
231 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
232 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
233 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
234 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
235 break;
236 case 1:
237 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
238 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
239 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
240 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
241 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
242 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
243 break;
244 case 2:
245 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
246 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
247 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
248 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
249 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
250 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
251 break;
252 case 3:
253 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
254 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
255 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
256 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
257 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
258 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
259 break;
260 case 4:
261 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
262 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
263 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
264 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
265 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
266 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
267 break;
268 case 5:
269 fscanf (disks[0], "%02hhX%02hhX%02hhX\n", &parity [0x0], &parity [0x1], &parity [0x2]);
270 fscanf (disks[1], "%02hhX%02hhX%02hhX\n", &message[0x0], &message[0x1], &message[0x2]);
271 fscanf (disks[2], "%02hhX%02hhX%02hhX\n", &message[0x3], &message[0x4], &message[0x5]);
272 fscanf (disks[3], "%02hhX%02hhX%02hhX\n", &message[0x6], &message[0x7], &message[0x8]);
273 fscanf (disks[4], "%02hhX%02hhX%02hhX\n", &message[0x9], &message[0xA], &message[0xB]);
274 fscanf (disks[5], "%02hhX%02hhX%02hhX\n", &padding[0x0], &padding[0x1], &padding[0x2]);
275 break;
276 } close_disks ();
277
278 printf ("%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX "
279 "%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX\n",
280 message[0x0], message[0x1], message[0x2], message[0x3], message[0x4], message[0x5],
281 message[0x6], message[0x7], message[0x8], message[0x9], message[0xA], message[0xB]);
282 } break;
283 case COMMAND_WRITE: {
284 uint8_t message[MESSAGE_SIZE] = {0}; { // scan message
285 int message_size = 0;
286
287 while (*head == ' ' ||
288 *head == '\t') ++head;
289 const char *invalid = NULL;
290 size_t len = 0;
291 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
292 if (!strchr ("0123456789abcdefABCDEF", *c)) {
293 invalid = c;
294 break;
295 } len += 1;
296 } if (invalid) {
297 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
298 break;
299 } if (len != 2*MESSAGE_SIZE) {
300 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
301 break;
302 }
303
304 while (sscanf (head, "%2hhx%n", &message[message_size], &scanned) == 1 &&
305 message_size < MESSAGE_SIZE) {
306 head += scanned;
307 message_size += 1;
308 }
309 }
310
311 // compute parity
312 uint8_t padding[PADDING_SIZE] = {
313 0x00,
314 0x00,
315 0x00,
316 };
317 uint8_t parity[PARITY_SIZE] = {
318 message[0x0] ^ message[0x3] ^ message[0x6] ^ message[0x9],
319 message[0x1] ^ message[0x4] ^ message[0x7] ^ message[0xA],
320 message[0x2] ^ message[0x5] ^ message[0x8] ^ message[0xB],
321 };
322
323 // write blocks
324 open_disks (address); // open disk files, ensuring their integrity
325 switch (address % DISK_COUNT) {
326 case 0:
327 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
328 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
329 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
330 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
331 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
332 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
333 break;
334 case 1:
335 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
336 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
337 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
338 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
339 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
340 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
341 break;
342 case 2:
343 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
344 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
345 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
346 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
347 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
348 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
349 break;
350 case 3:
351 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
352 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
353 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
354 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
355 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
356 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
357 break;
358 case 4:
359 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
360 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
361 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
362 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
363 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
364 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
365 break;
366 case 5:
367 fprintf (disks[0], "%02hhX%02hhX%02hhX\n", parity [0x0], parity [0x1], parity [0x2]);
368 fprintf (disks[1], "%02hhX%02hhX%02hhX\n", message[0x0], message[0x1], message[0x2]);
369 fprintf (disks[2], "%02hhX%02hhX%02hhX\n", message[0x3], message[0x4], message[0x5]);
370 fprintf (disks[3], "%02hhX%02hhX%02hhX\n", message[0x6], message[0x7], message[0x8]);
371 fprintf (disks[4], "%02hhX%02hhX%02hhX\n", message[0x9], message[0xA], message[0xB]);
372 fprintf (disks[5], "%02hhX%02hhX%02hhX\n", padding[0x0], padding[0x1], padding[0x2]);
373 break;
374 } close_disks ();
375 } break;
376 } free (line);
377 }
378
379 return EXIT_SUCCESS;
380}
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 @@
1// Aksel
2// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6
3// M1M2M3 P1P2P3 M4M5M6 M7M8M9 P4P5P6 MAMBMC
4// P1P2P3 M1M2M3 M4M5M6 P4P5P6 M7M8M9 MAMBMC
5// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6
6#include <stdlib.h>
7#include <stdio.h>
8#include <stdint.h>
9#include <stdbool.h>
10#include <string.h>
11#include <ctype.h>
12
13#define DISK_COUNT 6
14#define MESSAGE_SIZE 12
15#define BLOCK_SIZE 3
16
17uint8_t coefficients[DISK_COUNT - 2] = { 1, 1, 1, 1, };
18
19// TODO(cmmm): generate
20int shift_table[][DISK_COUNT] = {
21 { 0, 1, 2, 3, 4, 5 },
22 { 0, 2, 1, 3, 5, 4 },
23 { 1, 2, 0, 4, 5, 3 },
24};
25
26#define DISK_SIZE 0x40
27#define POPCOUNT __builtin_popcount
28#define CTZ __builtin_ctz
29
30#ifndef WIN32
31#define LINE_SIZE (2*BLOCK_SIZE + 1)
32#else
33#define LINE_SIZE (2*BLOCK_SIZE + 2)
34static ssize_t
35getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
36 register char c;
37 register char *cs = NULL;
38 register int length = 0;
39 while ((c = getc (stream)) != EOF) {
40 cs = (char *) realloc (cs, ++length + 1);
41 if ((*(cs + length - 1) = c) == '\n') {
42 *(cs + length) = '\0';
43 break;
44 }
45 }
46
47 if ((*lineptr) == NULL) {
48 *lineptr = cs;
49 } else {
50 if ((length + 1) < *n)
51 *lineptr = (char *) realloc (*lineptr, length + 1);
52 memcpy (*lineptr, cs, length);
53 free (cs);
54 }
55
56 return (ssize_t) (*n = strlen (*lineptr));
57}
58#endif
59
60enum command {
61 COMMAND_WRITE,
62 COMMAND_READ,
63};
64
65FILE *disks[DISK_COUNT];
66
67static void
68recompute_bad_disk (int bad_disk)
69{
70 int cluster = bad_disk/(DISK_COUNT/2);
71
72 for (int j = 0; j < DISK_SIZE; ++j) {
73 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE];
74 int shift = j % (DISK_COUNT/2);
75 int logical_bad_disk;
76 bool empty = false;
77 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
78 if (shift_table[shift][k] == bad_disk) {
79 logical_bad_disk = k;
80 continue;
81 }
82 for (int l = 0; l < BLOCK_SIZE; ++l) {
83 int c = fgetc (disks[shift_table[shift][k]]);
84 if (c == ' ') {
85 fgetc (disks[shift_table[shift][k]]);
86 empty = true;
87 } else {
88 ungetc (c, disks[shift_table[shift][k]]);
89 fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
90 }
91 } fgetc (disks[shift_table[shift][k]]);
92 }
93
94 if (empty) { // address empty
95 for (int l = 0; l < BLOCK_SIZE; ++l) {
96 fprintf (disks[bad_disk], " ");
97 } fprintf (disks[bad_disk], "\n");
98 continue;
99 } else if (logical_bad_disk % (DISK_COUNT/2) == DISK_COUNT/2 - 1) { // lost parity
100 for (int l = 0; l < BLOCK_SIZE; ++l)
101 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00;
102 for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
103 if (k == logical_bad_disk) continue;
104 for (int l = 0; l < BLOCK_SIZE; ++l)
105 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] +=
106 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
107 c += 1;
108 }
109 } else {
110 for (int l = 0; l < BLOCK_SIZE; ++l) {
111 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] =
112 block_bytes[((DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1)*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
113 }
114 for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1; ++k) {
115 if (k == logical_bad_disk) continue;
116 for (int l = 0; l < BLOCK_SIZE; ++l)
117 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] -=
118 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
119 c += 1;
120 }
121 }
122
123 for (int l = 0; l < BLOCK_SIZE; ++l) {
124 fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
125 } fprintf (disks[bad_disk], "\n");
126 }
127}
128
129static void
130open_disks (uint8_t address)
131{
132 uint16_t bad_disks = 0;
133 for (int i = 0; i < DISK_COUNT; ++i) {
134 char filename[] = "disk0";
135 filename[strlen (filename) - 1] += i;
136 disks[i] = fopen (filename, "r+");
137 if (!disks[i]) {
138 disks[i] = fopen (filename, "w+");
139 if (!disks[i]) {
140 fprintf (stderr, "Ошибка! Невозможно открыть файл: %s\n", filename);
141 exit (EXIT_FAILURE);
142 }
143
144 fprintf (stderr, "Предупреждение! Найден плохой диск: %s\n", filename);
145 bad_disks |= 1 << i;
146 } else { // disk file wasn't deleted
147 fseek (disks[i], 0, SEEK_END);
148 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
149 fprintf (stderr, "Предупреждение!Найден плохой диск: %s\n", filename);
150 fclose (disks[i]);
151 disks[i] = fopen (filename, "w+");
152 bad_disks |= 1 << i;
153 } else rewind (disks[i]);
154 }
155 }
156
157 int bad_disk_count = POPCOUNT (bad_disks);
158 if (bad_disk_count == 1) {
159 fprintf (stderr, "Повторный расчет, один диск плохой...\n");
160 int bad_disk = CTZ (bad_disks);
161 recompute_bad_disk (bad_disk);
162 } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) {
163 fprintf (stderr, "2 плохих диска в разделяющемся кластере, повторный расчет.\n");
164 int bad_disk0 = CTZ (bad_disks);
165 int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0));
166 recompute_bad_disk (bad_disk0);
167 recompute_bad_disk (bad_disk1);
168 } else if (bad_disk_count) {
169 fprintf (stderr, "Ошибка! Повторная инициализация массива с новыми дисками.\n");
170 for (int i = 0; i < DISK_COUNT; ++i) {
171 for (int j = 0; j < DISK_SIZE; ++j) {
172 for (int k = 0; k < BLOCK_SIZE; ++k) {
173 fputs (" ", disks[i]);
174 } fputs ("\n", disks[i]);
175 }
176 }
177 }
178
179 for (int i = 0; i < DISK_COUNT; ++i)
180 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
181}
182
183static void
184close_disks (void)
185{
186 for (int i = 0; i < DISK_COUNT; ++i)
187 fclose (disks[i]);
188}
189
190int
191main (void)
192{
193 fprintf (stderr, "Инициализация RAID 50 с POLY на 6 дисках с 12 байтовым сообщением.\n");
194
195
196 open_disks (0);
197 close_disks ( );
198
199 for (;;) {
200 char *line = NULL;
201 size_t line_size = 0;
202 const char *head;
203 int assigned;
204 int scanned;
205
206 printf ("> ");
207 scanned = getline (&line, &line_size, stdin);
208 if (scanned == -1)
209 exit (EXIT_SUCCESS);
210 else if (scanned == 1)
211 continue;
212 head = line;
213
214 uint8_t address; {
215 assigned = sscanf (head, "%hhu%n", &address, &scanned);
216 if (assigned != 1 || address >= DISK_SIZE) {
217 fprintf(stderr, "Ошибка! Адрес не входит в границы! [0; 64)\n");
218 continue;
219 } head += scanned;
220 }
221
222 enum command command; {
223 char command_buffer[6] = {0};
224 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
225 if (assigned != 1 ||
226 (!strncmp (command_buffer, "read", 4) &&
227 !strncmp (command_buffer, "write", 5))) {
228 fprintf(stderr, "Ошибка! Не корректная команда! (read; write)\n");
229 continue;
230 } head += scanned;
231 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
232 }
233
234 switch (command) {
235 case COMMAND_READ: {
236 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE];
237 int shift = address % (DISK_COUNT/2);
238 open_disks (address);
239 int c = fgetc (disks[0]);
240 if (c == ' ') {
241 close_disks ();
242 printf ("Пусто\n");
243 break;
244 } else ungetc (c, disks[0]);
245 for (int i = 0; i < DISK_COUNT; ++i) {
246 for (int j = 0; j < BLOCK_SIZE; ++j) {
247 fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[BLOCK_SIZE*i + j]);
248 }
249 } close_disks ();
250
251 for (int i = 0; i < DISK_COUNT; ++i) {
252 if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue;
253 for (int j = 0; j < BLOCK_SIZE; ++j)
254 printf ("%02hhX", block_bytes[BLOCK_SIZE*i + j]);
255 printf (" ");
256 } printf ("\n");
257 } break;
258 case COMMAND_WRITE: {
259 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message
260 uint8_t *write_head = block_bytes;
261 int message_size = 0;
262
263 while (*head == ' ' ||
264 *head == '\t') ++head;
265 const char *invalid = NULL;
266 size_t len = 0;
267 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
268 if (!strchr ("0123456789abcdefABCDEF", *c)) {
269 invalid = c;
270 break;
271 } len += 1;
272 } if (invalid) {
273 fprintf (stderr, "Ошибка! В сообщении запрещён символ `%c'\n", *invalid);
274 break;
275 } if (len != 2*MESSAGE_SIZE) {
276 fprintf (stderr, "Ошибка! Ожидалось %d hex цифр для сообщения, получилось %zu\n", 2*MESSAGE_SIZE, len);
277 break;
278 }
279
280 while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 &&
281 message_size < MESSAGE_SIZE) {
282 head += scanned;
283 message_size += 1;
284 write_head += 1;
285 if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0)
286 write_head += BLOCK_SIZE;
287 }
288 }
289
290 int shift = address % (DISK_COUNT/2);
291
292 for (int i = 0; i < DISK_COUNT/2 - 1; ++i) {
293 for (int j = 0; j < BLOCK_SIZE; ++j)
294 block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j];
295 }
296
297 for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) {
298 for (int j = 0; j < BLOCK_SIZE; ++j)
299 block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i - 1]*block_bytes[i*BLOCK_SIZE + j];
300 }
301
302 open_disks (address);
303 for (int i = 0; i < DISK_COUNT; ++i) {
304 for (int j = 0; j < BLOCK_SIZE; ++j)
305 fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]);
306 fprintf (disks[shift_table[shift][i]], "\n");
307 } close_disks ();
308 } break;
309 } free (line);
310 }
311 return EXIT_SUCCESS;
312}
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 @@
1// feld marshal
2// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4
3// M1M2 P1P2 M3M4 M5M6 P3P4 M7M8
4// P1P2 M1M2 M3M4 P3P4 M5M6 M7M8
5// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4
6#include <stdlib.h>
7#include <stdio.h>
8#include <stdint.h>
9#include <string.h>
10#include <ctype.h>
11
12#define DISK_COUNT 6
13#define MESSAGE_SIZE 8
14#define BLOCK_SIZE 2
15
16uint8_t coefficients[DISK_COUNT - 2] = { 1, 1, 1, 1, };
17
18// TODO(cmmm): generate
19int shift_table[][DISK_COUNT] = {
20 { 0, 1, 2, 3, 4, 5 },
21 { 0, 2, 1, 3, 5, 4 },
22 { 1, 2, 0, 4, 5, 3 },
23};
24
25#define DISK_SIZE 0x40
26#define POPCOUNT __builtin_popcount
27#define CTZ __builtin_ctz
28
29#ifndef WIN32
30#define LINE_SIZE (2*BLOCK_SIZE + 1)
31#else
32#define LINE_SIZE (2*BLOCK_SIZE + 2)
33static ssize_t
34getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
35 register char c;
36 register char *cs = NULL;
37 register int length = 0;
38 while ((c = getc (stream)) != EOF) {
39 cs = (char *) realloc (cs, ++length + 1);
40 if ((*(cs + length - 1) = c) == '\n') {
41 *(cs + length) = '\0';
42 break;
43 }
44 }
45
46 // return the allocated memory if lineptr is null
47 if ((*lineptr) == NULL) {
48 *lineptr = cs;
49 } else {
50 // check if enough memory is allocated
51 if ((length + 1) < *n)
52 *lineptr = (char *) realloc (*lineptr, length + 1);
53 memcpy (*lineptr, cs, length);
54 free (cs);
55 }
56
57 return (ssize_t) (*n = strlen (*lineptr));
58}
59#endif
60
61enum command {
62 COMMAND_WRITE,
63 COMMAND_READ,
64};
65
66FILE *disks[DISK_COUNT];
67
68static void
69recompute_bad_disk (int bad_disk)
70{
71 int cluster = bad_disk/(DISK_COUNT/2);
72
73 for (int j = 0; j < DISK_SIZE; ++j) {
74 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE];
75 int shift = j % (DISK_COUNT/2);
76
77 // read blocks from good disks
78 int logical_bad_disk;
79 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
80 if (shift_table[shift][k] == bad_disk) {
81 logical_bad_disk = k;
82 continue;
83 }
84 for (int l = 0; l < BLOCK_SIZE; ++l) {
85 fscanf (disks[shift_table[shift][k]], "%02hhX", &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
86 } fscanf (disks[shift_table[shift][k]], "\n");
87 }
88
89 // compute lost block
90 if (logical_bad_disk % (DISK_COUNT/2) == DISK_COUNT/2 - 1) { // lost parity
91 for (int l = 0; l < BLOCK_SIZE; ++l)
92 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00;
93 for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
94 if (k == logical_bad_disk) continue;
95 for (int l = 0; l < BLOCK_SIZE; ++l)
96 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] +=
97 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
98 c += 1;
99 }
100 } else { // lost data
101 for (int l = 0; l < BLOCK_SIZE; ++l) {
102 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] =
103 block_bytes[((DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1)*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
104 }
105 for (int k = cluster*DISK_COUNT/2, c = 0; k < DISK_COUNT/2 + cluster*DISK_COUNT/2 - 1; ++k) {
106 if (k == logical_bad_disk) continue;
107 for (int l = 0; l < BLOCK_SIZE; ++l)
108 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] -=
109 coefficients[c]*block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
110 c += 1;
111 }
112 }
113
114 // write lost block
115 for (int l = 0; l < BLOCK_SIZE; ++l) {
116 fprintf (disks[bad_disk], "%02hhX", block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
117 } fprintf (disks[bad_disk], "\n");
118 }
119}
120
121static void
122open_disks (uint8_t address)
123{
124 uint16_t bad_disks = 0;
125 for (int i = 0; i < DISK_COUNT; ++i) {
126 char filename[] = "disk0";
127 filename[strlen (filename) - 1] += i;
128 disks[i] = fopen (filename, "r+");
129 if (!disks[i]) { // disk file was deleted
130 disks[i] = fopen (filename, "w+");
131 if (!disks[i]) {
132 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
133 exit (EXIT_FAILURE);
134 }
135
136 fprintf (stderr, "WARNING: found bad disk: %s\n", filename);
137 bad_disks |= 1 << i;
138 } else { // disk file wasn't deleted
139 fseek (disks[i], 0, SEEK_END);
140 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
141 fprintf (stderr, "WARNING: found bad disk: %s\n", filename);
142 fclose (disks[i]);
143 disks[i] = fopen (filename, "w+");
144 bad_disks |= 1 << i;
145 } else rewind (disks[i]);
146 }
147 }
148
149 // there were bad disks
150 int bad_disk_count = POPCOUNT (bad_disks);
151 if (bad_disk_count == 1) { // recompute lost disk
152 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
153 int bad_disk = CTZ (bad_disks);
154 recompute_bad_disk (bad_disk);
155 } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) {
156 fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n");
157 int bad_disk0 = CTZ (bad_disks);
158 int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0));
159 recompute_bad_disk (bad_disk0);
160 recompute_bad_disk (bad_disk1);
161 } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost
162 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
163 for (int i = 0; i < DISK_COUNT; ++i) {
164 for (int j = 0; j < DISK_SIZE; ++j) {
165 for (int k = 0; k < BLOCK_SIZE; ++k) {
166 fputs ("00", disks[i]);
167 } fputs ("\n", disks[i]);
168 }
169 }
170 }
171
172 // position head for writing/reading message
173 for (int i = 0; i < DISK_COUNT; ++i)
174 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
175}
176
177static void
178close_disks (void)
179{
180 for (int i = 0; i < DISK_COUNT; ++i)
181 fclose (disks[i]);
182}
183
184int
185main (void)
186{
187 fprintf (stderr, "INFO: initializing RAID 50 on 6 disks with 8 byte messages...\n");
188
189 // check disk integrity on startup
190 open_disks (0);
191 close_disks ( );
192
193 for (;;) {
194 char *line = NULL;
195 size_t line_size = 0;
196 const char *head;
197 int assigned;
198 int scanned;
199
200 // read whole line
201 printf ("> ");
202 scanned = getline (&line, &line_size, stdin);
203 if (scanned == -1)
204 exit (EXIT_SUCCESS);
205 else if (scanned == 1)
206 continue;
207 head = line;
208
209 uint8_t address; { // scan address
210 assigned = sscanf (head, "%hhx%n", &address, &scanned);
211 if (assigned != 1 || address >= DISK_SIZE) {
212 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
213 continue;
214 } head += scanned;
215 }
216
217 enum command command; { // scan command
218 char command_buffer[6] = {0};
219 assigned = sscanf (head, "%5s %n", command_buffer, &scanned);
220 if (assigned != 1 ||
221 (!strncmp (command_buffer, "read", 4) &&
222 !strncmp (command_buffer, "write", 5))) {
223 fprintf(stderr, "ERROR: command not in set (read; write)\n");
224 continue;
225 } head += scanned;
226 command = command_buffer[0] == 'r' ? COMMAND_READ : COMMAND_WRITE;
227 }
228
229 switch (command) {
230 case COMMAND_READ: {
231 // parse out message
232 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE];
233 int shift = address % (DISK_COUNT/2);
234 open_disks (address);
235 for (int i = 0; i < DISK_COUNT; ++i) {
236 for (int j = 0; j < BLOCK_SIZE; ++j)
237 fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[2*i + j]);
238 fscanf (disks[shift_table[shift][i]], "\n");
239 } close_disks ();
240
241 for (int i = 0; i < DISK_COUNT; ++i) {
242 if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue;
243 for (int j = 0; j < BLOCK_SIZE; ++j)
244 printf ("%02hhX", block_bytes[2*i + j]);
245 printf (" ");
246 } printf ("\n");
247 } break;
248 case COMMAND_WRITE: {
249 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message
250 uint8_t *write_head = block_bytes;
251
252 while (*head == ' ' ||
253 *head == '\t') ++head;
254 const char *invalid = NULL;
255 size_t len = 0;
256 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
257 if (!strchr ("0123456789abcdefABCDEF", *c)) {
258 invalid = c;
259 break;
260 } len += 1;
261 } if (invalid) {
262 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
263 break;
264 } if (len != 2*MESSAGE_SIZE) {
265 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
266 break;
267 }
268
269 int message_size = 0;
270 while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 &&
271 message_size < MESSAGE_SIZE) {
272 head += scanned;
273 message_size += 1;
274 write_head += 1;
275 if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0)
276 write_head += BLOCK_SIZE;
277 }
278 }
279
280 int shift = address % (DISK_COUNT/2);
281
282 // compute parity of first cluster
283 for (int i = 0; i < DISK_COUNT/2 - 1; ++i) {
284 for (int j = 0; j < BLOCK_SIZE; ++j)
285 block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] += coefficients[i]*block_bytes[i*BLOCK_SIZE + j];
286 }
287
288 // compute parity of second cluster
289 for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) {
290 for (int j = 0; j < BLOCK_SIZE; ++j)
291 block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] += coefficients[i - 1]*block_bytes[i*BLOCK_SIZE + j];
292 }
293
294 // write needed blocks in each file in the necessary order
295 open_disks (address);
296 for (int i = 0; i < DISK_COUNT; ++i) {
297 for (int j = 0; j < BLOCK_SIZE; ++j)
298 fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]);
299 fprintf (disks[shift_table[shift][i]], "\n");
300 } close_disks ();
301 } break;
302 } free (line);
303 }
304 return EXIT_SUCCESS;
305}
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 @@
1// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6
2// M1M2M3 P1P2P3 M4M5M6 M7M8M9 P4P5P6 MAMBMC
3// P1P2P3 M1M2M3 M4M5M6 P4P5P6 M7M8M9 MAMBMC
4// M1M2M3 M4M5M6 P1P2P3 M7M8M9 MAMBMC P4P5P6
5#include <stdlib.h>
6#include <stdio.h>
7#include <stdint.h>
8#include <stdbool.h>
9#include <string.h>
10#include <ctype.h>
11
12#define DISK_COUNT 6
13#define MESSAGE_SIZE 12
14#define BLOCK_SIZE 3
15
16// TODO(cmmm): generate
17int shift_table[][DISK_COUNT] = {
18 { 0, 1, 2, 3, 4, 5 },
19 { 0, 2, 1, 3, 5, 4 },
20 { 1, 2, 0, 4, 5, 3 },
21};
22
23#define DISK_SIZE 0x40
24#define POPCOUNT __builtin_popcount
25#define CTZ __builtin_ctz
26
27#ifndef WIN32
28#define LINE_SIZE (2*BLOCK_SIZE + 1)
29#else
30#define LINE_SIZE (2*BLOCK_SIZE + 2)
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59enum command {
60 COMMAND_NONE,
61 COMMAND_WRITE,
62 COMMAND_READ,
63};
64
65FILE *disks[DISK_COUNT];
66
67static void
68recompute_bad_disk (int bad_disk)
69{
70 int cluster = bad_disk/(DISK_COUNT/2);
71
72 for (int j = 0; j < DISK_SIZE; ++j) {
73 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE];
74 int shift = j % (DISK_COUNT/2);
75
76 // read blocks from good disks
77 int logical_bad_disk;
78 bool empty = false;
79 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
80 if (shift_table[shift][k] == bad_disk) {
81 logical_bad_disk = k;
82 continue;
83 }
84 for (int l = 0; l < BLOCK_SIZE; ++l) {
85 int c = fgetc (disks[shift_table[shift][k]]);
86 if (c == ' ') {
87 fgetc (disks[shift_table[shift][k]]);
88 empty = true;
89 } else {
90 ungetc (c, disks[shift_table[shift][k]]);
91 fscanf (disks[shift_table[shift][k]], "%02hhX",
92 &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
93 }
94 } fgetc (disks[shift_table[shift][k]]);
95 }
96
97 if (empty) { // address empty
98 for (int l = 0; l < BLOCK_SIZE; ++l) {
99 fprintf (disks[bad_disk], " ");
100 } fprintf (disks[bad_disk], "\n");
101 continue;
102 }
103
104 // compute lost block
105 for (int l = 0; l < BLOCK_SIZE; ++l)
106 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00;
107 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
108 if (k == logical_bad_disk) continue;
109 for (int l = 0; l < BLOCK_SIZE; ++l)
110 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] ^=
111 block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
112 }
113
114 // write lost block
115 for (int l = 0; l < BLOCK_SIZE; ++l) {
116 fprintf (disks[bad_disk], "%02hhX",
117 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
118 } fprintf (disks[bad_disk], "\n");
119 }
120}
121
122static void
123open_disks (uint8_t address)
124{
125 uint16_t bad_disks = 0;
126 for (int i = 0; i < DISK_COUNT; ++i) {
127 char filename[] = "disk0";
128 filename[strlen (filename) - 1] += i;
129 disks[i] = fopen (filename, "r+");
130 if (!disks[i]) { // disk file was deleted
131 disks[i] = fopen (filename, "w+");
132 if (!disks[i]) {
133 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
134 exit (EXIT_FAILURE);
135 }
136
137 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
138 bad_disks |= 1 << i;
139 } else { // disk file wasn't deleted
140 fseek (disks[i], 0, SEEK_END);
141 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
142 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
143 fclose (disks[i]);
144 disks[i] = fopen (filename, "w+");
145 bad_disks |= 1 << i;
146 } else rewind (disks[i]);
147 }
148 }
149
150 // there were bad disks
151 int bad_disk_count = POPCOUNT (bad_disks);
152 if (bad_disk_count == 1) { // recompute lost disk
153 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
154 int bad_disk = CTZ (bad_disks);
155 recompute_bad_disk (bad_disk);
156 } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) {
157 fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n");
158 int bad_disk0 = CTZ (bad_disks);
159 int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0));
160 recompute_bad_disk (bad_disk0);
161 recompute_bad_disk (bad_disk1);
162 } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost
163 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
164 for (int i = 0; i < DISK_COUNT; ++i) {
165 for (int j = 0; j < DISK_SIZE; ++j) {
166 for (int k = 0; k < BLOCK_SIZE; ++k) {
167 fputs (" ", disks[i]);
168 } fputs ("\n", disks[i]);
169 }
170 }
171 }
172
173 // position head for writing/reading message
174 for (int i = 0; i < DISK_COUNT; ++i)
175 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
176}
177
178static void
179close_disks (void)
180{
181 for (int i = 0; i < DISK_COUNT; ++i)
182 fclose (disks[i]);
183}
184
185int
186main (void)
187{
188 fprintf (stderr, "INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...\n");
189
190 // check disk integrity on startup
191 open_disks (0);
192 close_disks ( );
193
194 for (;;) {
195 char *line = NULL;
196 size_t line_size = 0;
197 char *head;
198 int assigned;
199 int scanned;
200
201 // read whole line
202 printf ("> ");
203 scanned = getline (&line, &line_size, stdin);
204 if (scanned == -1)
205 exit (EXIT_SUCCESS);
206 else if (scanned == 1)
207 continue;
208 head = line;
209
210 uint8_t address; { // scan address
211 assigned = sscanf (head, "%hhx%n", &address, &scanned);
212 if (assigned != 1 || address >= DISK_SIZE || scanned > 2) {
213 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
214 continue;
215 } head += scanned;
216 }
217
218 enum command command = COMMAND_NONE; { // scan command
219 while (*head == ' ') head += 1;
220 if (!strncmp (head, "read", 4)) {
221 head += 4;
222 command = COMMAND_READ;
223 } else if (!strncmp (head, "write", 5)) {
224 head += 5;
225 command = COMMAND_WRITE;
226 }
227 if (!isspace(*head))
228 command = COMMAND_NONE;
229 }
230
231 switch (command) {
232 case COMMAND_NONE: {
233 fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n");
234 continue;
235 } break;
236 case COMMAND_READ: {
237 // parse out message
238 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE];
239 int shift = address % (DISK_COUNT/2);
240
241 while (isspace (*head)) {
242 head += 1;
243 if (*head == '\n' ||
244 *head == '\r') {
245 *head = '\0';
246 }
247 } if (*head) {
248 fprintf (stderr, "ERROR: trailing junk after command: %s", head);
249 continue;
250 }
251
252 open_disks (address);
253 int c = fgetc (disks[0]);
254 if (c == ' ') {
255 close_disks ();
256 printf ("No data stored!\n");
257 break;
258 } ungetc (c, disks[0]);
259
260 for (int i = 0; i < DISK_COUNT; ++i) {
261 for (int j = 0; j < BLOCK_SIZE; ++j)
262 fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[i*BLOCK_SIZE + j]);
263 fscanf (disks[shift_table[shift][i]], "\n");
264 } close_disks ();
265
266 for (int i = 0; i < DISK_COUNT; ++i) {
267 if ((i + 1) % (DISK_COUNT/2) == 0) continue;
268 for (int j = 0; j < BLOCK_SIZE; ++j)
269 printf ("%02hhX", block_bytes[i*BLOCK_SIZE + j]);
270 } printf ("\n");
271 } break;
272 case COMMAND_WRITE: {
273 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message
274 uint8_t *write_head = block_bytes;
275 int message_size = 0;
276
277 while (*head == ' ' ||
278 *head == '\t') ++head;
279 const char *invalid = NULL;
280 size_t len = 0;
281 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
282 if (!strchr ("0123456789abcdefABCDEF", *c)) {
283 invalid = c;
284 break;
285 } len += 1;
286 } if (invalid) {
287 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
288 break;
289 } if (len != 2*MESSAGE_SIZE) {
290 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
291 break;
292 }
293
294 while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 &&
295 message_size < MESSAGE_SIZE) {
296 head += scanned;
297 message_size += 1;
298 write_head += 1;
299 if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0)
300 write_head += BLOCK_SIZE;
301 }
302 }
303
304 int shift = address % (DISK_COUNT/2);
305
306 // compute parity of first cluster
307 for (int i = 0; i < DISK_COUNT/2 - 1; ++i) {
308 for (int j = 0; j < BLOCK_SIZE; ++j)
309 block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j];
310 }
311
312 // compute parity of second cluster
313 for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) {
314 for (int j = 0; j < BLOCK_SIZE; ++j)
315 block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j];
316 }
317
318 // write needed blocks in each file in the necessary order
319 open_disks (address);
320 for (int i = 0; i < DISK_COUNT; ++i) {
321 for (int j = 0; j < BLOCK_SIZE; ++j)
322 fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]);
323 fprintf (disks[shift_table[shift][i]], "\n");
324 } close_disks ();
325 } break;
326 } free (line);
327 } return EXIT_SUCCESS;
328}
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 @@
1// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4
2// M1M2 P1P2 M3M4 M5M6 P3P4 M7M8
3// P1P2 M1M2 M3M4 P3P4 M5M6 M7M8
4// M1M2 M3M4 P1P2 M5M6 M7M8 P3P4
5#include <stdlib.h>
6#include <stdio.h>
7#include <stdint.h>
8#include <stdbool.h>
9#include <string.h>
10#include <ctype.h>
11
12#define DISK_COUNT 6
13#define MESSAGE_SIZE 8
14#define BLOCK_SIZE 2
15
16// TODO(cmmm): generate
17int shift_table[][DISK_COUNT] = {
18 { 0, 1, 2, 3, 4, 5 },
19 { 0, 2, 1, 3, 5, 4 },
20 { 1, 2, 0, 4, 5, 3 },
21};
22
23#define DISK_SIZE 0x40
24#define POPCOUNT __builtin_popcount
25#define CTZ __builtin_ctz
26
27#ifndef WIN32
28#define LINE_SIZE (2*BLOCK_SIZE + 1)
29#else
30#define LINE_SIZE (2*BLOCK_SIZE + 2)
31static ssize_t
32getline (char **restrict lineptr, size_t *restrict n, FILE *restrict stream) {
33 register char c;
34 register char *cs = NULL;
35 register int length = 0;
36 while ((c = getc (stream)) != EOF) {
37 cs = (char *) realloc (cs, ++length + 1);
38 if ((*(cs + length - 1) = c) == '\n') {
39 *(cs + length) = '\0';
40 break;
41 }
42 }
43
44 // return the allocated memory if lineptr is null
45 if ((*lineptr) == NULL) {
46 *lineptr = cs;
47 } else {
48 // check if enough memory is allocated
49 if ((length + 1) < *n)
50 *lineptr = (char *) realloc (*lineptr, length + 1);
51 memcpy (*lineptr, cs, length);
52 free (cs);
53 }
54
55 return (ssize_t) (*n = strlen (*lineptr));
56}
57#endif
58
59enum command {
60 COMMAND_NONE,
61 COMMAND_WRITE,
62 COMMAND_READ,
63};
64
65FILE *disks[DISK_COUNT];
66
67static void
68recompute_bad_disk (int bad_disk)
69{
70 int cluster = bad_disk/(DISK_COUNT/2);
71
72 for (int j = 0; j < DISK_SIZE; ++j) {
73 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE];
74 int shift = j % (DISK_COUNT/2);
75
76 // read blocks from good disks
77 int logical_bad_disk;
78 bool empty = false;
79 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
80 if (shift_table[shift][k] == bad_disk) {
81 logical_bad_disk = k;
82 continue;
83 }
84 for (int l = 0; l < BLOCK_SIZE; ++l) {
85 int c = fgetc (disks[shift_table[shift][k]]);
86 if (c == ' ') {
87 fgetc (disks[shift_table[shift][k]]);
88 empty = true;
89 } else {
90 ungetc (c, disks[shift_table[shift][k]]);
91 fscanf (disks[shift_table[shift][k]], "%02hhX",
92 &block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
93 }
94 } fgetc (disks[shift_table[shift][k]]);
95 }
96
97 if (empty) { // address empty
98 for (int l = 0; l < BLOCK_SIZE; ++l) {
99 fprintf (disks[bad_disk], " ");
100 } fprintf (disks[bad_disk], "\n");
101 continue;
102 }
103
104 // compute lost block
105 for (int l = 0; l < BLOCK_SIZE; ++l)
106 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] = 0x00;
107 for (int k = cluster*DISK_COUNT/2; k < DISK_COUNT/2 + cluster*DISK_COUNT/2; ++k) {
108 if (k == logical_bad_disk) continue;
109 for (int l = 0; l < BLOCK_SIZE; ++l)
110 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)] ^=
111 block_bytes[(k*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)];
112 }
113
114 // write lost block
115 for (int l = 0; l < BLOCK_SIZE; ++l) {
116 fprintf (disks[bad_disk], "%02hhX",
117 block_bytes[(logical_bad_disk*BLOCK_SIZE + l) % (MESSAGE_SIZE/2 + BLOCK_SIZE)]);
118 } fprintf (disks[bad_disk], "\n");
119 }
120}
121
122static void
123open_disks (uint8_t address)
124{
125 uint16_t bad_disks = 0;
126 for (int i = 0; i < DISK_COUNT; ++i) {
127 char filename[] = "disk0";
128 filename[strlen (filename) - 1] += i;
129 disks[i] = fopen (filename, "r+");
130 if (!disks[i]) { // disk file was deleted
131 disks[i] = fopen (filename, "w+");
132 if (!disks[i]) {
133 fprintf (stderr, "ERROR: unable to open file: %s\n", filename);
134 exit (EXIT_FAILURE);
135 }
136
137 fprintf (stderr, "WARNING: found bad disk (missing): %s\n", filename);
138 bad_disks |= 1 << i;
139 } else { // disk file wasn't deleted
140 fseek (disks[i], 0, SEEK_END);
141 if (ftell (disks[i]) != DISK_SIZE*LINE_SIZE) { // disk file has bad format
142 fprintf (stderr, "WARNING: found bad disk (corrupted): %s\n", filename);
143 fclose (disks[i]);
144 disks[i] = fopen (filename, "w+");
145 bad_disks |= 1 << i;
146 } else rewind (disks[i]);
147 }
148 }
149
150 // there were bad disks
151 int bad_disk_count = POPCOUNT (bad_disks);
152 if (bad_disk_count == 1) { // recompute lost disk
153 fprintf (stderr, "INFO: there is just 1 bad disk, recomputing it...\n");
154 int bad_disk = CTZ (bad_disks);
155 recompute_bad_disk (bad_disk);
156 } else if (bad_disk_count == 2 && bad_disks & ((1 << DISK_COUNT/2) - 1) && bad_disks >> DISK_COUNT/2) {
157 fprintf (stderr, "INFO: there are 2 bad disk in separate clusters, recomputing them...\n");
158 int bad_disk0 = CTZ (bad_disks);
159 int bad_disk1 = CTZ (bad_disks ^ (1 << bad_disk0));
160 recompute_bad_disk (bad_disk0);
161 recompute_bad_disk (bad_disk1);
162 } else if (bad_disk_count) { // replace all disks with empty ones, all data is lost
163 fprintf (stderr, "ERROR: too many bad disks, reinitializing the array with new disks...\n");
164 for (int i = 0; i < DISK_COUNT; ++i) {
165 for (int j = 0; j < DISK_SIZE; ++j) {
166 for (int k = 0; k < BLOCK_SIZE; ++k) {
167 fputs (" ", disks[i]);
168 } fputs ("\n", disks[i]);
169 }
170 }
171 }
172
173 // position head for writing/reading message
174 for (int i = 0; i < DISK_COUNT; ++i)
175 fseek (disks[i], address*LINE_SIZE, SEEK_SET);
176}
177
178static void
179close_disks (void)
180{
181 for (int i = 0; i < DISK_COUNT; ++i)
182 fclose (disks[i]);
183}
184
185int
186main (void)
187{
188 fprintf (stderr, "INFO: initializing RAID 50 with XOR on 6 disks with 8 byte messages...\n");
189
190 // check disk integrity on startup
191 open_disks (0);
192 close_disks ( );
193
194 for (;;) {
195 char *line = NULL;
196 size_t line_size = 0;
197 char *head;
198 int assigned;
199 int scanned;
200
201 // read whole line
202 printf ("> ");
203 scanned = getline (&line, &line_size, stdin);
204 if (scanned == -1)
205 exit (EXIT_SUCCESS);
206 else if (scanned == 1)
207 continue;
208 head = line;
209
210 uint8_t address; { // scan address
211 assigned = sscanf (head, "%hhx%n", &address, &scanned);
212 if (assigned != 1 || address >= DISK_SIZE || scanned > 2) {
213 fprintf(stderr, "ERROR: address not in set [0x00; 0x40)\n");
214 continue;
215 } head += scanned;
216 }
217
218 enum command command = COMMAND_NONE; { // scan command
219 while (*head == ' ') head += 1;
220 if (!strncmp (head, "read", 4)) {
221 head += 4;
222 command = COMMAND_READ;
223 } else if (!strncmp (head, "write", 5)) {
224 head += 5;
225 command = COMMAND_WRITE;
226 }
227 if (!isspace(*head))
228 command = COMMAND_NONE;
229 }
230
231 switch (command) {
232 case COMMAND_NONE: {
233 fprintf(stderr, "ERROR: invalid command, must be on of (read, write)\n");
234 continue;
235 } break;
236 case COMMAND_READ: {
237 // parse out message
238 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE];
239 int shift = address % (DISK_COUNT/2);
240
241 while (isspace (*head)) {
242 head += 1;
243 if (*head == '\n' ||
244 *head == '\r') {
245 *head = '\0';
246 }
247 } if (*head) {
248 fprintf (stderr, "ERROR: trailing junk after command: %s", head);
249 continue;
250 }
251
252 open_disks (address);
253 int c = fgetc (disks[0]);
254 if (c == ' ') {
255 close_disks ();
256 printf ("No data stored!\n");
257 break;
258 } ungetc (c, disks[0]);
259
260 for (int i = 0; i < DISK_COUNT; ++i) {
261 for (int j = 0; j < BLOCK_SIZE; ++j)
262 fscanf (disks[shift_table[shift][i]], "%02hhX", &block_bytes[2*i + j]);
263 fscanf (disks[shift_table[shift][i]], "\n");
264 } close_disks ();
265
266 for (int i = 0; i < DISK_COUNT; ++i) {
267 if (i % (DISK_COUNT/2) == DISK_COUNT/2 - 1) continue;
268 for (int j = 0; j < BLOCK_SIZE; ++j)
269 printf ("%02hhX", block_bytes[2*i + j]);
270 } printf ("\n");
271 } break;
272 case COMMAND_WRITE: {
273 uint8_t block_bytes[MESSAGE_SIZE/2 + BLOCK_SIZE + MESSAGE_SIZE/2 + BLOCK_SIZE] = {0}; { // scan message
274 uint8_t *write_head = block_bytes;
275 int message_size = 0;
276
277 while (*head == ' ' ||
278 *head == '\t') ++head;
279 const char *invalid = NULL;
280 size_t len = 0;
281 for (const char *c = head; *c && *c != '\r' && *c != '\n'; ++c) {
282 if (!strchr ("0123456789abcdefABCDEF", *c)) {
283 invalid = c;
284 break;
285 } len += 1;
286 } if (invalid) {
287 fprintf (stderr, "ERROR: message contains invalid character `%c'\n", *invalid);
288 break;
289 } if (len != 2*MESSAGE_SIZE) {
290 fprintf (stderr, "ERROR: expected %d hex digits for message, received %zu\n", 2*MESSAGE_SIZE, len);
291 break;
292 }
293
294 while (sscanf (head, "%2hhx%n", write_head, &scanned) == 1 &&
295 message_size < MESSAGE_SIZE) {
296 head += scanned;
297 message_size += 1;
298 write_head += 1;
299 if (message_size % ((DISK_COUNT/2 - 1)*BLOCK_SIZE) == 0)
300 write_head += BLOCK_SIZE;
301 }
302 }
303
304 int shift = address % (DISK_COUNT/2);
305
306 // compute parity of first cluster
307 for (int i = 0; i < DISK_COUNT/2 - 1; ++i) {
308 for (int j = 0; j < BLOCK_SIZE; ++j)
309 block_bytes[(DISK_COUNT/2 - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j];
310 }
311
312 // compute parity of second cluster
313 for (int i = DISK_COUNT/2; i < DISK_COUNT - 1; ++i) {
314 for (int j = 0; j < BLOCK_SIZE; ++j)
315 block_bytes[(DISK_COUNT - 1)*BLOCK_SIZE + j] ^= block_bytes[i*BLOCK_SIZE + j];
316 }
317
318 // write needed blocks in each file in the necessary order
319 open_disks (address);
320 for (int i = 0; i < DISK_COUNT; ++i) {
321 for (int j = 0; j < BLOCK_SIZE; ++j)
322 fprintf (disks[shift_table[shift][i]], "%02hhX", block_bytes[i*BLOCK_SIZE + j]);
323 fprintf (disks[shift_table[shift][i]], "\n");
324 } close_disks ();
325 } break;
326 } free (line);
327 } return EXIT_SUCCESS;
328}