|
|
1.1 root 1: //
2: // nono
3: // Copyright (C) 2024 nono project
4: // Licensed under nono-license.txt
5: //
6:
7: //
8: // ディスクイメージドライバ (QCOW2 形式)
9: //
10:
11: // https://www.qemu.org/docs/master/interop/qcow2.html
12: //
13: // L1 テーブル、L2 テーブル、データ、refcount テーブル、refcount ブロック等は
14: // いずれもクラスタ単位で割り当てる。
15: // 1クラスタのバイト数は 1U << qcow2_header.cluster_bits で可変だが、
16: // 通常 64KB。従ってこの場合、ディスクイメージの先頭の 64KB がインデックス 0、
17: // 次の $0001'0000 からの 64KB がインデックス 1 … と番号付けする。
18: //
19: // L2 テーブルは 1エントリ 8バイト (64bit) で1クラスタ分を収容する。
20: // 64KB クラスタの場合 1クラスタあたり 8192 エントリ。
21: // 1つの L2 テーブルで 64KB データクラスタ * 8192 エントリ = 512MB。
22: //
23: // L1 テーブルも 1エントリ 8バイト (64bit) で1クラスタ分なので、
24: // 64KB クラスタの場合 1クラスタあたり 8192 エントリ。
25: // L1 テーブルはヘッダで指定される位置に1つ。
26: // 運用中にエントリ数が増えたりはしない。
27: //
28: // refcount テーブル (1段目) は、1エントリ 8バイト (64bit) で、
29: // refcount ブロック (2段目) の開始アドレスを持つ。0 なら未使用(未割り当て)。
30: // refcount ブロックは、通常1エントリ 2バイト (16bit) で、ホストクラスタの
31: // 使用状況を表す。refcount が 0 なら未使用クラスタ、1 なら使用中。
32: // 2 以上ならスナップショット等で共有されていることを示すが、スナップショット
33: // 等を実装していないため現状起きない。
34: // 64KB/クラスタの場合 1ブロックに 32768 クラスタ分の refcount を収容。
35: // refcount の対象はデータクラスタではなくホストクラスタなので、単純に
36: // クラスタ #n はイメージファイル先頭から n * cluster_size バイト目のクラスタ
37: // を指す。
38: // 注: 実際は refcount_order によって可変に出来る構造だが、
39: // 現状 16bit のみ対応。
40:
41: // ログレベルは
42: // 1: 容量の拡張などの構造が変化する事案。Attach 時のサマリ。
43: // 2: Read/Write アクセスのサマリ。
44: // 3: Read/Write アクセスの詳細。
45:
46: #include "diskdriver_qcow2.h"
47: #include <fcntl.h>
48: #include <sys/stat.h>
49: #include <zlib.h>
50:
51: #define Px64 "%08x'%08x"
52: #define V64(x) (uint32)((x) >> 32), (uint32)(x)
53:
54: // 定義とか。
55: class QCOW2
56: {
57: public:
58: static constexpr uint32 HEADER_MAGIC = 0x514649fb;
59:
60: // 暗号化方法。
61: static constexpr uint32 CRYPT_NONE = 0;
62: static constexpr uint32 CRYPT_AES = 1;
63: static constexpr uint32 CRYPT_LUKS = 2;
64:
65: // 圧縮方法。
66: static constexpr uint32 COMPRESS_ZLIB = 0;
67: static constexpr uint32 COMPRESS_ZSTD = 1;
68:
69: // ヘッダの拡張タイプ
70: static constexpr uint32 EXTTYPE_END = 0;
71: static constexpr uint32 EXTTYPE_BACKING_FILENAME = 0xe2792aca;
72: static constexpr uint32 EXTTYPE_FEATURE_NAME = 0x6803f857;
73: static constexpr uint32 EXTTYPE_BITMAPS = 0x23852875;
74:
75: // L1 テーブルエントリ。
76: //
77: // 6 5 4 3 2 1 0
78: // 32109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
79: //+--------+--------+--------+--------+--------+--------+--------+--------+
80: //|U0000000 AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAA0 00000000|
81: //+--------+--------+--------+--------+--------+--------+--------+--------+
82: // U (bit 63): %0 なら L2 テーブルは未使用もしくは CoW。
83: // %1 なら refcount==1。
84: // A (bit 55-9): L2 テーブル開始位置のイメージファイル上でのオフセット。
85: // クラスタ境界に整列していること。
86: // 0 ならこの L2 (とそのクラスタ) はすべて未確保。
87: // 0: Reserved
88:
89: // L2 テーブルエントリ。
90: //
91: // 32109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
92: //+--------+--------+--------+--------+--------+--------+--------+--------+
93: //|SCDDDDDD DDDDDDDD DDDDDDDD DDDDDDDD DDDDDDDD DDDDDDDD DDDDDDDD DDDDDDDD|
94: //+--------+--------+--------+--------+--------+--------+--------+--------+
95: // S (bit 63): %0 なら未使用/圧縮/CoW クラスタを示す。
96: // %1 なら refcount==1 の標準クラスタを示す。
97: // C (bit 62): %0 なら標準クラスタ、%1 なら圧縮クラスタ。
98: // D (bit 61-0): 種類ごとのクラスタディスクリプタ。
99:
100: // 標準クラスタディスクリプタの場合。
101: //
102: // 109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
103: //+--------+--------+--------+--------+--------+--------+--------+--------+
104: //| 000000 AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAA0 0000000Z|
105: //+--------+--------+--------+--------+--------+--------+--------+--------+
106: // A (bit 55-9): クラスタオフセット。クラスタ境界に整列していること。
107: // オフセットが 0 で bit63 が %0 なら、クラスタは未確保。
108: // bit63 が %1 ならオフセットは 0 を取りうる。
109: // Z (bit 0): %1 ならこのクラスタはすべてゼロが読める。
110: // 0: Reserved
111:
112: // 圧縮クラスタディスクリプタの場合。
113: //
114: // 109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
115: //+--------+--------+--------+--------+--------+--------+--------+--------+
116: //| NNNNNN NNAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA AAAAAAAA|
117: //+--------+--------+--------+--------+--------+--------+--------+--------+
118: // A (bit(x-1)-0): オフセット。クラスタ境界整列の制約はない (通常整列
119: // していない)。
120: // N (bit61-x): Aで表されるオフセットを含むセクタを超えて、圧縮データに
121: // 使用される追加の 512 バイトセクタの数。
122: // クラスタ境界を越えても構わない。
123: // x = 62 - (cluster_bits - 8)。例えば cluster_bits=16 なら 54。
124:
125: // L1、L2、標準クラスタのディスクリプタ配置をじっとにらむと
126: // ビット位置は衝突していない。
127: static constexpr uint64 DESC_USED = 0x80000000'00000000ULL;
128: static constexpr uint64 DESC_COMPRESSED = 0x40000000'00000000ULL;
129: static constexpr uint64 DESC_OFFSET_MASK = 0x00ffffff'fffffe00ULL;
130: static constexpr uint64 DESC_ALLZERO = 0x00000000'00000001ULL;
131: };
132:
133: // QCOW2 ヘッダ。ファイル上の値はすべてビッグエンディアン。
134: struct qcow2_header
135: {
136: uint32 magic {}; // QCOW2::HEADER_MAGIC
137: uint32 version {}; // バージョン (2 か 3)
138:
139: // バッキングファイルがある時はファイル名のオフセット。
140: // バッキングファイルがない時は 0。
141: uint64 backing_file_offset {};
142:
143: // バッキングファイルがある時はファイル名の長さ。'\0' 終端ではない。
144: // バッキングファイルがない時は不定。
145: uint32 backing_file_size {};
146:
147: // クラスタのビット数。通常 16 (64KB)。
148: // 9 未満 (512バイト未満) には出来ない。
149: // 現在の QEMU 実装ではクラスタサイズ 2MB が上限のようだ。
150: uint32 cluster_bits {};
151:
152: // 仮想ディスクサイズ [byte]
153: uint64 disk_size {};
154:
155: // 暗号化方法。0: 暗号化なし、1: AES、2:LUKS。
156: uint32 crypt_method {};
157:
158: // L1 テーブルのエントリ数。
159: uint32 L1_size {};
160:
161: // L1 テーブルの開始オフセット。クラスタ境界に整列していること。
162: uint64 L1_table_offset {};
163:
164: // refcount テーブルの開始オフセット。クラスタ境界に整列していること。
165: uint64 refcount_table_offset {};
166:
167: // refcount テーブルが専有しているクラスタ数。
168: uint32 refcount_table_clusters {};
169:
170: // イメージに含まれているスナップショット数。
171: uint32 nb_snapshots {};
172:
173: // スナップショットテーブルの開始オフセット。クラスタ境界に整列。
174: uint64 snapshots_offset {};
175:
176: // ここから version >= 3 の場合のみ。
177:
178: uint64 incompatible_features {};
179: uint64 compatible_features {};
180: uint64 autoclear_features {};
181: uint32 refcount_order {};
182: uint32 header_length {};
183:
184: // ここから header_length > 104 の場合のみ。
185: uint8 compression_type {};
186: uint8 padding_105_111[7] {};
187: } __packed;
188:
189:
190: // コンストラクタ
191: DiskDriverQcow2::DiskDriverQcow2(const std::string& objname_,
192: const std::string& pathname_)
193: : inherited(objname_ + ".qcow2", pathname_)
194: {
195: // デフォルトは true (空き)。
196: freemap.SetDefault(true);
197: }
198:
199: // デストラクタ
200: DiskDriverQcow2::~DiskDriverQcow2()
201: {
202: Close();
203: }
204:
205: // 知らないファイルフォーマットなら黙って false を返す。
206: bool
207: DiskDriverQcow2::Match()
208: {
209: uint32 hdr[2];
210:
211: fd = open(pathname.c_str(), O_RDONLY);
212: if (fd < 0) {
213: return false;
214: }
215:
216: auto r = readpos(fd, hdr, sizeof(hdr), 0);
217: if (r < 0) {
218: return false;
219: }
220:
221: uint32 magic = be32toh(hdr[0]);
222: uint32 version_ = be32toh(hdr[1]);
223:
224: if (magic != QCOW2::HEADER_MAGIC) {
225: return false;
226: }
227: if (version_ != 2 && version_ != 3) {
228: return false;
229: }
230:
231: return true;
232: }
233:
234: // サポートしていない形式なら errmsg にエラーメッセージをセットして
235: // false を返す。
236: bool
237: DiskDriverQcow2::Attach(std::string& errmsg)
238: {
239: qcow2_header hdr;
240:
241: assert(fd.Valid());
242:
243: // v2 ヘッダは72バイト固定。
244: auto r = readpos(fd, &hdr, 72, 0);
245: if (r < 0) {
246: errmsg = "file is too small";
247: return false;
248: }
249:
250: // イメージ上の値はすべてビッグエンディアン。
251: // メンバに持つか、ローカルだけか、デバッグ表示するだけかで処置が違う。
252: BE32TOH(hdr.magic);
253: version = be32toh(hdr.version);
254: uint64 backing_file_offset = be64toh(hdr.backing_file_offset);
255: BE32TOH(hdr.backing_file_size);
256: cluster_bits = be32toh(hdr.cluster_bits);
257: cluster_size = 1U << cluster_bits;
258: filesize = be64toh(hdr.disk_size);
259: uint32 crypt_method = be32toh(hdr.crypt_method);
260: L1_size = be32toh(hdr.L1_size);
261: L1_table_offset = be64toh(hdr.L1_table_offset);
262: refcount_table_offset = be64toh(hdr.refcount_table_offset);
263: refcount_table_clusters = be32toh(hdr.refcount_table_clusters);
264: BE32TOH(hdr.nb_snapshots);
265: BE64TOH(hdr.snapshots_offset);
266:
267: // version 3 なら、追加で104バイト目までが固定。
268: uint64 incompatible_features = 0;
269: uint32 refcount_order = 4;
270: uint32 header_length = 72;
271: uint8 compression_type = 0;
272: if (version >= 3) {
273: r = readpos(fd, (uint8 *)&hdr + 72, 104 - 72, 72);
274: if (r < 0) {
275: errmsg = "file is too short (v3)";
276: return false;
277: }
278:
279: incompatible_features = be64toh(hdr.incompatible_features);
280: BE64TOH(hdr.compatible_features);
281: BE64TOH(hdr.autoclear_features);
282: refcount_order = be32toh(hdr.refcount_order);
283: header_length = be32toh(hdr.header_length);
284: // 続きがあれば読む。ただし v3 では 112 バイト目までが定義済み。
285: if (header_length > 112) {
286: header_length = 112;
287: }
288: if (header_length > 104) {
289: r = readpos(fd, (uint8 *)&hdr + 104, header_length - 104, 104);
290: if (r < 0) {
291: errmsg = "file is too short (v3)";
292: return false;
293: }
294: compression_type = hdr.compression_type;
295: }
296: }
297:
298: const char *crypt_method_str = CryptMethodToStr(crypt_method);
299: const char *compression_type_str = CompressionTypeToStr(compression_type);
300:
301: if (loglevel >= 1) {
302: putmsgn("%s:", pathname.c_str());
303: putmsgn("magic = %08x (%s), version = 0x%x", hdr.magic,
304: (hdr.magic == QCOW2::HEADER_MAGIC ? "ok" : "bad"), version);
305: putmsgn("backing_file_offset = 0x" Px64, V64(backing_file_offset));
306: putmsgn("backing_file_size = 0x%08x", hdr.backing_file_size);
307: putmsgn("cluster_bits = %u (size = %u)",
308: cluster_bits, (1U << cluster_bits));
309: putmsgn("disk_size = 0x" Px64, V64(filesize));
310: if (crypt_method_str) {
311: putmsgn("crypt_method = 0x%x (%s)", crypt_method, crypt_method_str);
312: } else {
313: putmsgn("crypt_method = 0x%x (unknown)", crypt_method);
314: }
315: putmsgn("L1_size = 0x%08x", L1_size);
316: putmsgn("L1_table_offset = 0x" Px64, V64(L1_table_offset));
317: putmsgn("refcount_table_offset = 0x" Px64, V64(refcount_table_offset));
318: putmsgn("refcount_table_clusters = 0x%x", refcount_table_clusters);
319: putmsgn("nb_snapshots = 0x%x", hdr.nb_snapshots);
320: putmsgn("snapshots_offset = 0x" Px64, V64(hdr.snapshots_offset));
321: if (version >= 3) {
322: putmsgn("incompatible_features = 0x" Px64,
323: V64(incompatible_features));
324: putmsgn("compatible_features = 0x" Px64,
325: V64(hdr.compatible_features));
326: putmsgn("autoclear_features = 0x" Px64,
327: V64(hdr.autoclear_features));
328: putmsgn("refcount_order = %u (bits = %u)",
329: refcount_order, (1U << refcount_order));
330: putmsgn("header_length = %d", header_length);
331: if (compression_type_str) {
332: putmsgn("compression_type = 0x%x (%s)",
333: compression_type, compression_type_str);
334: } else {
335: putmsgn("compression_type = 0x%x (unknown)",
336: compression_type);
337: }
338: }
339: }
340:
341: // header_length バイト目以降にある拡張部は使っていないので放置。
342:
343: // 外部ファイルによる COW はサポートしていない。
344: if (backing_file_offset != 0) {
345: errmsg = "backing file not supported";
346: return false;
347: }
348:
349: // 暗号化はサポートしていない。
350: if (crypt_method != QCOW2::CRYPT_NONE) {
351: if (crypt_method_str) {
352: errmsg = std::string(crypt_method_str);
353: } else {
354: errmsg = string_format("crypt_method %u", crypt_method);
355: }
356: errmsg += " not supported";
357: return false;
358: }
359:
360: // incompatible_features を調べる。
361: // 未対応のビットが立っていたらオープン時にエラーにしなければならない。
362: // 現状全部対応していない。
363: if (incompatible_features != 0) {
364: errmsg = string_format("incompatible_features=0x" Px64 " not supported",
365: V64(incompatible_features));
366: return false;
367: }
368:
369: // compatible_features は知らなくても安全に無視出来る?
370:
371: // autoclear_features は、知らなければクリアしてよい…らしい。
372: // が書き込みを伴うため Open() で処理する。
373:
374: if (refcount_order != 4) {
375: errmsg = string_format("refcount_bits=%u not supported",
376: 1U << refcount_order);
377: return false;
378: }
379:
380: // refblock_capacity は 1クラスタに収容できる refcount の数。
381: // 64KB/クラスタで refcount_bits=16 (refcount_order=4) なら 32768。
382: refblock_capacity = cluster_size >> (refcount_order - 3);
383: refblock_bits = cluster_bits - (refcount_order - 3);
384: refblock_mask = refblock_capacity - 1;
385:
386: // 圧縮方法は zlib しかサポートしていない。
387: if (compression_type != QCOW2::COMPRESS_ZLIB) {
388: if (compression_type_str) {
389: errmsg = std::string(compression_type_str);
390: } else {
391: errmsg = string_format("compression_type %u", compression_type);
392: }
393: errmsg += " not supported";
394: return false;
395: }
396:
397: return true;
398: }
399:
400: bool
401: DiskDriverQcow2::Open(bool read_only)
402: {
403: assert(pathname.empty() == false);
404:
405: if (read_only == false) {
406: // R/W なら開き直す。
407: fd = open(pathname.c_str(), O_RDWR);
408: if (fd < 0) {
409: warn("%s", pathname.c_str());
410: return false;
411: }
412:
413: // autoclear_features は、知らなければクリアしてよい…らしい。
414: // 書き込み可能になったここで行う。
415: uint64 autoclear;
416: off_t offset = offsetof(qcow2_header, autoclear_features);
417: auto r = readpos(fd, &autoclear, sizeof(autoclear), offset);
418: if (__predict_false(r < 0)) {
419: // 読めないことはないはずだが、読めなかったらたぶん相当おかしい。
420: warn("%s: %s readpos(@0x%x) failed",
421: pathname.c_str(), __func__, (uint32)offset);
422: return false;
423: }
424:
425: if (__predict_false(autoclear != 0)) {
426: autoclear = 0;
427: writepos(fd, &autoclear, sizeof(autoclear), offset);
428: // 失敗しても気にしない?
429: }
430: }
431:
432: // L1 テーブルを読み込む。
433: L1_table.resize(L1_size);
434: if (ReadTable(L1_table, L1_table_offset) == false) {
435: return false;
436: }
437:
438: // L2 テーブルキャッシュを初期化。
439: cluster_mask = cluster_size - 1;
440: L2_entries = cluster_size / sizeof(uint64);
441: L2_entries_bits = cluster_bits - 3;
442: L2_entries_mask = L2_entries - 1;
443: L2_table.resize(L2_entries);
444: cached_L1_index = (uint64)-1;
445:
446: // refcount テーブルを読み込んでオンメモリ版を構成。
447: if (ReadRefcount() == false) {
448: return false;
449: }
450:
451: // 圧縮クラスタ用のパラメータ。
452: // offset_bits がオフセット部のビット数。
453: // sector_mask はサイズ部(を右詰めしたもの) に対するマスク。
454: uint szbits = cluster_bits - 8;
455: compress_offset_bits = 62 - szbits;
456: compress_sector_mask = (1ULL << szbits) - 1;
457:
458: // 圧縮クラスタを持つイメージへの書き込みは、この仕組みと用途を
459: // 考えるとメリットがないため、サポートしない。
460: // しかし圧縮クラスタを持っているかどうかはヘッダには書いてなく、
461: // L2 ディスクリプタを全部調べる必要がある。
462: int has_compressed = HasCompressed();
463: if (has_compressed < 0) {
464: return false;
465: }
466: if (has_compressed && read_only == false) {
467: warnx("%s: Compressed QCOW2 must be read-only", pathname.c_str());
468: return false;
469: }
470:
471: // データキャッシュを初期化。
472: data_cluster.resize(cluster_size);
473: cached_data_index = (uint64)-1;
474:
475: return true;
476: }
477:
478: void
479: DiskDriverQcow2::Close()
480: {
481: fd.Close();
482: filesize = 0;
483: }
484:
485: bool
486: DiskDriverQcow2::Read(void *buf, off_t offset, size_t size)
487: {
488: putmsg(2, "%s offset=0x" Px64 ", size=%zu", __func__, V64(offset), size);
489:
490: uint64 cl_idx = offset >> cluster_bits;
491: uint64 cl_off = offset & cluster_mask;
492:
493: for (; size > 0; cl_idx++) {
494: // L1/L2_index は、キャスト云々の面倒な事故を防ぐため uint64 に
495: // しているが、値域としては事実上 uint32 で収まる。
496: uint64 L1_index = cl_idx >> L2_entries_bits;
497: uint64 L2_index = cl_idx & L2_entries_mask;
498: uint64 cl_len = std::min((uint64)size, cluster_size - cl_off);
499: uint64 L1_desc;
500: uint64 L2_desc;
501:
502: if (__predict_false(L1_index >= L1_size)) {
503: putmsg(0, "%s: L1_index(%u) is out of L1_size(%u)",
504: __func__, (uint32)L1_index, L1_size);
505: return false;
506: }
507:
508: // キャッシュに乗っていればそこから使う。
509: if (cl_idx == cached_data_index) {
510: memcpy(buf, &data_cluster[cl_off], cl_len);
511: goto done;
512: }
513:
514: L1_desc = L1_table[L1_index];
515: if (__predict_false((L1_desc & QCOW2::DESC_USED) == 0)) {
516: // L2 全体が未割当。
517: putmsg(2, " L1[0x%x] desc=0x" Px64, (uint32)L1_index, V64(L1_desc));
518: memset(buf, 0, cl_len);
519: goto done;
520: }
521:
522: // 必要なら L2_table を更新。
523: if (__predict_false(cached_L1_index != L1_index)) {
524: uint64 L2_offset = L1_desc & QCOW2::DESC_OFFSET_MASK;
525: if (ReadTable(L2_table, L2_offset) == false) {
526: cached_L1_index = (uint64)-1;
527: return false;
528: }
529: cached_L1_index = L1_index;
530: }
531:
532: L2_desc = L2_table[L2_index];
533: putmsg(2, " L2[0x%x/%04x] desc=0x" Px64,
534: (uint32)L1_index, (uint32)L2_index, V64(L2_desc));
535:
536: // if (bit63:USED) {
537: // if (bit0:ALLZERO)
538: // ゼロクラスタ;
539: // else
540: // 標準クラスタ;
541: // } else {
542: // if (bit62:COMPRESSED)
543: // 圧縮クラスタ;
544: // else
545: // 未割当クラスタ;
546: // }
547:
548: if (__predict_true((L2_desc & QCOW2::DESC_USED))) {
549: if (__predict_false((L2_desc & QCOW2::DESC_ALLZERO))) {
550: // ゼロクラスタ。
551: memset(buf, 0, cl_len);
552: } else {
553: // 標準クラスタ。
554: uint64 off = L2_desc & QCOW2::DESC_OFFSET_MASK;
555: auto r = readpos(fd, data_cluster.data(), data_cluster.size(),
556: (off_t)off);
557: if (__predict_false(r < 0)) {
558: warn("%s: %s readpos(@0x%" PRIx64 ") failed",
559: pathname.c_str(), __func__, off);
560: return false;
561: }
562: cached_data_index = cl_idx;
563:
564: memcpy(buf, &data_cluster[cl_off], cl_len);
565: }
566: } else {
567: if ((L2_desc & QCOW2::DESC_COMPRESSED)) {
568: // 圧縮クラスタ。
569:
570: uint64 offset_mask = (1ULL << compress_offset_bits) - 1;
571: uint64 off = L2_desc & offset_mask;
572: uint64 nsector =
573: (L2_desc >> compress_offset_bits) & compress_sector_mask;
574:
575: // 圧縮データを読み込む。
576: std::vector<uint8> comp(512 * (nsector + 1));
577: auto r = readpos(fd, comp.data(), comp.size(), off);
578: if (__predict_false(r < 0)) {
579: warn("%s: %s(COMPRESSED) readpos(@0x%" PRIx64 ") failed",
580: pathname.c_str(), __func__, off);
581: return false;
582: }
583:
584: // 展開。
585: z_stream z;
586: memset(&z, 0, sizeof(z));
587: if (inflateInit2(&z, -12) != Z_OK) {
588: warnx("%s: %s inflateInit2 failed",
589: pathname.c_str(), __func__);
590: return false;
591: }
592: z.next_in = comp.data();
593: z.avail_in = comp.size();
594: z.next_out = data_cluster.data();
595: z.avail_out = data_cluster.size();
596: inflate(&z, Z_FINISH);
597: inflateEnd(&z);
598: cached_data_index = cl_idx;
599:
600: memcpy(buf, &data_cluster[cl_off], cl_len);
601: } else {
602: // 未割当クラスタ。
603: memset(buf, 0, cl_len);
604: }
605: }
606:
607: done:
608: size -= cl_len;
609: if (size == 0) {
610: break;
611: }
612: buf = (void *)((uint8 *)buf + cl_len);
613: cl_off = 0;
614: }
615:
616: return true;
617: }
618:
619: bool
620: DiskDriverQcow2::Write(const void *buf, off_t offset, size_t size)
621: {
622: putmsg(2, "%s offset=0x" Px64 ", size=%zu", __func__, V64(offset), size);
623:
624: uint64 cl_idx = offset >> cluster_bits;
625: uint64 cl_off = offset & cluster_mask;
626:
627: for (; size > 0; cl_idx++) {
628: uint64 L1_index = cl_idx >> L2_entries_bits;
629: uint64 L2_index = cl_idx & L2_entries_mask;
630: uint64 cl_len = std::min((uint64)size, cluster_size - cl_off);
631: uint64 L1_desc;
632: uint64 L2_desc;
633:
634: if (__predict_false(L1_index >= L1_size)) {
635: putmsg(0, "%s: L1_index(%u) is out of L1_size(%u)",
636: __func__, (uint32)L1_index, L1_size);
637: return false;
638: }
639:
640: // キャッシュされてるところに書き込みが来たら無効にするだけ。
641: if (cl_idx == cached_data_index) {
642: cached_data_index = -1;
643: }
644:
645: L1_desc = L1_table[L1_index];
646: if (__predict_false((L1_desc & QCOW2::DESC_USED) == 0)) {
647: // L2 全体が未割当なので、L2 テーブルを作成。
648:
649: // テーブルの初期値はゼロクリアでよい。
650: // そして、この流れですぐ使うので L2_table をここで書き換える。
651: std::fill(L2_table.begin(), L2_table.end(), 0);
652: off_t newoff = AllocCluster(L2_table.data());
653: if (__predict_false(newoff < 0)) {
654: // エラーメッセージは表示済み。
655: return false;
656: }
657: cached_L1_index = L1_index;
658:
659: // L1 のエントリを更新。
660: uint64 newdesc = QCOW2::DESC_USED | (uint64)newoff;
661: L1_table[L1_index] = newdesc;
662: L1_desc = newdesc;
663: bool r = WriteEntry(L1_table_offset, L1_index, newdesc);
664: if (__predict_false(r == false)) {
665: // エラーメッセージは表示済み。
666: return false;
667: }
668:
669: putmsg(1, " L1[0x%x] desc=" Px64 " (new L2)",
670: (uint32)L1_index, V64(newdesc));
671: }
672:
673: // 必要なら L2_table を更新。
674: uint64 L2_offset = L1_desc & QCOW2::DESC_OFFSET_MASK;
675: if (__predict_false(cached_L1_index != L1_index)) {
676: if (ReadTable(L2_table, L2_offset) == false) {
677: cached_L1_index = (uint64)-1;
678: return false;
679: }
680: cached_L1_index = L1_index;
681: }
682:
683: L2_desc = L2_table[L2_index];
684: putmsg(2, " L2[0x%x/%04x] desc=0x" Px64,
685: (uint32)L1_index, (uint32)L2_index, V64(L2_desc));
686:
687: // if (bit63:USED) {
688: // if (bit0:ALLZERO)
689: // ゼロクラスタ;
690: // else
691: // 標準クラスタ;
692: // } else {
693: // if (bit62:COMPRESSED)
694: // 圧縮クラスタ;
695: // else
696: // 未割当クラスタ;
697: // }
698:
699: if (__predict_true((L2_desc & QCOW2::DESC_USED))) {
700: if (__predict_false((L2_desc & QCOW2::DESC_ALLZERO))) {
701: // ゼロクラスタ。
702: if (is_mem_zero(buf, cl_len)) {
703: // 書き込みデータがゼロなら何もしない。
704: } else {
705: // 割り当てて書き出す。
706: goto alloc;
707: }
708: } else {
709: // 標準クラスタ。
710: uint64 off = (L2_desc & QCOW2::DESC_OFFSET_MASK) + cl_off;
711: auto r = writepos(fd, buf, cl_len, (off_t)off);
712: if (__predict_false(r < 0)) {
713: warn("%s: %s writepos(@0x%" PRIx64 ") failed",
714: pathname.c_str(), __func__, off);
715: return false;
716: }
717: }
718: } else {
719: if ((L2_desc & QCOW2::DESC_COMPRESSED)) {
720: // 圧縮クラスタ。
721: // 書き込みは発生しないはずなのでここには来ないはずだが
722: // もし来てしまったらディスク I/O エラーで帰る。
723: warnx("%s: Compressed cluster not supported [L1=%u L2=%u]",
724: pathname.c_str(), (uint32)L1_index, (uint32)L2_index);
725: return false;
726: } else {
727: // 未割当クラスタ。
728: if (version >= 3 && is_mem_zero(buf, cl_len)) {
729: // 書き込みデータがすべてゼロならゼロクラスタにしたい。
730: // version 2 にはゼロクラスタはない。
731: uint64 newdesc = QCOW2::DESC_USED | QCOW2::DESC_ALLZERO;
732: L2_table[L2_index] = newdesc;
733: if (WriteEntry(L2_offset, L2_index, newdesc) == false) {
734: // エラーメッセージは表示済み。
735: return false;
736: }
737: putmsg(1, " L2[0x%x/%04x] desc=0x" Px64 " (new zero)",
738: (uint32)L1_index, (uint32)L2_index, V64(newdesc));
739: } else {
740: alloc:
741: std::vector<uint8> tmp(cluster_size);
742: memcpy(tmp.data() + cl_off, buf, cl_len);
743: off_t newoff = AllocCluster(tmp.data());
744: if (__predict_false(newoff < 0)) {
745: // エラーメッセージは表示済み。
746: return false;
747: }
748:
749: // L2 のエントリを更新。
750: uint64 newdesc = QCOW2::DESC_USED | (uint64)newoff;
751: L2_table[L2_index] = newdesc;
752: if (WriteEntry(L2_offset, L2_index, newdesc) == false) {
753: // エラーメッセージは表示済み。
754: return false;
755: }
756: putmsg(1, " L2[0x%x/%04x] desc=0x" Px64 " (new data)",
757: (uint32)L1_index, (uint32)L2_index, V64(newdesc));
758: }
759: }
760: }
761:
762: size -= cl_len;
763: if (size == 0) {
764: break;
765: }
766: buf = (const void *)((const uint8 *)buf + cl_len);
767: cl_off = 0;
768: }
769:
770: return true;
771: }
772:
773: // 内部関数
774:
775: // イメージ中に圧縮クラスタがあるか調べる。
776: // L2 ディスクリプタをすべて調べて、圧縮クラスタが一つでも見付かれば 1 を返す。
777: // 見付からなければ 0 を返す。
778: // エラーが起きれば warn() 系でエラーメッセージを表示して -1 を返す。
779: // L2_table キャッシュも更新する。
780: int
781: DiskDriverQcow2::HasCompressed()
782: {
783: // どうせ L2 テーブルを全部読むのなら、起動直後は大抵ディスクの
784: // 先頭をアクセスするのだから、L1_table[] を後ろから前に読んでいって、
785: // L1_table[0] のテーブルをそのままキャッシュしておく。
786:
787: int L1_index = L1_table.size() - 1;
788: for (; L1_index >= 0; L1_index--) {
789: uint64 L1_desc = L1_table[L1_index];
790: if ((L1_desc & QCOW2::DESC_USED) == 0) {
791: continue;
792: }
793: // L2 テーブルを読み込む。
794: uint64 L2_offset = L1_desc & QCOW2::DESC_OFFSET_MASK;
795: if (ReadTable(L2_table, L2_offset) == false) {
796: return -1;
797: }
798: cached_L1_index = L1_index;
799:
800: // 全数検査。
801: constexpr uint64 mask = QCOW2::DESC_USED | QCOW2::DESC_COMPRESSED;
802: for (uint L2_index = 0; L2_index < L2_entries; L2_index++) {
803: uint64 L2_desc = L2_table[L2_index];
804: if ((L2_desc & mask) == QCOW2::DESC_COMPRESSED) {
805: // 圧縮クラスタあり!
806: return 1;
807: }
808: }
809: }
810:
811: return 0;
812: }
813:
814: // ファイルの off の位置から uint64 を buf.size() 個読み出して返す。
815: // 失敗すれば warn() 系でエラーメッセージを表示してから false を返す。
816: bool
817: DiskDriverQcow2::ReadTable(std::vector<uint64>& buf, uint64 off)
818: {
819: size_t bytes = buf.size() * sizeof(buf[0]);
820: auto r = readpos(fd, buf.data(), bytes, (off_t)off);
821: if (__predict_false(r < 0)) {
822: warn("%s: %s readpos(@0x%" PRIx64 ") failed",
823: pathname.c_str(), __func__, off);
824: return false;
825: }
826:
827: for (uint i = 0, end = buf.size(); i < end; i++) {
828: BE64TOH(buf[i]);
829: }
830:
831: return true;
832: }
833:
834: // 新しいクラスタを確保して buf を書き込む。
835: // buf は cluster_size [バイト] であること。
836: // 書き込めれば新しいクラスタの位置 (ファイル先頭からのオフセット) を返す。
837: // 失敗すれば -1 を返す。
838: off_t
839: DiskDriverQcow2::AllocCluster(const void *buf)
840: {
841: // refcount テーブルから空きクラスタを探す。
842: uint64 hcl_idx = AllocRefcount();
843: if ((int64)hcl_idx == -1) {
844: return -1;
845: }
846: uint64 newoff = hcl_idx << cluster_bits;
847:
848: auto r = writepos(fd, buf, cluster_size, (off_t)newoff);
849: if (__predict_false(r < 0)) {
850: warn("%s: %s writepos(@0x%" PRIx64 ") failed",
851: pathname.c_str(), __func__, newoff);
852: return -1;
853: }
854:
855: return (off_t)newoff;
856: }
857:
858: // ファイルの baseoff[index] の位置に data を書き出す。
859: // 失敗すれば warn() 系でエラーメッセージを表示してから false を返す。
860: bool
861: DiskDriverQcow2::WriteEntry(uint64 baseoff, uint64 index, uint64 data)
862: {
863: uint64 offset = baseoff + index * sizeof(uint64);
864: uint64 be_data = htobe64(data);
865:
866: auto r = writepos(fd, &be_data, sizeof(be_data), (off_t)offset);
867: if (__predict_false(r < 0)) {
868: warn("%s: %s writepos(@0x%" PRIx64 ") failed",
869: pathname.c_str(), __func__, offset);
870: return false;
871: }
872:
873: return true;
874: }
875:
876: // ディスクイメージ上の refcount テーブルを読み込んで、オンメモリ版を構成する。
877: bool
878: DiskDriverQcow2::ReadRefcount()
879: {
880: uint64 reftable_capacity =
881: refcount_table_clusters << (cluster_bits - 3/*sizeof(uint64)*/);
882: uint32 reftable_idx;
883:
884: // refcount テーブル(1段目) を一旦全部読み込む。
885: std::vector<uint64> reftable(reftable_capacity);
886: auto r = readpos(fd, reftable.data(), reftable_capacity * sizeof(uint64),
887: (off_t)refcount_table_offset);
888: if (__predict_false(r < 0)) {
889: warn("%s: %s readpos(@0x%" PRIx64 ") failed",
890: pathname.c_str(), __func__, refcount_table_offset);
891: return false;
892: }
893:
894: for (reftable_idx = 0; reftable_idx < reftable_capacity; reftable_idx++) {
895: // refcount ブロック (2段目) の位置を取得。
896: uint64 refblock_offset = reftable[reftable_idx];
897:
898: // 通常あるとは思えないが、仕様上は穴空きは許されている。
899: // どうせほぼゼロなので先にゼロかどうか調べる。
900: if (refblock_offset == 0) {
901: continue;
902: }
903: refblock_offset = be64toh(refblock_offset);
904:
905: // 書き込み時のために、このブロックのオフセットを覚えておく。
906: if (reftable_idx >= refcount_block_offset.size()) {
907: refcount_block_offset.resize(reftable_idx + 1);
908: }
909: refcount_block_offset[reftable_idx] = refblock_offset;
910:
911: // refcount ブロック(2段目) を読み込む。
912: std::vector<uint16> refblock(refblock_capacity);
913: r = readpos(fd, refblock.data(), cluster_size, (off_t)refblock_offset);
914: if (__predict_false(r < 0)) {
915: warn("%s: %s readpos(@0x%" PRIx64 ") failed",
916: pathname.c_str(), __func__, refblock_offset);
917: return false;
918: }
919:
920: // ブロック内の refcount がすべてゼロなら飛ばしておく。
921: if (is_mem_zero(refblock.data(), cluster_size)) {
922: continue;
923: }
924:
925: // 少なくとも使用中の refcount があるのでここまでは拡張。
926: uint64 e = reftable_idx << refblock_bits;
927: freemap.Expand(e + refblock_capacity);
928:
929: for (uint i = 0; i < refblock_capacity; i++) {
930: // イメージ上の値は BE なので 0 かどうかだけで比較する。
931: // イメージ上は refcount なので >0 が使用中だが
932: // メモリ上は freemap なので false が使用中。
933: if (refblock[i] != 0) {
934: freemap.ClearBit(e + i);
935: }
936: }
937: }
938:
939: return true;
940: }
941:
942: // 空いてるホストクラスタを探して、ホストクラスタ番号を返す。
943: // 失敗すれば warn() 系でエラーメッセージを表示してから (int64)-1 を返す。
944: uint64
945: DiskDriverQcow2::AllocRefcount()
946: {
947: uint64 reftable_capacity =
948: refcount_table_clusters << (cluster_bits - 3/*sizeof(uint64)*/);
949: uint64 hcl_idx = 0;
950:
951: // refcount を元に空きクラスタを探す。
952: if (FindCluster(&hcl_idx) == false) {
953: return -1;
954: }
955: if ((int64)hcl_idx >= 0) {
956: // 見付かった。
957: return hcl_idx;
958: }
959: // 割り当て済みの refcount ブロックに空きがなかった。
960:
961: // refcount テーブル(1段目)から空きを探す。
962: uint64 new_table_idx = 0;
963: for (uint64 end = refcount_block_offset.size();
964: new_table_idx < end; new_table_idx++)
965: {
966: if (refcount_block_offset[new_table_idx] == 0) {
967: break;
968: }
969: }
970: if (__predict_false(new_table_idx >= reftable_capacity)) {
971: // refcount テーブル(1段目)の拡張は未実装。
972: // ホストイメージサイズが 16TB (64KB/クラスタ時) までは起きない。
973: warnx("%s: No free refcount table! (hcl=%" PRIx64 ")",
974: pathname.c_str(), hcl_idx);
975: return -1;
976: }
977:
978: // new_table_idx が新しく割り当て可能になる refcount ブロック番号。
979: // new_table_idx == 1 ならホストクラスタ 32768-65535 が未使用なので、
980: // この先頭のクラスタを refcount ブロック用にする。
981: uint64 new_block_idx = (new_table_idx << refblock_bits) + 0/*先頭*/;
982: uint64 new_block_offset = new_block_idx << cluster_bits;
983:
984: // オンメモリのほうを更新。
985: freemap.Expand(new_block_idx + refblock_capacity);
986: freemap.ClearBit(new_block_idx);
987:
988: // イメージのほうも更新。
989: std::vector<uint8> refblock(cluster_size);
990: *(uint16 *)&refblock[0] = htobe16(1);
991: auto n = writepos(fd, refblock.data(), refblock.size(),
992: (off_t)new_block_offset);
993: if (__predict_false(n < 0)) {
994: warn("%s: %s writepos(@0x%" PRIx64 ", %zu) failed",
995: pathname.c_str(), __func__, new_block_offset, refblock.size());
996: return -1;
997: }
998:
999: // refcount テーブル(1段目)に今追加したブロック(2段目)をリンク。
1000: // オンメモリのほうを更新。
1001: if (new_table_idx >= refcount_block_offset.size()) {
1002: refcount_block_offset.resize(new_table_idx + 1);
1003: }
1004: refcount_block_offset[new_table_idx] = new_block_offset;
1005: // イメージも更新。
1006: auto r = WriteEntry(refcount_table_offset, new_table_idx, new_block_offset);
1007: if (__predict_false(r == false)) {
1008: return -1;
1009: }
1010:
1011: // もう一度探す。
1012: // refcount ブロックが増えたので、今度は見付かるはず。
1013: if (FindCluster(&hcl_idx) == false) {
1014: return -1;
1015: }
1016: if ((int64)hcl_idx < 0) {
1017: warnx("%s: Refcount block was added but no free cluster found??",
1018: pathname.c_str());
1019: }
1020: return hcl_idx;
1021: }
1022:
1023: // freemap から空きホストクラスタを探す。
1024: // 見付かれば *hcl_idx_p にホストクラスタ番号を書き戻して true を返す。
1025: // 見付からなければ *hcl_idx_p に -1 を書き戻して true を返す。
1026: // 失敗すれば warn() 系でエラーメッセージを表示してから false を返す。
1027: bool
1028: DiskDriverQcow2::FindCluster(uint64 *hcl_idx_p)
1029: {
1030: uint64 hcl_idx = 0;
1031:
1032: for (size_t i = 0, iend = freemap.DataSize(); i < iend; i++) {
1033: uint64 data = freemap.GetData(i);
1034: if (__predict_true(data == 0)) {
1035: continue;
1036: }
1037: // 空きのある 64 ビットが見つかった。
1038:
1039: uint32 b = __builtin_ctzll(data);
1040: hcl_idx = i * 64 + b;
1041:
1042: // ここを使用中にする。
1043: freemap.ClearBit(hcl_idx);
1044:
1045: // イメージにもこのエントリだけ書き込む。
1046: uint64 reftable_idx = hcl_idx >> refblock_bits;
1047: uint64 refblock_idx = hcl_idx & refblock_mask;
1048: uint64 refblock_offset = refcount_block_offset[reftable_idx];
1049: uint64 offset = refblock_offset + refblock_idx * sizeof(uint16);
1050: uint16 refcount = htobe16(1);
1051: auto r = writepos(fd, &refcount, sizeof(refcount), (off_t)offset);
1052: if (__predict_false(r < 0)) {
1053: warn("%s: %s refcount writepos(@0x%" PRIx64 ") failed",
1054: pathname.c_str(), __func__, offset);
1055: return false;
1056: }
1057:
1058: *hcl_idx_p = hcl_idx;
1059: return true;
1060: }
1061:
1062: // 見付からなかった。
1063: *hcl_idx_p = -1;
1064: return true;
1065: }
1066:
1067: // src から len バイトがすべてゼロなら true を返す。
1068: /*static*/ bool
1069: DiskDriverQcow2::is_mem_zero(const void *src, size_t len)
1070: {
1071: const uint8 *s = (const uint8 *)src;
1072:
1073: size_t n = (size_t)(uintptr_t)s & 7;
1074: if (__predict_false(n != 0)) {
1075: n = 8 - n;
1076: len -= n;
1077: do {
1078: if (*s++ != 0) {
1079: return false;
1080: }
1081: } while (--n != 0);
1082: }
1083:
1084: n = len / 8;
1085: do {
1086: if (*(const uint64 *)s != 0) {
1087: return false;
1088: }
1089: s += 8;
1090: } while (--n != 0);
1091:
1092: n = len & 7;
1093: if (__predict_false(n != 0)) {
1094: do {
1095: if (*s++ != 0) {
1096: return false;
1097: }
1098: } while (--n != 0);
1099: }
1100: return true;
1101: }
1102:
1103: // crypt_method に対応する文字列を返す。知らない値なら NULL を返す。
1104: /*static*/ const char *
1105: DiskDriverQcow2::CryptMethodToStr(uint32 crypt_method_)
1106: {
1107: switch (crypt_method_) {
1108: case QCOW2::CRYPT_NONE: return "None";
1109: case QCOW2::CRYPT_AES: return "AES";
1110: case QCOW2::CRYPT_LUKS: return "LUKS";
1111: default:
1112: break;
1113: }
1114: return NULL;
1115: }
1116:
1117: // compression_type に対応する文字列を返す。知らない値なら NULL を返す。
1118: /*static*/ const char *
1119: DiskDriverQcow2::CompressionTypeToStr(uint32 compression_type_)
1120: {
1121: switch (compression_type_) {
1122: case QCOW2::COMPRESS_ZLIB: return "zlib";
1123: case QCOW2::COMPRESS_ZSTD: return "zstd";
1124: default:
1125: break;
1126: }
1127: return NULL;
1128: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.