-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
block_cache.cpp
1789 lines (1514 loc) · 54.3 KB
/
block_cache.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
/*
Copyright (c) 2010-2018, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#include "libtorrent/block_cache.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/disk_io_job.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/error.hpp"
#include "libtorrent/disk_io_thread.hpp" // disk_operation_failed
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/aux_/alloca.hpp"
#include "libtorrent/performance_counters.hpp"
#include "libtorrent/aux_/time.hpp"
#include "libtorrent/aux_/block_cache_reference.hpp"
#include "libtorrent/aux_/numeric_cast.hpp"
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/variant/get.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
/*
The disk cache mimics ARC (adaptive replacement cache).
See paper: http://dbs.uni-leipzig.de/file/ARC.pdf
See slides: http://www-vlsi.stanford.edu/smart_memories/protected/meetings/spring2004/arc-fast.pdf
This cache has a few modifications to make it fit the bittorrent use
case better. It has a few more lists and it defers the eviction
of pieces.
read_lru1
This is a plain LRU for items that have been requested once. If a piece
in this list gets accessed again, by someone other than the first
accessor, the piece is promoted into LRU2. which holds pieces that are
more frequently used, and more important to keep around as this LRU list
takes churn.
read_lru1_ghost
This is a list of pieces that were least recently evicted from read_lru1.
These pieces don't hold any actual blocks in the cache, they are just
here to extend the reach and probability for pieces to be promoted into
read_lru2. Any piece in this list that get one more access is promoted to
read_lru2. This is technically a cache-miss, since there's no cached
blocks here, but for the purposes of promoting the piece from
infrequently used to frequently used), it's considered a cache-hit.
read_lru2
TODO
read_lru2_ghost
TODO
volatile_read_lru
TODO
write_lru
TODO
Cache hits
..........
When a piece get a cache hit, it's promoted, either to the beginning of the
lru2 or into lru2. Since this ARC implementation operates on pieces instead
of blocks, any one peer requesting blocks from one piece would essentially
always produce a "cache hit" the second block it requests. In order to make
the promotions make more sense, and be more in the spirit of the ARC
algorithm, each access contains a token, unique to each peer. If any access
has a different token than the last one, it's considered a cache hit. This
is because at least two peers requested blocks from the same piece.
Deferred evictions
..................
Since pieces and blocks can be pinned in the cache, and it's not always
practical, or possible, to evict a piece at the point where a new block is
allocated (because it's not known what the block will be used for),
evictions are not done at the time of allocating blocks. Instead, whenever
an operation requires to add a new piece to the cache, it also records the
cache event leading to it, in m_last_cache_op. This is one of cache_miss
(piece did not exist in cache), lru1_ghost_hit (the piece was found in
lru1_ghost and it was promoted) or lru2_ghost_hit (the piece was found in
lru2_ghost and it was promoted). This cache operation then guides the cache
eviction algorithm to know which list to evict from. The volatile list is
always the first one to be evicted however.
Write jobs
..........
When the write cache is enabled, write jobs are not issued via the normal
job queue. They are just hung on its corresponding cached piece entry, and a
flush_hashed job is issued. This job will inspect the current state of the
cached piece and determine if any of the blocks should be flushed. It also
kicks the hasher, i.e. progresses the SHA1 context, which calculates the
SHA-1 hash of the piece. This job flushed blocks that have been hashed and
also form a contiguous block run of at least the write cache line size.
Read jobs
.........
The data blocks pulled in from disk by read jobs, are hung on the
corresponding cache piece (cached_piece_entry) once the operation completes.
Read operations typically pulls in an entire read cache stripe, and not just
the one block that was requested. When adjacent blocks are requested to be
read in quick succession, there is a risk that each block would pull in more
blocks (read ahead) and potentially read the same blocks several times, if
the original requests were serviced by different disk thread. This is
because all the read operation may start before any of them has completed,
hanging the resulting blocks in the cache. i.e. they would all be cache
misses, even though all but the first should be cache hits in the first's
read ahead.
In order to solve this problem, there is only a single outstanding read job
at any given time per piece. When there is an outstanding read job on a
piece, the *outstanding_read* member is set to 1. This indicates that the
job should be hung on the piece for later processing, instead of being
issued into the main job queue. There is a tailqueue on each piece entry
called read_jobs where these jobs are added.
At the end of every read job, this job list is inspected, any job in it is
tried against the cache to see if it's a cache hit now. If it is, complete
it right away. If it isn't, put it back in the read_jobs list except for
one, which is issued into the regular job queue.
*/
#define DEBUG_CACHE 0
#if DEBUG_CACHE
#define DLOG(...) std::fprintf(__VA_ARGS__)
#else
#define DLOG(...) do {} while (false)
#endif
namespace libtorrent {
#if DEBUG_CACHE
void log_refcounts(cached_piece_entry const* pe)
{
char out[4096];
char* ptr = out;
char* end = ptr + sizeof(out);
ptr += std::snprintf(ptr, end - ptr, "piece: %d [ ", int(pe->piece));
for (int i = 0; i < pe->blocks_in_piece; ++i)
{
ptr += std::snprintf(ptr, end - ptr, "%d ", int(pe->blocks[i].refcount));
}
strncpy(ptr, "]\n", end - ptr);
DLOG(stderr, out);
}
#endif
std::array<const char*, 15> const job_action_name =
{{
"read",
"write",
"hash",
"move_storage",
"release_files",
"delete_files",
"check_fastresume",
"rename_file",
"stop_torrent",
"flush_piece",
"flush_hashed",
"flush_storage",
"trim_cache",
"set_file_priority",
"clear_piece",
}};
// make sure the job names array covers all the job IDs
static_assert(int(job_action_name.size()) == static_cast<int>(job_action_t::num_job_ids)
, "disk-job-action and action-name-array mismatch");
#if TORRENT_USE_ASSERTS || !defined TORRENT_DISABLE_LOGGING
std::array<char const*, 7> const piece_log_t::job_names =
{{
"flushing",
"flush_expired",
"try_flush_write_blocks",
"try_flush_write_blocks2",
"flush_range",
"clear_outstanding_jobs",
"set_outstanding_jobs",
}};
char const* job_name(job_action_t const job)
{
int const j = static_cast<int>(job);
if (j < 0 || j >= piece_log_t::last_job)
return "unknown";
if (j < piece_log_t::flushing)
return job_action_name[static_cast<std::size_t>(j)];
return piece_log_t::job_names[static_cast<std::size_t>(j - piece_log_t::flushing)];
}
#endif // TORRENT_DISABLE_LOGGING
#if TORRENT_USE_ASSERTS
void print_piece_log(aux::vector<piece_log_t> const& piece_log)
{
for (int i = 0; i < int(piece_log.size()); ++i)
{
if (piece_log[i].block == -1)
{
std::printf("%d: %s\n", i, job_name(piece_log[i].job));
}
else
{
std::printf("%d: %s %d\n", i, job_name(piece_log[i].job), piece_log[i].block);
}
}
}
void assert_print_piece(cached_piece_entry const* pe)
{
static const char* const cache_state[] =
{
"write", "volatile-read", "read-lru", "read-lru-ghost", "read-lfu", "read-lfu-ghost"
};
if (pe == nullptr)
{
assert_print("piece: nullptr\n");
}
else
{
assert_print("piece: %d\nrefcount: %d\npiece_refcount: %d\n"
"num_blocks: %d\nhashing: %d\n\nhash: %p\nhash_offset: %d\n"
"cache_state: (%d) %s\noutstanding_flush: %d\npiece: %d\n"
"num_dirty: %d\nnum_blocks: %d\nblocks_in_piece: %d\n"
"hashing_done: %d\nmarked_for_deletion: %d\nneed_readback: %d\n"
"hash_passed: %d\nread_jobs: %d\njobs: %d\n"
"piece_log:\n"
, int(pe->piece), pe->refcount, pe->piece_refcount, int(pe->num_blocks)
, int(pe->hashing), static_cast<void*>(pe->hash.get()), pe->hash ? pe->hash->offset : -1
, int(pe->cache_state)
, pe->cache_state < cached_piece_entry::num_lrus ? cache_state[pe->cache_state] : ""
, int(pe->outstanding_flush), int(pe->piece), int(pe->num_dirty)
, int(pe->num_blocks), int(pe->blocks_in_piece), int(pe->hashing_done)
, int(pe->marked_for_eviction), int(pe->need_readback), pe->hash_passes
, pe->read_jobs.size(), pe->jobs.size());
bool first = true;
for (auto const& log : pe->piece_log)
{
assert_print("%s %s (%d)", (first ? "" : ",")
, job_name(log.job), log.block);
first = false;
}
}
assert_print("\n");
}
#define TORRENT_PIECE_ASSERT(cond, piece) \
do { if (!(cond)) { assert_print_piece(piece); assert_fail(#cond, __LINE__, __FILE__, __func__, nullptr); } } TORRENT_WHILE_0
#else
#define TORRENT_PIECE_ASSERT(cond, piece) do {} TORRENT_WHILE_0
#endif
cached_piece_entry::cached_piece_entry()
: num_dirty(0)
, num_blocks(0)
, hashing(0)
, hashing_done(0)
, marked_for_deletion(false)
, need_readback(false)
, cache_state(none)
, outstanding_flush(0)
, outstanding_read(0)
, marked_for_eviction(false)
, pinned(0)
{}
cached_piece_entry::~cached_piece_entry()
{
TORRENT_ASSERT(piece_refcount == 0);
TORRENT_ASSERT(jobs.empty());
TORRENT_ASSERT(read_jobs.empty());
#if TORRENT_USE_ASSERTS
if (blocks)
{
for (int i = 0; i < blocks_in_piece; ++i)
{
TORRENT_ASSERT(!blocks[i].pending);
TORRENT_ASSERT(blocks[i].refcount == 0);
TORRENT_ASSERT(blocks[i].hashing_count == 0);
TORRENT_ASSERT(blocks[i].flushing_count == 0);
}
}
in_use = false;
#endif
}
block_cache::block_cache(io_service& ios
, std::function<void()> const& trigger_trim)
: disk_buffer_pool(ios, trigger_trim)
, m_last_cache_op(cache_miss)
, m_ghost_size(8)
, m_max_volatile_blocks(100)
, m_volatile_size(0)
, m_read_cache_size(0)
, m_write_cache_size(0)
, m_send_buffer_blocks(0)
, m_pinned_blocks(0)
{
}
block_cache::~block_cache()
{
std::vector<char*> bufs;
for (auto const& pe : m_pieces)
{
if (!pe.blocks) continue;
int const num_blocks = int(pe.blocks_in_piece);
for (int i = 0; i < num_blocks; ++i)
{
if (pe.blocks[i].buf == nullptr) continue;
bufs.push_back(pe.blocks[i].buf);
}
}
free_multiple_buffers(bufs);
}
// returns:
// -1: not in cache
// -2: no memory
int block_cache::try_read(disk_io_job* j, buffer_allocator_interface& allocator
, bool expect_no_fail)
{
INVARIANT_CHECK;
cached_piece_entry* p = find_piece(j);
int ret = 0;
// if the piece cannot be found in the cache,
// it's a cache miss
TORRENT_ASSERT(!expect_no_fail || p != nullptr);
if (p == nullptr) return -1;
#if TORRENT_USE_ASSERTS
p->piece_log.push_back(piece_log_t(j->action, j->d.io.offset / 0x4000));
#endif
cache_hit(p, j->d.io.offset / default_block_size, bool(j->flags & disk_interface::volatile_read));
ret = copy_from_piece(p, j, allocator, expect_no_fail);
if (ret < 0) return ret;
ret = j->d.io.buffer_size;
return ret;
}
void block_cache::bump_lru(cached_piece_entry* p)
{
// move to the top of the LRU list
TORRENT_PIECE_ASSERT(p->cache_state == cached_piece_entry::write_lru, p);
linked_list<cached_piece_entry>* lru_list = &m_lru[p->cache_state];
// move to the back (MRU) of the list
lru_list->erase(p);
lru_list->push_back(p);
p->expire = aux::time_now();
}
// this is called for pieces that we're reading from, when they
// are in the cache (including the ghost lists)
void block_cache::cache_hit(cached_piece_entry* p, int block, bool volatile_read)
{
// this can be pretty expensive
// INVARIANT_CHECK;
TORRENT_ASSERT(p);
TORRENT_ASSERT(p->in_use);
// move the piece into this queue. Whenever we have a cache
// hit, we move the piece into the lru2 queue (i.e. the most
// frequently used piece).
std::uint16_t target_queue = cached_piece_entry::read_lru2;
if (p->blocks[block].cache_hit == 0)
{
// if it's not a duplicate hit and the piece isn't in
// any of the ghost lists, ignore it
if (p->cache_state == cached_piece_entry::read_lru1
|| p->cache_state == cached_piece_entry::read_lru2
|| p->cache_state == cached_piece_entry::write_lru
|| p->cache_state == cached_piece_entry::volatile_read_lru)
return;
if (p->cache_state == cached_piece_entry::read_lru1_ghost)
target_queue = cached_piece_entry::read_lru1;
}
if (p->cache_state == cached_piece_entry::volatile_read_lru)
{
// a volatile read hit on a volatile piece doesn't do anything
if (volatile_read) return;
// however, if this is a proper read on a volatile piece
// we need to promote it to lru1
target_queue = cached_piece_entry::read_lru1;
}
// if we have this piece anywhere in L1 or L2, it's a "hit"
// and it should be bumped to the highest priority in L2
// i.e. "frequently used"
if (p->cache_state < cached_piece_entry::read_lru1
|| p->cache_state > cached_piece_entry::read_lru2_ghost)
return;
// if we got a cache hit in a ghost list, that indicates the proper
// list is too small. Record which ghost list we got the hit in and
// it will be used to determine which end of the cache we'll evict
// from, next time we need to reclaim blocks
if (p->cache_state == cached_piece_entry::read_lru1_ghost)
{
m_last_cache_op = ghost_hit_lru1;
}
else if (p->cache_state == cached_piece_entry::read_lru2_ghost)
{
m_last_cache_op = ghost_hit_lru2;
}
// move into L2 (frequently used)
m_lru[p->cache_state].erase(p);
m_lru[target_queue].push_back(p);
p->cache_state = target_queue;
p->expire = aux::time_now();
#if TORRENT_USE_ASSERTS
switch (p->cache_state)
{
case cached_piece_entry::write_lru:
case cached_piece_entry::volatile_read_lru:
case cached_piece_entry::read_lru1:
case cached_piece_entry::read_lru2:
TORRENT_ASSERT(p->in_storage == true);
break;
default:
TORRENT_ASSERT(p->in_storage == false);
break;
}
#endif
}
// this is used to move pieces primarily from the write cache
// to the read cache. Technically it can move from read to write
// cache as well, it's unclear if that ever happens though
void block_cache::update_cache_state(cached_piece_entry* p)
{
int state = p->cache_state;
std::uint16_t desired_state = p->cache_state;
if (p->num_dirty > 0 || p->hash)
desired_state = cached_piece_entry::write_lru;
else if (p->cache_state == cached_piece_entry::write_lru)
desired_state = cached_piece_entry::read_lru1;
if (desired_state == state) return;
TORRENT_PIECE_ASSERT(state < cached_piece_entry::num_lrus, p);
TORRENT_PIECE_ASSERT(desired_state < cached_piece_entry::num_lrus, p);
linked_list<cached_piece_entry>* src = &m_lru[state];
linked_list<cached_piece_entry>* dst = &m_lru[desired_state];
src->erase(p);
dst->push_back(p);
p->expire = aux::time_now();
p->cache_state = desired_state;
#if TORRENT_USE_ASSERTS
switch (p->cache_state)
{
case cached_piece_entry::write_lru:
case cached_piece_entry::volatile_read_lru:
case cached_piece_entry::read_lru1:
case cached_piece_entry::read_lru2:
TORRENT_ASSERT(p->in_storage == true);
break;
default:
TORRENT_ASSERT(p->in_storage == false);
break;
}
#endif
}
void block_cache::try_evict_one_volatile()
{
INVARIANT_CHECK;
DLOG(stderr, "[%p] try_evict_one_volatile\n", static_cast<void*>(this));
if (m_volatile_size < m_max_volatile_blocks) return;
linked_list<cached_piece_entry>* piece_list = &m_lru[cached_piece_entry::volatile_read_lru];
for (list_iterator<cached_piece_entry> i = piece_list->iterate(); i.get();)
{
cached_piece_entry* pe = i.get();
TORRENT_PIECE_ASSERT(pe->in_use, pe);
i.next();
if (pe->ok_to_evict() && pe->num_blocks == 0)
{
#if TORRENT_USE_INVARIANT_CHECKS
for (int j = 0; j < pe->blocks_in_piece; ++j)
TORRENT_PIECE_ASSERT(pe->blocks[j].buf == nullptr, pe);
#endif
TORRENT_PIECE_ASSERT(pe->refcount == 0, pe);
move_to_ghost(pe);
continue;
}
TORRENT_PIECE_ASSERT(pe->num_dirty == 0, pe);
// someone else is using this piece
if (pe->refcount > 0) continue;
// some blocks are pinned in this piece, skip it
if (pe->pinned > 0) continue;
TORRENT_ALLOCA(to_delete, char*, pe->blocks_in_piece);
int num_to_delete = 0;
// go through the blocks and evict the ones that are not dirty and not
// referenced
for (int j = 0; j < pe->blocks_in_piece; ++j)
{
cached_block_entry& b = pe->blocks[j];
TORRENT_PIECE_ASSERT(b.dirty == false, pe);
TORRENT_PIECE_ASSERT(b.pending == false, pe);
if (b.buf == nullptr || b.refcount > 0 || b.dirty || b.pending) continue;
to_delete[num_to_delete++] = b.buf;
b.buf = nullptr;
TORRENT_PIECE_ASSERT(pe->num_blocks > 0, pe);
--pe->num_blocks;
TORRENT_PIECE_ASSERT(m_read_cache_size > 0, pe);
--m_read_cache_size;
TORRENT_PIECE_ASSERT(m_volatile_size > 0, pe);
--m_volatile_size;
}
if (pe->ok_to_evict() && pe->num_blocks == 0)
{
#if TORRENT_USE_INVARIANT_CHECKS
for (int j = 0; j < pe->blocks_in_piece; ++j)
TORRENT_PIECE_ASSERT(pe->blocks[j].buf == nullptr, pe);
#endif
move_to_ghost(pe);
}
if (num_to_delete == 0) return;
DLOG(stderr, "[%p] removed %d blocks\n", static_cast<void*>(this)
, num_to_delete);
free_multiple_buffers(to_delete.first(num_to_delete));
return;
}
}
cached_piece_entry* block_cache::allocate_piece(disk_io_job const* j, std::uint16_t const cache_state)
{
#ifdef TORRENT_EXPENSIVE_INVARIANT_CHECKS
INVARIANT_CHECK;
#endif
TORRENT_ASSERT(cache_state < cached_piece_entry::num_lrus);
// we're assuming we're not allocating a ghost piece
// a bit further down
TORRENT_ASSERT(cache_state != cached_piece_entry::read_lru1_ghost
&& cache_state != cached_piece_entry::read_lru2_ghost);
cached_piece_entry* p = find_piece(j);
if (p == nullptr)
{
int const piece_size = j->storage->files().piece_size(j->piece);
int const blocks_in_piece = (piece_size + default_block_size - 1) / default_block_size;
cached_piece_entry pe;
pe.piece = j->piece;
pe.storage = j->storage;
pe.expire = aux::time_now();
pe.blocks_in_piece = aux::numeric_cast<std::uint16_t>(blocks_in_piece);
pe.blocks.reset(new (std::nothrow) cached_block_entry[std::size_t(blocks_in_piece)]);
if (!pe.blocks) return nullptr;
p = const_cast<cached_piece_entry*>(&*m_pieces.insert(std::move(pe)).first);
j->storage->add_piece(p);
p->cache_state = cache_state;
TORRENT_PIECE_ASSERT(p->cache_state < cached_piece_entry::num_lrus, p);
linked_list<cached_piece_entry>* lru_list = &m_lru[p->cache_state];
lru_list->push_back(p);
// this piece is part of the ARC cache (as opposed to
// the write cache). Allocating a new read piece indicates
// that we just got a cache miss. Record this to determine
// which end to evict blocks from next time we need to
// evict blocks
if (cache_state == cached_piece_entry::read_lru1)
m_last_cache_op = cache_miss;
#if TORRENT_USE_ASSERTS
switch (p->cache_state)
{
case cached_piece_entry::write_lru:
case cached_piece_entry::volatile_read_lru:
case cached_piece_entry::read_lru1:
case cached_piece_entry::read_lru2:
TORRENT_ASSERT(p->in_storage == true);
break;
default:
TORRENT_ASSERT(p->in_storage == false);
break;
}
#endif
}
else
{
TORRENT_PIECE_ASSERT(p->in_use, p);
// we want to retain the piece now
p->marked_for_eviction = false;
// only allow changing the cache state downwards. i.e. turn a ghost
// piece into a non-ghost, or a read piece into a write piece
if (p->cache_state > cache_state)
{
// this can happen for instance if a piece fails the hash check
// first it's in the write cache, then it completes and is moved
// into the read cache, but fails and is cleared (into the ghost list)
// then we want to add new dirty blocks to it and we need to move
// it back into the write cache
m_lru[p->cache_state].erase(p);
p->cache_state = cache_state;
m_lru[p->cache_state].push_back(p);
p->expire = aux::time_now();
#if TORRENT_USE_ASSERTS
switch (p->cache_state)
{
case cached_piece_entry::write_lru:
case cached_piece_entry::volatile_read_lru:
case cached_piece_entry::read_lru1:
case cached_piece_entry::read_lru2:
TORRENT_ASSERT(p->in_storage == true);
break;
default:
TORRENT_ASSERT(p->in_storage == false);
break;
}
#endif
}
}
return p;
}
cached_piece_entry* block_cache::add_dirty_block(disk_io_job* j, bool const add_hasher)
{
#ifdef TORRENT_EXPENSIVE_INVARIANT_CHECKS
INVARIANT_CHECK;
#endif
TORRENT_ASSERT(boost::get<disk_buffer_holder>(j->argument));
TORRENT_ASSERT(m_write_cache_size + m_read_cache_size + 1 <= in_use());
cached_piece_entry* pe = allocate_piece(j, cached_piece_entry::write_lru);
TORRENT_ASSERT(pe);
if (pe == nullptr) return pe;
TORRENT_PIECE_ASSERT(pe->in_use, pe);
int block = j->d.io.offset / default_block_size;
TORRENT_ASSERT((j->d.io.offset % default_block_size) == 0);
// we should never add a new dirty block on a piece
// that has checked the hash. Before we add it, the
// piece need to be cleared (with async_clear_piece)
TORRENT_PIECE_ASSERT(pe->hashing_done == 0, pe);
// this only evicts read blocks
int evict = num_to_evict(1);
if (evict > 0) try_evict_blocks(evict, pe);
TORRENT_PIECE_ASSERT(block < pe->blocks_in_piece, pe);
TORRENT_PIECE_ASSERT(j->piece == pe->piece, pe);
TORRENT_PIECE_ASSERT(!pe->marked_for_eviction, pe);
TORRENT_PIECE_ASSERT(pe->blocks[block].refcount == 0, pe);
cached_block_entry& b = pe->blocks[block];
TORRENT_PIECE_ASSERT(b.buf != boost::get<disk_buffer_holder>(j->argument).get(), pe);
// we might have a left-over read block from
// hash checking
// we might also have a previous dirty block which
// we're still waiting for to be written
if (b.buf != nullptr && b.buf != boost::get<disk_buffer_holder>(j->argument).get())
{
TORRENT_PIECE_ASSERT(b.refcount == 0 && !b.pending, pe);
free_block(pe, block);
TORRENT_PIECE_ASSERT(b.dirty == 0, pe);
}
b.buf = boost::get<disk_buffer_holder>(j->argument).release();
b.dirty = true;
++pe->num_blocks;
++pe->num_dirty;
++m_write_cache_size;
TORRENT_PIECE_ASSERT(j->piece == pe->piece, pe);
TORRENT_PIECE_ASSERT(j->flags & disk_io_job::in_progress, pe);
TORRENT_PIECE_ASSERT(j->piece == pe->piece, pe);
pe->jobs.push_back(j);
if (block == 0 && !pe->hash && pe->hashing_done == false && add_hasher)
pe->hash.reset(new partial_hash);
update_cache_state(pe);
bump_lru(pe);
return pe;
}
// flushed is an array of num_flushed integers. Each integer is the block index
// that was flushed. This function marks those blocks as not pending and not
// dirty. It also adjusts its understanding of the read vs. write cache size
// (since these blocks now are part of the read cache) the refcounts of the
// blocks are also decremented by this function. They are expected to have been
// incremented by the caller.
bool block_cache::blocks_flushed(cached_piece_entry* pe, int const* flushed, int const num_flushed)
{
TORRENT_PIECE_ASSERT(pe->in_use, pe);
for (int i = 0; i < num_flushed; ++i)
{
int block = flushed[i];
TORRENT_PIECE_ASSERT(block >= 0, pe);
TORRENT_PIECE_ASSERT(block < pe->blocks_in_piece, pe);
TORRENT_PIECE_ASSERT(pe->blocks[block].dirty, pe);
TORRENT_PIECE_ASSERT(pe->blocks[block].pending, pe);
pe->blocks[block].pending = false;
// it's important to mark it as non-dirty before decrementing the
// refcount because the buffer may be marked as discardable/volatile it
// this is the last reference to it
pe->blocks[block].dirty = false;
dec_block_refcount(pe, block, block_cache::ref_flushing);
}
m_write_cache_size -= num_flushed;
m_read_cache_size += num_flushed;
pe->num_dirty -= num_flushed;
update_cache_state(pe);
return maybe_free_piece(pe);
}
std::pair<block_cache::const_iterator, block_cache::const_iterator> block_cache::all_pieces() const
{
return std::make_pair(m_pieces.begin(), m_pieces.end());
}
void block_cache::free_block(cached_piece_entry* pe, int block)
{
TORRENT_ASSERT(pe != nullptr);
TORRENT_PIECE_ASSERT(pe->in_use, pe);
TORRENT_PIECE_ASSERT(block < pe->blocks_in_piece, pe);
TORRENT_PIECE_ASSERT(block >= 0, pe);
cached_block_entry& b = pe->blocks[block];
TORRENT_PIECE_ASSERT(b.refcount == 0, pe);
TORRENT_PIECE_ASSERT(!b.pending, pe);
TORRENT_PIECE_ASSERT(b.buf, pe);
if (b.dirty)
{
--pe->num_dirty;
b.dirty = false;
TORRENT_PIECE_ASSERT(m_write_cache_size > 0, pe);
--m_write_cache_size;
}
else
{
TORRENT_PIECE_ASSERT(m_read_cache_size > 0, pe);
--m_read_cache_size;
if (pe->cache_state == cached_piece_entry::volatile_read_lru)
{
--m_volatile_size;
}
}
TORRENT_PIECE_ASSERT(pe->num_blocks > 0, pe);
--pe->num_blocks;
free_buffer(b.buf);
b.buf = nullptr;
}
bool block_cache::evict_piece(cached_piece_entry* pe, tailqueue<disk_io_job>& jobs
, eviction_mode const mode)
{
INVARIANT_CHECK;
TORRENT_PIECE_ASSERT(pe->in_use, pe);
TORRENT_ALLOCA(to_delete, char*, pe->blocks_in_piece);
int num_to_delete = 0;
for (int i = 0; i < pe->blocks_in_piece; ++i)
{
if (pe->blocks[i].buf == nullptr || pe->blocks[i].refcount > 0) continue;
TORRENT_PIECE_ASSERT(!pe->blocks[i].pending, pe);
TORRENT_PIECE_ASSERT(pe->blocks[i].buf != nullptr, pe);
TORRENT_PIECE_ASSERT(num_to_delete < pe->blocks_in_piece, pe);
to_delete[num_to_delete++] = pe->blocks[i].buf;
pe->blocks[i].buf = nullptr;
TORRENT_PIECE_ASSERT(pe->num_blocks > 0, pe);
--pe->num_blocks;
if (!pe->blocks[i].dirty)
{
TORRENT_PIECE_ASSERT(m_read_cache_size > 0, pe);
--m_read_cache_size;
}
else
{
TORRENT_PIECE_ASSERT(pe->num_dirty > 0, pe);
--pe->num_dirty;
pe->blocks[i].dirty = false;
TORRENT_PIECE_ASSERT(m_write_cache_size > 0, pe);
--m_write_cache_size;
}
if (pe->num_blocks == 0) break;
}
if (pe->cache_state == cached_piece_entry::volatile_read_lru)
{
m_volatile_size -= num_to_delete;
}
if (num_to_delete) free_multiple_buffers(to_delete.first(num_to_delete));
if (pe->ok_to_evict(true) && pe->num_blocks == 0)
{
pe->hash.reset();
// append will move the items from pe->jobs onto the end of jobs
jobs.append(pe->jobs);
TORRENT_ASSERT(pe->jobs.empty());
if (mode == allow_ghost
&& (pe->cache_state == cached_piece_entry::read_lru1_ghost
|| pe->cache_state == cached_piece_entry::read_lru2_ghost))
return true;
if (mode == disallow_ghost
|| pe->cache_state == cached_piece_entry::write_lru
|| pe->cache_state == cached_piece_entry::volatile_read_lru)
erase_piece(pe);
else
move_to_ghost(pe);
return true;
}
return false;
}
void block_cache::mark_for_eviction(cached_piece_entry* p
, eviction_mode const mode)
{
INVARIANT_CHECK;
DLOG(stderr, "[%p] block_cache mark-for-deletion "
"piece: %d\n", static_cast<void*>(this), int(p->piece));
TORRENT_PIECE_ASSERT(p->jobs.empty(), p);
tailqueue<disk_io_job> jobs;
if (!evict_piece(p, jobs, mode))
{
p->marked_for_eviction = true;
p->marked_for_deletion = mode == disallow_ghost;
}
}
void block_cache::erase_piece(cached_piece_entry* pe)
{
INVARIANT_CHECK;
TORRENT_PIECE_ASSERT(pe->ok_to_evict(), pe);
TORRENT_PIECE_ASSERT(pe->cache_state < cached_piece_entry::num_lrus, pe);
TORRENT_PIECE_ASSERT(pe->jobs.empty(), pe);
linked_list<cached_piece_entry>* lru_list = &m_lru[pe->cache_state];
if (pe->hash)
{
TORRENT_PIECE_ASSERT(pe->hash->offset == 0, pe);
pe->hash.reset();
}
pe->storage->remove_piece(pe);
lru_list->erase(pe);
m_pieces.erase(*pe);
}
// this only evicts read blocks. For write blocks, see
// try_flush_write_blocks in disk_io_thread.cpp
int block_cache::try_evict_blocks(int num, cached_piece_entry* ignore)
{
INVARIANT_CHECK;
if (num <= 0) return 0;
DLOG(stderr, "[%p] try_evict_blocks: %d\n", static_cast<void*>(this), num);
TORRENT_ALLOCA(to_delete, char*, num);
int num_to_delete = 0;
// There are two ends of the ARC cache we can evict from. There's L1 and L2.
// The last cache operation determines which end we'll evict from. If we go
// through the entire list from the preferred end, and still need to evict
// more blocks, we'll go to the other end and start evicting from there. The
// lru_list is an array of two lists, these are the two ends to evict from,
// ordered by preference.
linked_list<cached_piece_entry>* lru_list[3];
// however, before we consider any of the proper LRU lists, we evict pieces
// from the volatile list. These are low priority pieces that were
// specifically marked as to not survive long in the cache. These are the
// first pieces to go when evicting
lru_list[0] = &m_lru[cached_piece_entry::volatile_read_lru];
if (m_last_cache_op == cache_miss)
{
// when there was a cache miss, evict from the largest list, to tend to
// keep the lists of equal size when we don't know which one is
// performing better
if (m_lru[cached_piece_entry::read_lru2].size()
> m_lru[cached_piece_entry::read_lru1].size())
{
lru_list[1] = &m_lru[cached_piece_entry::read_lru2];
lru_list[2] = &m_lru[cached_piece_entry::read_lru1];
}
else
{
lru_list[1] = &m_lru[cached_piece_entry::read_lru1];
lru_list[2] = &m_lru[cached_piece_entry::read_lru2];
}
}
else if (m_last_cache_op == ghost_hit_lru1)
{
// when we insert new items or move things from L1 to L2
// evict blocks from L2
lru_list[1] = &m_lru[cached_piece_entry::read_lru2];
lru_list[2] = &m_lru[cached_piece_entry::read_lru1];
}
else
{
// when we get cache hits in L2 evict from L1
lru_list[1] = &m_lru[cached_piece_entry::read_lru1];
lru_list[2] = &m_lru[cached_piece_entry::read_lru2];
}