-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworker.cpp
2594 lines (2359 loc) · 81.6 KB
/
worker.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file worker.cpp
*
* @copyright 2021-2022 extratype
*/
#include "worker.hpp"
using std::bad_alloc;
using std::shared_mutex;
namespace chunkdisk
{
extern std::vector<ChunkDiskWorker>& GetWorkers(SPD_STORAGE_UNIT* StorageUnit);
static constexpr auto STANDBY_MS = u32(60000);
static constexpr auto LOW_LOAD_THRESHOLD = u32(2); // load by CPU and file system, not by media
static constexpr auto MAX_QD = u32(32); // QD32
static constexpr auto STOP_TIMEOUT_MS = u32(5000);
ChunkDiskWorker::ChunkDiskWorker(ChunkDiskService& service)
: service_(service),
max_handles_per_([&service]() -> u32
{
auto& base = service.bases[0];
return max(1, service.MaxTransferLength() / base.BlockBytes(base.ChunkBlocks(1)));
}())
{
}
ChunkDiskWorker::~ChunkDiskWorker()
{
auto err = Stop(STOP_TIMEOUT_MS);
if (err != ERROR_SUCCESS && err != ERROR_INVALID_STATE)
{
SpdStorageUnitShutdown(service_.storage_unit); // fatal
Terminate();
}
}
DWORD ChunkDiskWorker::Start()
{
if (IsRunning()) return ERROR_INVALID_STATE;
try
{
// make class movable
mutex_working_ = std::make_unique<shared_mutex>();
mutex_buffers_ = std::make_unique<shared_mutex>();
mutex_handles_ = std::make_unique<shared_mutex>();
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
wait_event_.reset(CreateEventW(nullptr, TRUE, TRUE, nullptr));
if (!wait_event_) return GetLastError();
spd_ovl_event_.reset(CreateEventW(nullptr, TRUE, TRUE, nullptr));
if (!spd_ovl_event_)
{
wait_event_.reset();
return GetLastError();
}
iocp_.reset(CreateIoCompletionPort(
INVALID_HANDLE_VALUE, nullptr, 0, 1));
if (!iocp_)
{
spd_ovl_event_.reset();
wait_event_.reset();
return GetLastError();
}
spd_ovl_ = OVERLAPPED();
spd_ovl_.hEvent = spd_ovl_event_.get();
try
{
thread_ = std::thread(
[](LPVOID param) { recast<ChunkDiskWorker*>(param)->DoWorks(); },
this);
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
catch (const std::system_error& e)
{
spd_ovl_event_.reset();
wait_event_.reset();
iocp_.reset();
return e.code().value();
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::StopAsync(HANDLE& handle_out)
{
if (!IsRunning()) return ERROR_INVALID_STATE;
if (!PostQueuedCompletionStatus(iocp_.get(), 0,
CK_STOP, nullptr))
{
return GetLastError();
}
// native_handle() closed in detach()
auto h = HANDLE(nullptr);
if (!DuplicateHandle(GetCurrentProcess(), thread_.native_handle(),
GetCurrentProcess(), &h, 0, FALSE, DUPLICATE_SAME_ACCESS))
{
return GetLastError();
}
try
{
thread_.detach();
}
catch (const std::system_error& e)
{
CloseHandle(h);
return e.code().value();
}
handle_out = h;
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::Stop(DWORD timeout_ms)
{
if (!IsRunning()) return ERROR_INVALID_STATE;
auto h = HANDLE(nullptr);
auto err = StopAsync(h);
if (err != ERROR_SUCCESS) return err;
err = WaitForSingleObject(h, timeout_ms);
CloseHandle(h);
if (err == WAIT_OBJECT_0) return ERROR_SUCCESS;
if (err == WAIT_ABANDONED) return ERROR_ABANDONED_WAIT_0;
if (err == WAIT_TIMEOUT) return ERROR_TIMEOUT;
return GetLastError();
}
void ChunkDiskWorker::Terminate()
{
if (!IsRunning())
{
iocp_.reset();
return;
}
auto lkw = SRWLock(*mutex_working_, true, std::defer_lock);
if (lkw.try_lock())
{
if (!working_.empty())
{
auto* work = &*working_.begin();
while (work != nullptr)
{
for (auto& op : work->ops) ReportOpResult(op, ERROR_OPERATION_ABORTED);
CompleteWork(work, &work);
}
}
lkw.unlock();
}
iocp_.reset();
auto lkh = SRWLock(*mutex_handles_, true, std::defer_lock);
if (lkh.try_lock())
{
for (auto&& p : chunk_handles_)
{
auto& cfh = p.second;
if (cfh.handle_ro) CancelIo(cfh.handle_ro.get());
if (cfh.handle_rw) CancelIo(cfh.handle_rw.get());
}
lkh.unlock();
}
try
{
thread_.detach();
}
catch (const std::system_error&)
{
return;
}
}
DWORD ChunkDiskWorker::Wait(DWORD timeout_ms)
{
if (!IsRunning()) return ERROR_INVALID_STATE;
while (true)
{
auto lk = SRWLock(*mutex_working_, false);
if (working_.size() < MAX_QD)
{
return ERROR_SUCCESS;
// PostWork() may still fail with ERROR_BUSY due to messages
}
if (!ResetEvent(wait_event_.get())) return GetLastError();
lk.unlock();
auto ticks = (timeout_ms != INFINITE) ? GetTickCount64() : 0;
auto err = WaitForSingleObject(wait_event_.get(), timeout_ms);
if (err != WAIT_OBJECT_0)
{
if (err == WAIT_ABANDONED) return ERROR_ABANDONED_WAIT_0;
if (err == WAIT_TIMEOUT) return ERROR_TIMEOUT;
return GetLastError();
}
// PostMsg() ignores queue depth so queue may still be full
ticks = (timeout_ms != INFINITE) ? (GetTickCount64() - ticks) : 0;
timeout_ms = (timeout_ms > ticks) ? DWORD(timeout_ms - ticks) : 0;
}
}
DWORD ChunkDiskWorker::PostWork(SPD_STORAGE_UNIT_OPERATION_CONTEXT* context, const ChunkOpKind op_kind,
const u64 block_addr, const u64 count)
{
if (!IsRunning()) return ERROR_INVALID_STATE;
// check queue depth
auto lk = SRWLock(*mutex_working_, false);
if (working_.size() >= MAX_QD) return ERROR_BUSY;
// PostWork() from single dispatcher, MAX_QD still apply after unlocking
// messages ignore MAX_QD anyway
lk.unlock();
// expects something to do
// expects ChunkWork::ops not empty
// block_addr already checked by the WinSpd driver
// Unmap() filters empty ranges
if (count == 0) return ERROR_SUCCESS;
// prepare work
auto* const ctx_buffer = context->DataBuffer;
auto& base = service_.bases[0];
auto work = ChunkWork();
auto err = DWORD(ERROR_SUCCESS);
if (op_kind == READ_CHUNK || op_kind == WRITE_CHUNK)
{
// prepare buffer
// write back to ctx_buffer if read request processed immediately
// write request is never processed immediately
err = GetBuffer(work.buffer);
if (err != ERROR_SUCCESS)
{
SetScsiError(&context->Response->Status, SCSI_SENSE_HARDWARE_ERROR, SCSI_ADSENSE_NO_SENSE);
return err;
}
// whole disk as pages
// r.start_idx, r.end_idx: page index
// r.start_off, r.end_off: block offset in page
const auto r = base.BlockPageRange(0, block_addr, block_addr + count);
if (base.IsWholePages(r.start_off, r.end_off) || r.start_idx == r.end_idx)
{
// no need to page align buffer
auto* ops_buffer = work.buffer.get();
if (op_kind == WRITE_CHUNK) memcpy(ops_buffer, ctx_buffer, base.BlockBytes(count));
err = PrepareOps(work, op_kind, block_addr, count, ops_buffer);
}
else
{
// page align buffer to the next page
// GetBuffer() provides margin of one page
auto* ops_buffer = LPVOID(recast<u8*>(work.buffer.get()) + base.BlockBytes(r.start_off));
if (op_kind == WRITE_CHUNK) memcpy(ops_buffer, ctx_buffer, base.BlockBytes(count));
while (true)
{
// head
if (r.start_off != 0)
{
err = PrepareOps(work, op_kind, block_addr, base.page_length - r.start_off, ops_buffer);
if (err != ERROR_SUCCESS) break;
}
// aligned to page
// [start_idx, end_idx] -> [saddr, eaddr)
auto saddr = base.PageBlocks(r.start_idx) + ((r.start_off != 0) ? base.page_length : 0);
auto eaddr = base.PageBlocks(r.end_idx) + ((r.end_off != base.page_length) ? 0 : base.page_length);
if (saddr != eaddr)
{
err = PrepareOps(work, op_kind, saddr, eaddr - saddr, ops_buffer);
if (err != ERROR_SUCCESS) break;
}
// tail
if (r.end_off != base.page_length)
{
err = PrepareOps(work, op_kind, base.PageBlocks(r.end_idx), r.end_off, ops_buffer);
if (err != ERROR_SUCCESS) break;
}
break;
}
}
}
else if (op_kind == UNMAP_CHUNK)
{
// buffer is nullptr for UNMAP_CHUNK
if (service_.trim_chunk || service_.zero_chunk)
{
auto* descs = recast<SPD_UNMAP_DESCRIPTOR*>(ctx_buffer);
for (auto i = u64(0); i < count; ++i)
{
auto* ops_buffer = LPVOID(nullptr);
err = PrepareOps(work, op_kind, descs[i].BlockAddress, descs[i].BlockCount, ops_buffer);
if (err != ERROR_SUCCESS) break;
}
}
}
else
{
SetScsiError(&context->Response->Status, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ADSENSE_ILLEGAL_COMMAND);
return ERROR_INVALID_FUNCTION;
}
if (err != ERROR_SUCCESS)
{
if (work.num_errors == 0)
{
// internal error, e.g. ERROR_NOT_ENOUGH_MEMORY
SetScsiError(&context->Response->Status, SCSI_SENSE_HARDWARE_ERROR, SCSI_ADSENSE_NO_SENSE);
}
else
{
// the first error reported
// same effect calling SpdStatusUnitStatusSetSense()
context->Response->Status = work.response.Status;
}
service_.SetPostFileTime(GetSystemFileTime());
return err;
}
if (work.num_completed == work.ops.size())
{
// work.ops may be empty for UNMAP_CHUNK
// read all done immediately
if (op_kind == READ_CHUNK) memcpy(ctx_buffer, work.ops[0].buffer, base.BlockBytes(count));
ReturnBuffer(std::move(work.buffer));
service_.SetPostFileTime(GetSystemFileTime());
return ERROR_SUCCESS;
}
// start async.
work.SetContext(context->Response->Hint, context->Response->Kind);
try
{
lk.switch_lock(); // now exclusive
lk.lock();
auto work_it = working_.emplace(working_.end(), std::move(work)); // invalidates ChunkOpState::owner
work_it->it = work_it;
for (auto& op : work_it->ops) op.owner = &*work_it;
const auto post_ft = GetSystemFileTime();
if (!PostQueuedCompletionStatus(iocp_.get(), 0,
CK_POST, recast<OVERLAPPED*>(&*work_it)))
{
err = GetLastError();
working_.erase(work_it);
SetScsiError(&context->Response->Status, SCSI_SENSE_HARDWARE_ERROR, SCSI_ADSENSE_NO_SENSE);
return err;
}
lk.unlock();
service_.SetPostFileTime(post_ft);
}
catch (const bad_alloc&)
{
SetScsiError(&context->Response->Status, SCSI_SENSE_HARDWARE_ERROR, SCSI_ADSENSE_NO_SENSE);
return ERROR_NOT_ENOUGH_MEMORY;
}
return ERROR_IO_PENDING;
}
void ChunkDiskWorker::DoWorks()
{
auto bytes_transferred = DWORD();
auto ckey = u64();
auto* overlapped = (OVERLAPPED*)(nullptr);
auto next_timeout = DWORD(INFINITE); // no resources to be freed at start
auto next_check_time = u64();
while (true)
{
auto error = GetQueuedCompletionStatus(
iocp_.get(), &bytes_transferred, &ckey, &overlapped, next_timeout)
? ERROR_SUCCESS : GetLastError();
if (overlapped == nullptr)
{
if (error == WAIT_TIMEOUT)
{
next_timeout = IdleWork();
if (next_timeout == INFINITE) continue; // sleep
}
else
{
// error == ERROR_SUCCESS && ckey == CK_STOP
// error != ERROR_SUCCESS
StopWorks();
return;
}
}
else if (ckey == CK_POST)
{
// do work...
auto& work = *recast<ChunkWork*>(overlapped);
for (auto& op : work.ops)
{
if (PostOp(op) != ERROR_IO_PENDING)
{
if (CompleteWork(op.owner)) break;
}
}
}
else if (ckey == CK_IO)
{
auto& state = *GetOverlappedOp(overlapped);
if (CompleteIO(state, error, bytes_transferred) != ERROR_IO_PENDING) CompleteWork(state.owner);
}
if (next_timeout == INFINITE)
{
// woke up
next_timeout = STANDBY_MS;
next_check_time = GetSystemFileTime() + u64(STANDBY_MS) * 10000;
}
else
{
// check only when active
auto check_time = GetSystemFileTime();
if (check_time >= next_check_time)
{
auto next_check = PeriodicCheck();
next_check_time = check_time + u64(next_check) * 10000;
}
}
}
}
DWORD ChunkDiskWorker::PrepareMsg(ChunkWork& msg, ChunkOpKind kind, u64 idx, u64 start_off, u64 end_off, LPVOID buffer)
{
try
{
msg.ops.emplace_back(&msg, kind, idx, start_off, end_off, 0, buffer);
return ERROR_SUCCESS;
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
}
DWORD ChunkDiskWorker::PostMsg(ChunkWork msg)
{
if (msg.ops.empty()) return ERROR_INVALID_PARAMETER;
// this check is not thread safe,
// it's fine because we only use StartWorkers() and StopWorkers()
if (!IsRunning()) return ERROR_INVALID_STATE;
// ignore queue depth
auto err = DWORD(ERROR_IO_PENDING);
try
{
auto lk = SRWLock(*mutex_working_, true);
auto work_it = working_.emplace(working_.end(), std::move(msg)); // invalidates ChunkOpState::owner
work_it->it = work_it;
for (auto& op : work_it->ops) op.owner = &*work_it;
if (!PostQueuedCompletionStatus(iocp_.get(), 0,
CK_POST, recast<OVERLAPPED*>(&*work_it)))
{
err = GetLastError();
working_.erase(work_it);
return err;
}
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
// msg will be handled later
return ERROR_IO_PENDING;
}
DWORD ChunkDiskWorker::GetBuffer(Pages& buffer)
{
auto lk = SRWLock(*mutex_buffers_, true);
buffers_load_ += 1;
buffers_load_max_ = max(buffers_load_max_, buffers_load_);
if (buffers_.empty())
{
lk.unlock();
// align buffer to pages
// additional page for unaligned requests
auto buffer_size = service_.MaxTransferLength() + u32(service_.bases[0].PageBytes(1));
auto new_buffer = Pages(VirtualAlloc(nullptr, buffer_size, MEM_COMMIT, PAGE_READWRITE));
if (!new_buffer)
{
lk.lock();
buffers_load_ -= 1;
return ERROR_NOT_ENOUGH_MEMORY;
}
buffer = std::move(new_buffer);
return ERROR_SUCCESS;
}
else
{
buffer = std::move(buffers_.front());
buffers_.pop_front();
return ERROR_SUCCESS;
}
}
DWORD ChunkDiskWorker::ReturnBuffer(Pages buffer)
{
if (!buffer) return ERROR_INVALID_PARAMETER;
try
{
auto lk = SRWLock(*mutex_buffers_, true);
buffers_load_ -= 1;
// LIFO order
buffers_.emplace_front(std::move(buffer));
}
catch (const bad_alloc&)
{
// ignore error, will retry in GetBuffer()
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::OpenChunkAsync(const u64 chunk_idx, const bool is_write,
HANDLE& handle_out, ChunkOpState* state)
{
auto lk = SRWLock(*mutex_handles_, true);
auto it = chunk_handles_.find(chunk_idx);
auto emplaced = false;
if (it == chunk_handles_.end())
{
// try to keep max. by closing old handles
if (chunk_handles_.size() >= max_handles_per_ * MAX_QD)
{
for (auto it1 = chunk_handles_.begin(); it1 != chunk_handles_.end();)
{
auto& cfh1 = (*it1).second;
if (!(cfh1.refs_ro == 0 && cfh1.refs_rw == 0 && !cfh1.locked && cfh1.waiting.empty()))
{
++it1;
continue;
}
it1 = chunk_handles_.erase(it1);
if (chunk_handles_.size() < max_handles_per_ * MAX_QD) break;
}
}
try
{
it = chunk_handles_.try_emplace(chunk_idx).first;
emplaced = true;
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
}
else
{
chunk_handles_.reinsert_back(it);
}
// open or reuse or error
auto& cfh = (*it).second;
auto err = [this, chunk_idx, is_write, &handle_out, state, &cfh]() -> DWORD
{
// chunk locked?
if (cfh.locked)
{
if (state == nullptr) return ERROR_SHARING_VIOLATION;
try
{
cfh.waiting.push_back(state);
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
return ERROR_IO_PENDING;
}
// reuse handle
if (!is_write && cfh.handle_ro)
{
handle_out = cfh.handle_ro.get();
if (cfh.refs_ro == 0)
{
handles_ro_load_ += 1;
handles_ro_load_max_ = max(handles_ro_load_max_, handles_ro_load_);
}
++cfh.refs_ro;
return ERROR_SUCCESS;
}
if (is_write && cfh.handle_rw)
{
handle_out = cfh.handle_rw.get();
if (cfh.refs_rw == 0)
{
handles_rw_load_ += 1;
handles_rw_load_max_ = max(handles_rw_load_max_, handles_rw_load_);
}
++cfh.refs_rw;
return ERROR_SUCCESS;
}
if (is_write && service_.bases.size() > 1)
{
auto base_idx = service_.FindChunk(chunk_idx);
if (0 < base_idx && base_idx < service_.bases.size())
{
// chunk lock required
return ERROR_LOCK_FAILED;
}
}
auto h = FileHandle();
auto err = service_.CreateChunk(chunk_idx, h, is_write);
if (err == ERROR_SHARING_VIOLATION)
{
if (state == nullptr || !service_.CheckChunkLocked(chunk_idx)) return err; // synchronous
// locked, LOCK_CHUNK not handled yet
try
{
cfh.waiting.push_back(state);
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
return ERROR_IO_PENDING;
}
if (err != ERROR_SUCCESS) return err;
if (!h)
{
// chunk empty or does not exist
// may race with writes
handle_out = INVALID_HANDLE_VALUE;
return ERROR_SUCCESS;
}
// NOTE: a completion packet will also be sent if the I/O operation successfully completed synchronously.
// See https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o
// Related: https://docs.microsoft.com/en-us/troubleshoot/windows/win32/asynchronous-disk-io-synchronous
// Related: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setfilecompletionnotificationmodes
if (CreateIoCompletionPort(h.get(), iocp_.get(), CK_IO, 1) == nullptr)
{
return GetLastError();
}
// save new handle
handle_out = h.get();
if (!is_write)
{
cfh.handle_ro = std::move(h);
handles_ro_load_ += 1;
handles_ro_load_max_ = max(handles_ro_load_max_, handles_ro_load_);
++cfh.refs_ro;
}
else
{
cfh.handle_rw = std::move(h);
handles_rw_load_ += 1;
handles_rw_load_max_ = max(handles_rw_load_max_, handles_rw_load_);
++cfh.refs_rw;
}
return ERROR_SUCCESS;
}();
if (emplaced && !(err == ERROR_SUCCESS && handle_out != INVALID_HANDLE_VALUE))
{
if (cfh.waiting.empty()) chunk_handles_.erase(it);
}
return err;
}
DWORD ChunkDiskWorker::WaitChunkAsync(const u64 chunk_idx, ChunkOpState* state)
{
auto lk = SRWLock(*mutex_handles_, true);
try
{
auto [it, emplaced] = chunk_handles_.try_emplace(chunk_idx);
auto& cfh = (*it).second;
try
{
// locked, LOCK_CHUNK not handled yet if emplaced
cfh.waiting.push_back(state);
}
catch (const bad_alloc&)
{
if (emplaced) chunk_handles_.erase(it);
return ERROR_NOT_ENOUGH_MEMORY;
}
return ERROR_IO_PENDING;
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
}
DWORD ChunkDiskWorker::CloseChunkAsync(const u64 chunk_idx, const bool is_write, const bool remove)
{
auto lk = SRWLock(*mutex_handles_, true);
auto it = chunk_handles_.find(chunk_idx);
if (it == chunk_handles_.end()) return ERROR_NOT_FOUND;
// handles closed automatically in OpenChunkAsync() or PeriodicCheck()
auto& cfh = (*it).second;
if (!is_write)
{
--cfh.refs_ro;
if (cfh.refs_ro == 0)
{
if (cfh.locked || remove) cfh.handle_ro.reset();
handles_ro_load_ -= 1;
}
}
else
{
--cfh.refs_rw;
if (cfh.refs_rw == 0)
{
if (cfh.locked || remove) cfh.handle_rw.reset();
handles_rw_load_ -= 1;
}
}
if (cfh.refs_ro == 0 && cfh.refs_rw == 0)
{
if (remove && !cfh.locked && cfh.waiting.empty())
{
chunk_handles_.erase(it);
}
if (cfh.locked)
{
// cfh.locked not reset until WAIT_CHUNK then UNLOCK_CHUNK
lk.unlock();
// reply WAIT_CHUNK to the locking worker
auto err = [this, chunk_idx]() -> DWORD
{
auto* user = LPVOID();
service_.CheckChunkLocked(chunk_idx, user);
if (user == nullptr)
{
SpdStorageUnitShutdown(service_.storage_unit); // fatal
return ERROR_INVALID_STATE;
}
auto* worker = recast<ChunkDiskWorker*>(recast<ChunkOpState*>(user)->ovl.hEvent);
if (worker == nullptr)
{
SpdStorageUnitShutdown(service_.storage_unit); // fatal
return ERROR_INVALID_STATE;
}
auto msg = ChunkWork();
auto err = PrepareMsg(msg, WAIT_CHUNK, chunk_idx);
if (err != ERROR_SUCCESS) return err;
err = worker->PostMsg(std::move(msg));
return err == ERROR_IO_PENDING ? ERROR_SUCCESS : err;
}();
// fatal
if (err != ERROR_SUCCESS && err != ERROR_INVALID_STATE) SpdStorageUnitShutdown(service_.storage_unit);
}
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::RefreshChunkWrite(const u64 chunk_idx)
{
auto lk = SRWLock(*mutex_handles_, true);
auto it = chunk_handles_.find(chunk_idx);
if (it == chunk_handles_.end()) return ERROR_NOT_FOUND;
auto& cfh = (*it).second;
if (cfh.refs_rw != 0) return ERROR_BUSY;
cfh.handle_rw.reset();
if (cfh.refs_ro == 0 && !cfh.locked && cfh.waiting.empty())
{
chunk_handles_.erase(it);
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::LockChunk(const u64 chunk_idx)
{
auto lk = SRWLock(*mutex_handles_, true);
try
{
auto it = chunk_handles_.try_emplace(chunk_idx).first;
auto& cfh = (*it).second;
cfh.locked = true;
// WAIT_CHUNK sent in CloseChunkAsync() otherwise
if (cfh.refs_ro == 0 && cfh.refs_rw == 0)
{
cfh.handle_ro.reset();
cfh.handle_rw.reset();
// cfh.locked not reset until WAIT_CHUNK then UNLOCK_CHUNK
lk.unlock();
auto err = [this, chunk_idx]() -> DWORD
{
auto* user = LPVOID();
service_.CheckChunkLocked(chunk_idx, user);
if (user == nullptr)
{
SpdStorageUnitShutdown(service_.storage_unit); // fatal
return ERROR_INVALID_STATE;
}
auto* worker = recast<ChunkDiskWorker*>(recast<ChunkOpState*>(user)->ovl.hEvent);
if (worker == nullptr)
{
SpdStorageUnitShutdown(service_.storage_unit); // fatal
return ERROR_INVALID_STATE;
}
auto msg = ChunkWork();
auto err = PrepareMsg(msg, WAIT_CHUNK, chunk_idx);
if (err != ERROR_SUCCESS) return err;
err = worker->PostMsg(std::move(msg));
return err == ERROR_IO_PENDING ? ERROR_SUCCESS : err;
}();
// fatal
if (err != ERROR_SUCCESS && err != ERROR_INVALID_STATE) SpdStorageUnitShutdown(service_.storage_unit);
}
return ERROR_SUCCESS;
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
}
DWORD ChunkDiskWorker::UnlockChunk(const u64 chunk_idx)
{
auto lk = SRWLock(*mutex_handles_, true);
auto it = chunk_handles_.find(chunk_idx);
if (it == chunk_handles_.end()) return ERROR_NOT_FOUND;
auto& cfh = (*it).second;
if (!(cfh.locked && cfh.refs_ro == 0 && cfh.refs_rw == 0)) return ERROR_INVALID_STATE;
auto waiting = std::move(cfh.waiting);
chunk_handles_.erase(it);
lk.unlock();
for (auto* op : waiting)
{
// retry from the last step...
if (PostOp(*op) != ERROR_IO_PENDING) CompleteWork(op->owner);
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::PreparePageOps(ChunkWork& work, const bool is_write, const u64 page_idx,
const u32 start_off, const u32 end_off, LONGLONG& file_off, LPVOID& buffer)
{
const auto& base = service_.bases[0];
auto& ops = work.ops;
auto kind = is_write ? WRITE_PAGE : READ_PAGE;
if (is_write && !base.IsWholePages(start_off, end_off)) kind = WRITE_PAGE_PARTIAL;
try
{
auto& op = ops.emplace_back(&work, kind, page_idx, start_off, end_off, file_off, buffer);
file_off += LONGLONG(base.PageBytes(1));
if (buffer != nullptr) buffer = recast<u8*>(buffer) + base.BlockBytes(end_off - start_off);
// try to complete immediately
// not async context, can't lock a page, defer reading for WRITE_PAGE_PARTIAL
if (kind == READ_PAGE)
{
SRWLock lk;
auto* ptr = LPVOID();
auto err = service_.PeekPage(page_idx, lk, ptr);
if (err == ERROR_SUCCESS)
{
auto size = base.BlockBytes(op.end_off - op.start_off);
memcpy(op.buffer, recast<u8*>(ptr) + base.BlockBytes(op.start_off), size);
ReportOpResult(op);
return ERROR_SUCCESS;
}
}
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
return ERROR_SUCCESS;
}
DWORD ChunkDiskWorker::PrepareChunkOps(ChunkWork& work, ChunkOpKind kind, const u64 chunk_idx,
const u64 start_off, const u64 end_off, LPVOID& buffer)
{
const auto& base = service_.bases[0];
auto& ops = work.ops;
// try to complete immediately
if (kind == READ_CHUNK || kind == UNMAP_CHUNK)
{
auto h = HANDLE(INVALID_HANDLE_VALUE);
auto err = OpenChunkAsync(chunk_idx, false, h);
if (err != ERROR_SUCCESS && err != ERROR_SHARING_VIOLATION
&& !(err == ERROR_DUPLICATE_TAG && base.move_enabled))
{
return err;
// maybe locked if ERROR_SHARING_VIOLATION
// maybe being moved if ERROR_DUPLICATE_TAG
}
if (err == ERROR_SUCCESS)
{
if (h != INVALID_HANDLE_VALUE)
{
CloseChunkAsync(chunk_idx, false);
}
else
{
// may race with writes
if (kind == UNMAP_CHUNK)
{
// chunk does not exist in any base or empty chunk exists,
// nothing to unmap
return ERROR_SUCCESS;
}
try
{
auto& op = ops.emplace_back(&work, kind, chunk_idx, start_off, end_off,
LONGLONG(base.BlockBytes(start_off)), buffer);
if (buffer != nullptr)
{
// zero-fill if READ_CHUNK
memset(buffer, 0, base.BlockBytes(end_off - start_off));
buffer = recast<u8*>(buffer) + base.BlockBytes(end_off - start_off);
}
ReportOpResult(op);
return ERROR_SUCCESS;
}
catch (const bad_alloc&)
{
return ERROR_NOT_ENOUGH_MEMORY;
}
}
}
// buffer == nullptr only if UNMAP_CHUNK and service_.zero_chunk
if (kind == UNMAP_CHUNK)
{
if (base.IsWholeChunk(start_off, end_off))
{
// zero-fill the chunk
if (!service_.trim_chunk && service_.zero_chunk) kind = WRITE_CHUNK;
}
else
{
// zero-fill the range
if (service_.zero_chunk) kind = WRITE_CHUNK;
}
}
}
else if (kind != WRITE_CHUNK)
{
return ERROR_INVALID_FUNCTION;
}
// prepare asynchronous I/O
// kind: READ_CHUNK, WRITE_CHUNK, UNMAP_CHUNK
const auto is_write = (kind == WRITE_CHUNK);
const auto r = base.BlockPageRange(chunk_idx, start_off, end_off);
if (kind == UNMAP_CHUNK || base.IsWholePages(r.start_off, r.end_off, buffer))