• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "net/disk_cache/blockfile/rankings.h"
11 
12 #include <stdint.h>
13 
14 #include <limits>
15 #include <memory>
16 
17 #include "base/memory/raw_ptr.h"
18 #include "base/process/process.h"
19 #include "base/time/time.h"
20 #include "build/build_config.h"
21 #include "net/base/net_export.h"
22 #include "net/disk_cache/blockfile/backend_impl.h"
23 #include "net/disk_cache/blockfile/disk_format.h"
24 #include "net/disk_cache/blockfile/entry_impl.h"
25 #include "net/disk_cache/blockfile/errors.h"
26 #include "net/disk_cache/blockfile/stress_support.h"
27 
28 #if BUILDFLAG(IS_WIN)
29 #include <windows.h>
30 #endif
31 
32 using base::Time;
33 using base::TimeTicks;
34 
35 namespace disk_cache {
36 // This is used by crash_cache.exe to generate unit test files.
37 NET_EXPORT_PRIVATE RankCrashes g_rankings_crash = NO_CRASH;
38 }
39 
40 namespace {
41 
42 enum Operation {
43   INSERT = 1,
44   REMOVE
45 };
46 
47 // This class provides a simple lock for the LRU list of rankings. Whenever an
48 // entry is to be inserted or removed from the list, a transaction object should
49 // be created to keep track of the operation. If the process crashes before
50 // finishing the operation, the transaction record (stored as part of the user
51 // data on the file header) can be used to finish the operation.
52 class Transaction {
53  public:
54   // addr is the cache address of the node being inserted or removed. We want to
55   // avoid having the compiler doing optimizations on when to read or write
56   // from user_data because it is the basis of the crash detection. Maybe
57   // volatile is not enough for that, but it should be a good hint.
58   Transaction(volatile disk_cache::LruData* data, disk_cache::Addr addr,
59               Operation op, int list);
60 
61   Transaction(const Transaction&) = delete;
62   Transaction& operator=(const Transaction&) = delete;
63 
64   ~Transaction();
65  private:
66   raw_ptr<volatile disk_cache::LruData> data_;
67 };
68 
Transaction(volatile disk_cache::LruData * data,disk_cache::Addr addr,Operation op,int list)69 Transaction::Transaction(volatile disk_cache::LruData* data,
70                          disk_cache::Addr addr, Operation op, int list)
71     : data_(data) {
72   DCHECK(!data_->transaction);
73   DCHECK(addr.is_initialized());
74   data_->operation = op;
75   data_->operation_list = list;
76   data_->transaction = addr.value();
77 }
78 
~Transaction()79 Transaction::~Transaction() {
80   DCHECK(data_->transaction);
81   data_->transaction = 0;
82   data_->operation = 0;
83   data_->operation_list = 0;
84 }
85 
86 // Code locations that can generate crashes.
87 enum CrashLocation {
88   ON_INSERT_1, ON_INSERT_2, ON_INSERT_3, ON_INSERT_4, ON_REMOVE_1, ON_REMOVE_2,
89   ON_REMOVE_3, ON_REMOVE_4, ON_REMOVE_5, ON_REMOVE_6, ON_REMOVE_7, ON_REMOVE_8
90 };
91 
92 // Simulates a crash (by exiting the process without graceful shutdown) on debug
93 // builds, according to the value of g_rankings_crash. This used by
94 // crash_cache.exe to generate unit-test files.
GenerateCrash(CrashLocation location)95 void GenerateCrash(CrashLocation location) {
96 #if !defined(NDEBUG) && !BUILDFLAG(IS_IOS)
97   if (disk_cache::NO_CRASH == disk_cache::g_rankings_crash)
98     return;
99   switch (location) {
100     case ON_INSERT_1:
101       switch (disk_cache::g_rankings_crash) {
102         case disk_cache::INSERT_ONE_1:
103         case disk_cache::INSERT_LOAD_1:
104           base::Process::TerminateCurrentProcessImmediately(0);
105         default:
106           break;
107       }
108       break;
109     case ON_INSERT_2:
110       if (disk_cache::INSERT_EMPTY_1 == disk_cache::g_rankings_crash)
111         base::Process::TerminateCurrentProcessImmediately(0);
112       break;
113     case ON_INSERT_3:
114       switch (disk_cache::g_rankings_crash) {
115         case disk_cache::INSERT_EMPTY_2:
116         case disk_cache::INSERT_ONE_2:
117         case disk_cache::INSERT_LOAD_2:
118           base::Process::TerminateCurrentProcessImmediately(0);
119         default:
120           break;
121       }
122       break;
123     case ON_INSERT_4:
124       switch (disk_cache::g_rankings_crash) {
125         case disk_cache::INSERT_EMPTY_3:
126         case disk_cache::INSERT_ONE_3:
127           base::Process::TerminateCurrentProcessImmediately(0);
128         default:
129           break;
130       }
131       break;
132     case ON_REMOVE_1:
133       switch (disk_cache::g_rankings_crash) {
134         case disk_cache::REMOVE_ONE_1:
135         case disk_cache::REMOVE_HEAD_1:
136         case disk_cache::REMOVE_TAIL_1:
137         case disk_cache::REMOVE_LOAD_1:
138           base::Process::TerminateCurrentProcessImmediately(0);
139         default:
140           break;
141       }
142       break;
143     case ON_REMOVE_2:
144       if (disk_cache::REMOVE_ONE_2 == disk_cache::g_rankings_crash)
145         base::Process::TerminateCurrentProcessImmediately(0);
146       break;
147     case ON_REMOVE_3:
148       if (disk_cache::REMOVE_ONE_3 == disk_cache::g_rankings_crash)
149         base::Process::TerminateCurrentProcessImmediately(0);
150       break;
151     case ON_REMOVE_4:
152       if (disk_cache::REMOVE_HEAD_2 == disk_cache::g_rankings_crash)
153         base::Process::TerminateCurrentProcessImmediately(0);
154       break;
155     case ON_REMOVE_5:
156       if (disk_cache::REMOVE_TAIL_2 == disk_cache::g_rankings_crash)
157         base::Process::TerminateCurrentProcessImmediately(0);
158       break;
159     case ON_REMOVE_6:
160       if (disk_cache::REMOVE_TAIL_3 == disk_cache::g_rankings_crash)
161         base::Process::TerminateCurrentProcessImmediately(0);
162       break;
163     case ON_REMOVE_7:
164       switch (disk_cache::g_rankings_crash) {
165         case disk_cache::REMOVE_ONE_4:
166         case disk_cache::REMOVE_LOAD_2:
167         case disk_cache::REMOVE_HEAD_3:
168           base::Process::TerminateCurrentProcessImmediately(0);
169         default:
170           break;
171       }
172       break;
173     case ON_REMOVE_8:
174       switch (disk_cache::g_rankings_crash) {
175         case disk_cache::REMOVE_HEAD_4:
176         case disk_cache::REMOVE_LOAD_3:
177           base::Process::TerminateCurrentProcessImmediately(0);
178         default:
179           break;
180       }
181       break;
182     default:
183       NOTREACHED();
184   }
185 #endif  // NDEBUG
186 }
187 
188 // Update the timestamp fields of |node|.
UpdateTimes(disk_cache::CacheRankingsBlock * node,bool modified)189 void UpdateTimes(disk_cache::CacheRankingsBlock* node, bool modified) {
190   base::Time now = base::Time::Now();
191   node->Data()->last_used = now.ToInternalValue();
192   if (modified)
193     node->Data()->last_modified = now.ToInternalValue();
194 }
195 
196 }  // namespace
197 
198 namespace disk_cache {
199 
ScopedRankingsBlock()200 Rankings::ScopedRankingsBlock::ScopedRankingsBlock() : rankings_(nullptr) {}
201 
ScopedRankingsBlock(Rankings * rankings)202 Rankings::ScopedRankingsBlock::ScopedRankingsBlock(Rankings* rankings)
203     : rankings_(rankings) {}
204 
ScopedRankingsBlock(Rankings * rankings,CacheRankingsBlock * node)205 Rankings::ScopedRankingsBlock::ScopedRankingsBlock(Rankings* rankings,
206                                                    CacheRankingsBlock* node)
207     : std::unique_ptr<CacheRankingsBlock>(node), rankings_(rankings) {}
208 
209 Rankings::Iterator::Iterator() = default;
210 
Reset()211 void Rankings::Iterator::Reset() {
212   if (my_rankings) {
213     for (auto* node : nodes) {
214       ScopedRankingsBlock(my_rankings, node);
215     }
216   }
217   my_rankings = nullptr;
218   nodes = {nullptr, nullptr, nullptr};
219   list = List::NO_USE;
220 }
221 
222 Rankings::Rankings() = default;
223 
224 Rankings::~Rankings() = default;
225 
Init(BackendImpl * backend,bool count_lists)226 bool Rankings::Init(BackendImpl* backend, bool count_lists) {
227   DCHECK(!init_);
228   if (init_)
229     return false;
230 
231   backend_ = backend;
232   control_data_ = backend_->GetLruData();
233   count_lists_ = count_lists;
234 
235   ReadHeads();
236   ReadTails();
237 
238   if (control_data_->transaction)
239     CompleteTransaction();
240 
241   init_ = true;
242   return true;
243 }
244 
Reset()245 void Rankings::Reset() {
246   init_ = false;
247   for (int i = 0; i < LAST_ELEMENT; i++) {
248     heads_[i].set_value(0);
249     tails_[i].set_value(0);
250   }
251   control_data_ = nullptr;
252 }
253 
Insert(CacheRankingsBlock * node,bool modified,List list)254 void Rankings::Insert(CacheRankingsBlock* node, bool modified, List list) {
255   DCHECK(node->HasData());
256   Addr& my_head = heads_[list];
257   Addr& my_tail = tails_[list];
258   Transaction lock(control_data_, node->address(), INSERT, list);
259   CacheRankingsBlock head(backend_->File(my_head), my_head);
260   if (my_head.is_initialized()) {
261     if (!GetRanking(&head))
262       return;
263 
264     if (head.Data()->prev != my_head.value() &&  // Normal path.
265         head.Data()->prev != node->address().value()) {  // FinishInsert().
266       backend_->CriticalError(ERR_INVALID_LINKS);
267       return;
268     }
269 
270     head.Data()->prev = node->address().value();
271     head.Store();
272     GenerateCrash(ON_INSERT_1);
273     UpdateIterators(&head);
274   }
275 
276   node->Data()->next = my_head.value();
277   node->Data()->prev = node->address().value();
278   my_head.set_value(node->address().value());
279 
280   if (!my_tail.is_initialized() || my_tail.value() == node->address().value()) {
281     my_tail.set_value(node->address().value());
282     node->Data()->next = my_tail.value();
283     WriteTail(list);
284     GenerateCrash(ON_INSERT_2);
285   }
286 
287   UpdateTimes(node, modified);
288   node->Store();
289   // Make sure other aliased in-memory copies get synchronized.
290   UpdateIterators(node);
291   GenerateCrash(ON_INSERT_3);
292 
293   // The last thing to do is move our head to point to a node already stored.
294   WriteHead(list);
295   IncrementCounter(list);
296   GenerateCrash(ON_INSERT_4);
297   backend_->FlushIndex();
298 }
299 
300 // If a, b and r are elements on the list, and we want to remove r, the possible
301 // states for the objects if a crash happens are (where y(x, z) means for object
302 // y, prev is x and next is z):
303 // A. One element:
304 //    1. r(r, r), head(r), tail(r)                    initial state
305 //    2. r(r, r), head(0), tail(r)                    WriteHead()
306 //    3. r(r, r), head(0), tail(0)                    WriteTail()
307 //    4. r(0, 0), head(0), tail(0)                    next.Store()
308 //
309 // B. Remove a random element:
310 //    1. a(x, r), r(a, b), b(r, y), head(x), tail(y)  initial state
311 //    2. a(x, r), r(a, b), b(a, y), head(x), tail(y)  next.Store()
312 //    3. a(x, b), r(a, b), b(a, y), head(x), tail(y)  prev.Store()
313 //    4. a(x, b), r(0, 0), b(a, y), head(x), tail(y)  node.Store()
314 //
315 // C. Remove head:
316 //    1. r(r, b), b(r, y), head(r), tail(y)           initial state
317 //    2. r(r, b), b(r, y), head(b), tail(y)           WriteHead()
318 //    3. r(r, b), b(b, y), head(b), tail(y)           next.Store()
319 //    4. r(0, 0), b(b, y), head(b), tail(y)           prev.Store()
320 //
321 // D. Remove tail:
322 //    1. a(x, r), r(a, r), head(x), tail(r)           initial state
323 //    2. a(x, r), r(a, r), head(x), tail(a)           WriteTail()
324 //    3. a(x, a), r(a, r), head(x), tail(a)           prev.Store()
325 //    4. a(x, a), r(0, 0), head(x), tail(a)           next.Store()
Remove(CacheRankingsBlock * node,List list,bool strict)326 void Rankings::Remove(CacheRankingsBlock* node, List list, bool strict) {
327   DCHECK(node->HasData());
328 
329   Addr next_addr(node->Data()->next);
330   Addr prev_addr(node->Data()->prev);
331   if (!next_addr.is_initialized() || next_addr.is_separate_file() ||
332       !prev_addr.is_initialized() || prev_addr.is_separate_file()) {
333     if (next_addr.is_initialized() || prev_addr.is_initialized()) {
334       LOG(ERROR) << "Invalid rankings info.";
335       STRESS_NOTREACHED();
336     }
337     return;
338   }
339 
340   CacheRankingsBlock next(backend_->File(next_addr), next_addr);
341   CacheRankingsBlock prev(backend_->File(prev_addr), prev_addr);
342   if (!GetRanking(&next) || !GetRanking(&prev)) {
343     STRESS_NOTREACHED();
344     return;
345   }
346 
347   if (!CheckLinks(node, &prev, &next, &list))
348     return;
349 
350   Transaction lock(control_data_, node->address(), REMOVE, list);
351   prev.Data()->next = next.address().value();
352   next.Data()->prev = prev.address().value();
353   GenerateCrash(ON_REMOVE_1);
354 
355   CacheAddr node_value = node->address().value();
356   Addr& my_head = heads_[list];
357   Addr& my_tail = tails_[list];
358   if (node_value == my_head.value() || node_value == my_tail.value()) {
359     if (my_head.value() == my_tail.value()) {
360       my_head.set_value(0);
361       my_tail.set_value(0);
362 
363       WriteHead(list);
364       GenerateCrash(ON_REMOVE_2);
365       WriteTail(list);
366       GenerateCrash(ON_REMOVE_3);
367     } else if (node_value == my_head.value()) {
368       my_head.set_value(next.address().value());
369       next.Data()->prev = next.address().value();
370 
371       WriteHead(list);
372       GenerateCrash(ON_REMOVE_4);
373     } else if (node_value == my_tail.value()) {
374       my_tail.set_value(prev.address().value());
375       prev.Data()->next = prev.address().value();
376 
377       WriteTail(list);
378       GenerateCrash(ON_REMOVE_5);
379 
380       // Store the new tail to make sure we can undo the operation if we crash.
381       prev.Store();
382       GenerateCrash(ON_REMOVE_6);
383     }
384   }
385 
386   // Nodes out of the list can be identified by invalid pointers.
387   node->Data()->next = 0;
388   node->Data()->prev = 0;
389 
390   // The last thing to get to disk is the node itself, so before that there is
391   // enough info to recover.
392   next.Store();
393   GenerateCrash(ON_REMOVE_7);
394   prev.Store();
395   GenerateCrash(ON_REMOVE_8);
396   node->Store();
397   DecrementCounter(list);
398   if (strict)
399     UpdateIteratorsForRemoved(node_value, &next);
400 
401   UpdateIterators(&next);
402   UpdateIterators(&prev);
403   backend_->FlushIndex();
404 }
405 
406 // A crash in between Remove and Insert will lead to a dirty entry not on the
407 // list. We want to avoid that case as much as we can (as while waiting for IO),
408 // but the net effect is just an assert on debug when attempting to remove the
409 // entry. Otherwise we'll need reentrant transactions, which is an overkill.
UpdateRank(CacheRankingsBlock * node,bool modified,List list)410 void Rankings::UpdateRank(CacheRankingsBlock* node, bool modified, List list) {
411   Addr& my_head = heads_[list];
412   if (my_head.value() == node->address().value()) {
413     UpdateTimes(node, modified);
414     node->set_modified();
415     return;
416   }
417 
418   Remove(node, list, true);
419   Insert(node, modified, list);
420 }
421 
GetNext(CacheRankingsBlock * node,List list)422 CacheRankingsBlock* Rankings::GetNext(CacheRankingsBlock* node, List list) {
423   ScopedRankingsBlock next(this);
424   if (!node) {
425     Addr& my_head = heads_[list];
426     if (!my_head.is_initialized())
427       return nullptr;
428     next.reset(new CacheRankingsBlock(backend_->File(my_head), my_head));
429   } else {
430     if (!node->HasData())
431       node->Load();
432     Addr& my_tail = tails_[list];
433     if (!my_tail.is_initialized())
434       return nullptr;
435     if (my_tail.value() == node->address().value())
436       return nullptr;
437     Addr address(node->Data()->next);
438     if (address.value() == node->address().value())
439       return nullptr;  // Another tail? fail it.
440     next.reset(new CacheRankingsBlock(backend_->File(address), address));
441   }
442 
443   TrackRankingsBlock(next.get(), true);
444 
445   if (!GetRanking(next.get()))
446     return nullptr;
447 
448   ConvertToLongLived(next.get());
449   if (node && !CheckSingleLink(node, next.get()))
450     return nullptr;
451 
452   return next.release();
453 }
454 
GetPrev(CacheRankingsBlock * node,List list)455 CacheRankingsBlock* Rankings::GetPrev(CacheRankingsBlock* node, List list) {
456   ScopedRankingsBlock prev(this);
457   if (!node) {
458     Addr& my_tail = tails_[list];
459     if (!my_tail.is_initialized())
460       return nullptr;
461     prev.reset(new CacheRankingsBlock(backend_->File(my_tail), my_tail));
462   } else {
463     if (!node->HasData())
464       node->Load();
465     Addr& my_head = heads_[list];
466     if (!my_head.is_initialized())
467       return nullptr;
468     if (my_head.value() == node->address().value())
469       return nullptr;
470     Addr address(node->Data()->prev);
471     if (address.value() == node->address().value())
472       return nullptr;  // Another head? fail it.
473     prev.reset(new CacheRankingsBlock(backend_->File(address), address));
474   }
475 
476   TrackRankingsBlock(prev.get(), true);
477 
478   if (!GetRanking(prev.get()))
479     return nullptr;
480 
481   ConvertToLongLived(prev.get());
482   if (node && !CheckSingleLink(prev.get(), node))
483     return nullptr;
484 
485   return prev.release();
486 }
487 
FreeRankingsBlock(CacheRankingsBlock * node)488 void Rankings::FreeRankingsBlock(CacheRankingsBlock* node) {
489   TrackRankingsBlock(node, false);
490 }
491 
TrackRankingsBlock(CacheRankingsBlock * node,bool start_tracking)492 void Rankings::TrackRankingsBlock(CacheRankingsBlock* node,
493                                   bool start_tracking) {
494   if (!node)
495     return;
496 
497   IteratorPair current(node->address().value(), node);
498 
499   if (start_tracking)
500     iterators_.push_back(current);
501   else
502     iterators_.remove(current);
503 }
504 
SelfCheck()505 int Rankings::SelfCheck() {
506   int total = 0;
507   int error = 0;
508   for (int i = 0; i < LAST_ELEMENT; i++) {
509     int partial = CheckList(static_cast<List>(i));
510     if (partial < 0 && !error)
511       error = partial;
512     else if (partial > 0)
513       total += partial;
514   }
515 
516   return error ? error : total;
517 }
518 
SanityCheck(CacheRankingsBlock * node,bool from_list) const519 bool Rankings::SanityCheck(CacheRankingsBlock* node, bool from_list) const {
520   if (!node->VerifyHash())
521     return false;
522 
523   const RankingsNode* data = node->Data();
524 
525   if ((!data->next && data->prev) || (data->next && !data->prev))
526     return false;
527 
528   // Both pointers on zero is a node out of the list.
529   if (!data->next && !data->prev && from_list)
530     return false;
531 
532   List list = NO_USE;  // Initialize it to something.
533   if ((node->address().value() == data->prev) && !IsHead(data->prev, &list))
534     return false;
535 
536   if ((node->address().value() == data->next) && !IsTail(data->next, &list))
537     return false;
538 
539   if (!data->next && !data->prev)
540     return true;
541 
542   Addr next_addr(data->next);
543   Addr prev_addr(data->prev);
544   if (!next_addr.SanityCheck() || next_addr.file_type() != RANKINGS ||
545       !prev_addr.SanityCheck() || prev_addr.file_type() != RANKINGS)
546     return false;
547 
548   return true;
549 }
550 
DataSanityCheck(CacheRankingsBlock * node,bool from_list) const551 bool Rankings::DataSanityCheck(CacheRankingsBlock* node, bool from_list) const {
552   const RankingsNode* data = node->Data();
553   if (!data->contents)
554     return false;
555 
556   // It may have never been inserted.
557   if (from_list && (!data->last_used || !data->last_modified))
558     return false;
559 
560   return true;
561 }
562 
SetContents(CacheRankingsBlock * node,CacheAddr address)563 void Rankings::SetContents(CacheRankingsBlock* node, CacheAddr address) {
564   node->Data()->contents = address;
565   node->Store();
566 }
567 
ReadHeads()568 void Rankings::ReadHeads() {
569   for (int i = 0; i < LAST_ELEMENT; i++)
570     heads_[i] = Addr(control_data_->heads[i]);
571 }
572 
ReadTails()573 void Rankings::ReadTails() {
574   for (int i = 0; i < LAST_ELEMENT; i++)
575     tails_[i] = Addr(control_data_->tails[i]);
576 }
577 
WriteHead(List list)578 void Rankings::WriteHead(List list) {
579   control_data_->heads[list] = heads_[list].value();
580 }
581 
WriteTail(List list)582 void Rankings::WriteTail(List list) {
583   control_data_->tails[list] = tails_[list].value();
584 }
585 
GetRanking(CacheRankingsBlock * rankings)586 bool Rankings::GetRanking(CacheRankingsBlock* rankings) {
587   if (!rankings->address().is_initialized())
588     return false;
589 
590   if (!rankings->Load())
591     return false;
592 
593   if (!SanityCheck(rankings, true)) {
594     backend_->CriticalError(ERR_INVALID_LINKS);
595     return false;
596   }
597 
598   backend_->OnEvent(Stats::OPEN_RANKINGS);
599 
600   // Note that if the cache is in read_only mode, open entries are not marked
601   // as dirty, except when an entry is doomed. We have to look for open entries.
602   if (!backend_->read_only() && !rankings->Data()->dirty)
603     return true;
604 
605   EntryImpl* entry = backend_->GetOpenEntry(rankings);
606   if (!entry) {
607     if (backend_->read_only())
608       return true;
609 
610     // We cannot trust this entry, but we cannot initiate a cleanup from this
611     // point (we may be in the middle of a cleanup already). The entry will be
612     // deleted when detected from a regular open/create path.
613     rankings->Data()->dirty = backend_->GetCurrentEntryId() - 1;
614     if (!rankings->Data()->dirty)
615       rankings->Data()->dirty--;
616     return true;
617   }
618 
619   // Note that we should not leave this module without deleting rankings first.
620   rankings->SetData(entry->rankings()->Data());
621 
622   return true;
623 }
624 
ConvertToLongLived(CacheRankingsBlock * rankings)625 void Rankings::ConvertToLongLived(CacheRankingsBlock* rankings) {
626   if (rankings->own_data())
627     return;
628 
629   // We cannot return a shared node because we are not keeping a reference
630   // to the entry that owns the buffer. Make this node a copy of the one that
631   // we have, and let the iterator logic update it when the entry changes.
632   CacheRankingsBlock temp(nullptr, Addr(0));
633   *temp.Data() = *rankings->Data();
634   rankings->StopSharingData();
635   *rankings->Data() = *temp.Data();
636 }
637 
CompleteTransaction()638 void Rankings::CompleteTransaction() {
639   Addr node_addr(static_cast<CacheAddr>(control_data_->transaction));
640   if (!node_addr.is_initialized() || node_addr.is_separate_file()) {
641     NOTREACHED() << "Invalid rankings info.";
642   }
643 
644   CacheRankingsBlock node(backend_->File(node_addr), node_addr);
645   if (!node.Load())
646     return;
647 
648   node.Store();
649 
650   // We want to leave the node inside the list. The entry must me marked as
651   // dirty, and will be removed later. Otherwise, we'll get assertions when
652   // attempting to remove the dirty entry.
653   if (INSERT == control_data_->operation) {
654     FinishInsert(&node);
655   } else if (REMOVE == control_data_->operation) {
656     RevertRemove(&node);
657   } else {
658     NOTREACHED() << "Invalid operation to recover.";
659   }
660 }
661 
FinishInsert(CacheRankingsBlock * node)662 void Rankings::FinishInsert(CacheRankingsBlock* node) {
663   control_data_->transaction = 0;
664   control_data_->operation = 0;
665   Addr& my_head = heads_[control_data_->operation_list];
666   Addr& my_tail = tails_[control_data_->operation_list];
667   if (my_head.value() != node->address().value()) {
668     if (my_tail.value() == node->address().value()) {
669       // This part will be skipped by the logic of Insert.
670       node->Data()->next = my_tail.value();
671     }
672 
673     Insert(node, true, static_cast<List>(control_data_->operation_list));
674   }
675 
676   // Tell the backend about this entry.
677   backend_->RecoveredEntry(node);
678 }
679 
RevertRemove(CacheRankingsBlock * node)680 void Rankings::RevertRemove(CacheRankingsBlock* node) {
681   Addr next_addr(node->Data()->next);
682   Addr prev_addr(node->Data()->prev);
683   if (!next_addr.is_initialized() || !prev_addr.is_initialized()) {
684     // The operation actually finished. Nothing to do.
685     control_data_->transaction = 0;
686     return;
687   }
688   if (next_addr.is_separate_file() || prev_addr.is_separate_file()) {
689     NOTREACHED() << "Invalid rankings info.";
690   }
691 
692   CacheRankingsBlock next(backend_->File(next_addr), next_addr);
693   CacheRankingsBlock prev(backend_->File(prev_addr), prev_addr);
694   if (!next.Load() || !prev.Load())
695     return;
696 
697   CacheAddr node_value = node->address().value();
698   DCHECK(prev.Data()->next == node_value ||
699          prev.Data()->next == prev_addr.value() ||
700          prev.Data()->next == next.address().value());
701   DCHECK(next.Data()->prev == node_value ||
702          next.Data()->prev == next_addr.value() ||
703          next.Data()->prev == prev.address().value());
704 
705   if (node_value != prev_addr.value())
706     prev.Data()->next = node_value;
707   if (node_value != next_addr.value())
708     next.Data()->prev = node_value;
709 
710   List my_list = static_cast<List>(control_data_->operation_list);
711   Addr& my_head = heads_[my_list];
712   Addr& my_tail = tails_[my_list];
713   if (!my_head.is_initialized() || !my_tail.is_initialized()) {
714     my_head.set_value(node_value);
715     my_tail.set_value(node_value);
716     WriteHead(my_list);
717     WriteTail(my_list);
718   } else if (my_head.value() == next.address().value()) {
719     my_head.set_value(node_value);
720     prev.Data()->next = next.address().value();
721     WriteHead(my_list);
722   } else if (my_tail.value() == prev.address().value()) {
723     my_tail.set_value(node_value);
724     next.Data()->prev = prev.address().value();
725     WriteTail(my_list);
726   }
727 
728   next.Store();
729   prev.Store();
730   control_data_->transaction = 0;
731   control_data_->operation = 0;
732   backend_->FlushIndex();
733 }
734 
CheckLinks(CacheRankingsBlock * node,CacheRankingsBlock * prev,CacheRankingsBlock * next,List * list)735 bool Rankings::CheckLinks(CacheRankingsBlock* node, CacheRankingsBlock* prev,
736                           CacheRankingsBlock* next, List* list) {
737   CacheAddr node_addr = node->address().value();
738   if (prev->Data()->next == node_addr &&
739       next->Data()->prev == node_addr) {
740     // A regular linked node.
741     return true;
742   }
743 
744   if (node_addr != prev->address().value() &&
745       node_addr != next->address().value() &&
746       prev->Data()->next == next->address().value() &&
747       next->Data()->prev == prev->address().value()) {
748     // The list is actually ok, node is wrong.
749     node->Data()->next = 0;
750     node->Data()->prev = 0;
751     node->Store();
752     return false;
753   }
754 
755   if (prev->Data()->next == node_addr ||
756       next->Data()->prev == node_addr) {
757     // Only one link is weird, lets double check.
758     if (prev->Data()->next != node_addr && IsHead(node_addr, list))
759       return true;
760 
761     if (next->Data()->prev != node_addr && IsTail(node_addr, list))
762       return true;
763   }
764 
765   LOG(ERROR) << "Inconsistent LRU.";
766   STRESS_NOTREACHED();
767 
768   backend_->CriticalError(ERR_INVALID_LINKS);
769   return false;
770 }
771 
CheckSingleLink(CacheRankingsBlock * prev,CacheRankingsBlock * next)772 bool Rankings::CheckSingleLink(CacheRankingsBlock* prev,
773                                CacheRankingsBlock* next) {
774   if (prev->Data()->next != next->address().value() ||
775       next->Data()->prev != prev->address().value()) {
776     LOG(ERROR) << "Inconsistent LRU.";
777 
778     backend_->CriticalError(ERR_INVALID_LINKS);
779     return false;
780   }
781 
782   return true;
783 }
784 
CheckList(List list)785 int Rankings::CheckList(List list) {
786   Addr last1, last2;
787   int head_items;
788   int rv = CheckListSection(list, last1, last2, true,  // Head to tail.
789                             &last1, &last2, &head_items);
790   if (rv == ERR_NO_ERROR)
791     return head_items;
792 
793   return rv;
794 }
795 
796 // Note that the returned error codes assume a forward walk (from head to tail)
797 // so they have to be adjusted accordingly by the caller. We use two stop values
798 // to be able to detect a corrupt node at the end that is not linked going back.
CheckListSection(List list,Addr end1,Addr end2,bool forward,Addr * last,Addr * second_last,int * num_items)799 int Rankings::CheckListSection(List list, Addr end1, Addr end2, bool forward,
800                                Addr* last, Addr* second_last, int* num_items) {
801   Addr current = forward ? heads_[list] : tails_[list];
802   *last = *second_last = current;
803   *num_items = 0;
804   if (!current.is_initialized())
805     return ERR_NO_ERROR;
806 
807   if (!current.SanityCheckForRankings())
808     return ERR_INVALID_HEAD;
809 
810   std::unique_ptr<CacheRankingsBlock> node;
811   Addr prev_addr(current);
812   do {
813     node =
814         std::make_unique<CacheRankingsBlock>(backend_->File(current), current);
815     node->Load();
816     if (!SanityCheck(node.get(), true))
817       return ERR_INVALID_ENTRY;
818 
819     CacheAddr next = forward ? node->Data()->next : node->Data()->prev;
820     CacheAddr prev = forward ? node->Data()->prev : node->Data()->next;
821 
822     if (prev != prev_addr.value())
823       return ERR_INVALID_PREV;
824 
825     Addr next_addr(next);
826     if (!next_addr.SanityCheckForRankings())
827       return ERR_INVALID_NEXT;
828 
829     prev_addr = current;
830     current = next_addr;
831     *second_last = *last;
832     *last = current;
833     (*num_items)++;
834 
835     if (next_addr == prev_addr) {
836       if (next_addr == (forward ? tails_[list] : heads_[list]))
837         return ERR_NO_ERROR;
838       return ERR_INVALID_TAIL;
839     }
840   } while (current != end1 && current != end2);
841   return ERR_NO_ERROR;
842 }
843 
IsHead(CacheAddr addr,List * list) const844 bool Rankings::IsHead(CacheAddr addr, List* list) const {
845   for (int i = 0; i < LAST_ELEMENT; i++) {
846     if (addr == heads_[i].value()) {
847       *list = static_cast<List>(i);
848       return true;
849     }
850   }
851   return false;
852 }
853 
IsTail(CacheAddr addr,List * list) const854 bool Rankings::IsTail(CacheAddr addr, List* list) const {
855   for (int i = 0; i < LAST_ELEMENT; i++) {
856     if (addr == tails_[i].value()) {
857       *list = static_cast<List>(i);
858       return true;
859     }
860   }
861   return false;
862 }
863 
864 // We expect to have just a few iterators at any given time, maybe two or three,
865 // But we could have more than one pointing at the same mode. We walk the list
866 // of cache iterators and update all that are pointing to the given node.
UpdateIterators(CacheRankingsBlock * node)867 void Rankings::UpdateIterators(CacheRankingsBlock* node) {
868   CacheAddr address = node->address().value();
869   for (auto& iterator : iterators_) {
870     if (iterator.first == address && iterator.second->HasData()) {
871       CacheRankingsBlock* other = iterator.second;
872       if (other != node)
873         *other->Data() = *node->Data();
874     }
875   }
876 }
877 
UpdateIteratorsForRemoved(CacheAddr address,CacheRankingsBlock * next)878 void Rankings::UpdateIteratorsForRemoved(CacheAddr address,
879                                          CacheRankingsBlock* next) {
880   CacheAddr next_addr = next->address().value();
881   for (auto& iterator : iterators_) {
882     if (iterator.first == address) {
883       iterator.first = next_addr;
884       iterator.second->CopyFrom(next);
885     }
886   }
887 }
888 
IncrementCounter(List list)889 void Rankings::IncrementCounter(List list) {
890   if (!count_lists_)
891     return;
892 
893   DCHECK(control_data_->sizes[list] < std::numeric_limits<int32_t>::max());
894   if (control_data_->sizes[list] < std::numeric_limits<int32_t>::max())
895     control_data_->sizes[list]++;
896 }
897 
DecrementCounter(List list)898 void Rankings::DecrementCounter(List list) {
899   if (!count_lists_)
900     return;
901 
902   DCHECK(control_data_->sizes[list] > 0);
903   if (control_data_->sizes[list] > 0)
904     control_data_->sizes[list]--;
905 }
906 
907 }  // namespace disk_cache
908