OLD | NEW |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 // See net/disk_cache/disk_cache.h for the public interface of the cache. | 5 // See net/disk_cache/disk_cache.h for the public interface of the cache. |
6 | 6 |
7 #ifndef NET_DISK_CACHE_BACKEND_IMPL_H_ | 7 #ifndef NET_DISK_CACHE_BACKEND_IMPL_H_ |
8 #define NET_DISK_CACHE_BACKEND_IMPL_H_ | 8 #define NET_DISK_CACHE_BACKEND_IMPL_H_ |
9 | 9 |
10 #include "base/files/file_path.h" | 10 #include "base/files/file_path.h" |
11 #include "base/hash_tables.h" | 11 #include "base/hash_tables.h" |
12 #include "base/timer.h" | 12 #include "base/timer.h" |
13 #include "net/disk_cache/block_files.h" | 13 #include "net/disk_cache/block_files.h" |
14 #include "net/disk_cache/disk_cache.h" | 14 #include "net/disk_cache/disk_cache.h" |
15 #include "net/disk_cache/eviction.h" | 15 #include "net/disk_cache/eviction.h" |
16 #include "net/disk_cache/in_flight_backend_io.h" | 16 #include "net/disk_cache/in_flight_backend_io.h" |
17 #include "net/disk_cache/rankings.h" | 17 #include "net/disk_cache/rankings.h" |
18 #include "net/disk_cache/stats.h" | 18 #include "net/disk_cache/stats.h" |
19 #include "net/disk_cache/stress_support.h" | 19 #include "net/disk_cache/stress_support.h" |
20 #include "net/disk_cache/trace.h" | 20 #include "net/disk_cache/trace.h" |
21 | 21 |
22 namespace net { | |
23 class NetLog; | |
24 } // namespace net | |
25 | |
26 namespace disk_cache { | 22 namespace disk_cache { |
27 | 23 |
28 enum BackendFlags { | |
29 kNone = 0, | |
30 kMask = 1, // A mask (for the index table) was specified. | |
31 kMaxSize = 1 << 1, // A maximum size was provided. | |
32 kUnitTestMode = 1 << 2, // We are modifying the behavior for testing. | |
33 kUpgradeMode = 1 << 3, // This is the upgrade tool (dump). | |
34 kNewEviction = 1 << 4, // Use of new eviction was specified. | |
35 kNoRandom = 1 << 5, // Don't add randomness to the behavior. | |
36 kNoLoadProtection = 1 << 6, // Don't act conservatively under load. | |
37 kNoBuffering = 1 << 7 // Disable extended IO buffering. | |
38 }; | |
39 | |
40 // This class implements the Backend interface. An object of this | 24 // This class implements the Backend interface. An object of this |
41 // class handles the operations of the cache for a particular profile. | 25 // class handles the operations of the cache for a particular profile. |
42 class NET_EXPORT_PRIVATE BackendImpl : public Backend { | 26 class NET_EXPORT_PRIVATE BackendImpl : public Backend { |
43 friend class Eviction; | 27 friend class Eviction; |
44 public: | 28 public: |
45 BackendImpl(const base::FilePath& path, base::MessageLoopProxy* cache_thread, | 29 BackendImpl(const base::FilePath& path, base::MessageLoopProxy* cache_thread, |
46 net::NetLog* net_log); | 30 net::NetLog* net_log); |
47 // mask can be used to limit the usable size of the hash table, for testing. | |
48 BackendImpl(const base::FilePath& path, uint32 mask, | |
49 base::MessageLoopProxy* cache_thread, net::NetLog* net_log); | |
50 virtual ~BackendImpl(); | |
51 | 31 |
52 // Performs general initialization for this current instance of the cache. | 32 // Performs general initialization for this current instance of the cache. |
53 int Init(const CompletionCallback& callback); | 33 int Init(const CompletionCallback& callback); |
54 | 34 |
55 // Performs the actual initialization and final cleanup on destruction. | 35 private: |
56 int SyncInit(); | |
57 void CleanupCache(); | 36 void CleanupCache(); |
58 | 37 |
59 // Same behavior as OpenNextEntry but walks the list from back to front. | |
60 int OpenPrevEntry(void** iter, Entry** prev_entry, | |
61 const CompletionCallback& callback); | |
62 | |
63 // Synchronous implementation of the asynchronous interface. | |
64 int SyncOpenEntry(const std::string& key, Entry** entry); | |
65 int SyncCreateEntry(const std::string& key, Entry** entry); | |
66 int SyncDoomEntry(const std::string& key); | |
67 int SyncDoomAllEntries(); | |
68 int SyncDoomEntriesBetween(base::Time initial_time, | |
69 base::Time end_time); | |
70 int SyncDoomEntriesSince(base::Time initial_time); | |
71 int SyncOpenNextEntry(void** iter, Entry** next_entry); | |
72 int SyncOpenPrevEntry(void** iter, Entry** prev_entry); | |
73 void SyncEndEnumeration(void* iter); | |
74 void SyncOnExternalCacheHit(const std::string& key); | |
75 | |
76 // Open or create an entry for the given |key| or |iter|. | |
77 EntryImpl* OpenEntryImpl(const std::string& key); | |
78 EntryImpl* CreateEntryImpl(const std::string& key); | |
79 EntryImpl* OpenNextEntryImpl(void** iter); | |
80 EntryImpl* OpenPrevEntryImpl(void** iter); | |
81 | |
82 // Sets the maximum size for the total amount of data stored by this instance. | |
83 bool SetMaxSize(int max_bytes); | |
84 | |
85 // Sets the cache type for this backend. | |
86 void SetType(net::CacheType type); | |
87 | |
88 // Returns the full name for an external storage file. | 38 // Returns the full name for an external storage file. |
89 base::FilePath GetFileName(Addr address) const; | 39 base::FilePath GetFileName(Addr address) const; |
90 | 40 |
91 // Returns the actual file used to store a given (non-external) address. | 41 // Creates a new backing file for the cache index. |
92 MappedFile* File(Addr address); | 42 bool CreateBackingStore(disk_cache::File* file); |
93 | 43 bool InitBackingStore(bool* file_created); |
94 // Returns a weak pointer to the background queue. | |
95 base::WeakPtr<InFlightBackendIO> GetBackgroundQueue(); | |
96 | |
97 // Creates an external storage file. | |
98 bool CreateExternalFile(Addr* address); | |
99 | |
100 // Creates a new storage block of size block_count. | |
101 bool CreateBlock(FileType block_type, int block_count, | |
102 Addr* block_address); | |
103 | |
104 // Deletes a given storage block. deep set to true can be used to zero-fill | |
105 // the related storage in addition of releasing the related block. | |
106 void DeleteBlock(Addr block_address, bool deep); | |
107 | |
108 // Retrieves a pointer to the LRU-related data. | |
109 LruData* GetLruData(); | |
110 | |
111 // Updates the ranking information for an entry. | |
112 void UpdateRank(EntryImpl* entry, bool modified); | |
113 | |
114 // A node was recovered from a crash, it may not be on the index, so this | |
115 // method checks it and takes the appropriate action. | |
116 void RecoveredEntry(CacheRankingsBlock* rankings); | |
117 | |
118 // Permanently deletes an entry, but still keeps track of it. | |
119 void InternalDoomEntry(EntryImpl* entry); | |
120 | |
121 #if defined(NET_BUILD_STRESS_CACHE) | |
122 // Returns the address of the entry linked to the entry at a given |address|. | |
123 CacheAddr GetNextAddr(Addr address); | |
124 | |
125 // Verifies that |entry| is not currently reachable through the index. | |
126 void NotLinked(EntryImpl* entry); | |
127 #endif | |
128 | |
129 // Removes all references to this entry. | |
130 void RemoveEntry(EntryImpl* entry); | |
131 | |
132 // This method must be called when an entry is released for the last time, so | |
133 // the entry should not be used anymore. |address| is the cache address of the | |
134 // entry. | |
135 void OnEntryDestroyBegin(Addr address); | |
136 | |
137 // This method must be called after all resources for an entry have been | |
138 // released. | |
139 void OnEntryDestroyEnd(); | |
140 | |
141 // If the data stored by the provided |rankings| points to an open entry, | |
142 // returns a pointer to that entry, otherwise returns NULL. Note that this | |
143 // method does NOT increase the ref counter for the entry. | |
144 EntryImpl* GetOpenEntry(CacheRankingsBlock* rankings) const; | |
145 | |
146 // Returns the id being used on this run of the cache. | |
147 int32 GetCurrentEntryId() const; | |
148 | |
149 // Returns the maximum size for a file to reside on the cache. | |
150 int MaxFileSize() const; | |
151 | |
152 // A user data block is being created, extended or truncated. | |
153 void ModifyStorageSize(int32 old_size, int32 new_size); | |
154 | |
155 // Logs requests that are denied due to being too big. | |
156 void TooMuchStorageRequested(int32 size); | |
157 | |
158 // Returns true if a temporary buffer is allowed to be extended. | |
159 bool IsAllocAllowed(int current_size, int new_size); | |
160 | |
161 // Tracks the release of |size| bytes by an entry buffer. | |
162 void BufferDeleted(int size); | |
163 | |
164 // Only intended for testing the two previous methods. | |
165 int GetTotalBuffersSize() const { | |
166 return buffer_bytes_; | |
167 } | |
168 | |
169 // Returns true if this instance seems to be under heavy load. | |
170 bool IsLoaded() const; | |
171 | |
172 // Returns the full histogram name, for the given base |name| and experiment, | |
173 // and the current cache type. The name will be "DiskCache.t.name_e" where n | |
174 // is the cache type and e the provided |experiment|. | |
175 std::string HistogramName(const char* name, int experiment) const; | |
176 | |
177 net::CacheType cache_type() const { | |
178 return cache_type_; | |
179 } | |
180 | |
181 bool read_only() const { | |
182 return read_only_; | |
183 } | |
184 | |
185 // Returns a weak pointer to this object. | |
186 base::WeakPtr<BackendImpl> GetWeakPtr(); | |
187 | |
188 // Returns true if we should send histograms for this user again. The caller | |
189 // must call this function only once per run (because it returns always the | |
190 // same thing on a given run). | |
191 bool ShouldReportAgain(); | |
192 | |
193 // Reports some data when we filled up the cache. | |
194 void FirstEviction(); | |
195 | |
196 // Reports a critical error (and disables the cache). | |
197 void CriticalError(int error); | |
198 | 44 |
199 // Reports an uncommon, recoverable error. | 45 // Reports an uncommon, recoverable error. |
200 void ReportError(int error); | 46 void ReportError(int error); |
201 | 47 |
202 // Called when an interesting event should be logged (counted). | |
203 void OnEvent(Stats::Counters an_event); | |
204 | |
205 // Keeps track of payload access (doesn't include metadata). | |
206 void OnRead(int bytes); | |
207 void OnWrite(int bytes); | |
208 | |
209 // Timer callback to calculate usage statistics. | |
210 void OnStatsTimer(); | |
211 | |
212 // Handles the pending asynchronous IO count. | |
213 void IncrementIoCount(); | |
214 void DecrementIoCount(); | |
215 | |
216 // Sets internal parameters to enable unit testing mode. | |
217 void SetUnitTestMode(); | |
218 | |
219 // Sets internal parameters to enable upgrade mode (for internal tools). | |
220 void SetUpgradeMode(); | |
221 | |
222 // Sets the eviction algorithm to version 2. | |
223 void SetNewEviction(); | |
224 | |
225 // Sets an explicit set of BackendFlags. | |
226 void SetFlags(uint32 flags); | |
227 | |
228 // Clears the counter of references to test handling of corruptions. | |
229 void ClearRefCountForTest(); | |
230 | |
231 // Sends a dummy operation through the operation queue, for unit tests. | |
232 int FlushQueueForTest(const CompletionCallback& callback); | |
233 | |
234 // Runs the provided task on the cache thread. The task will be automatically | |
235 // deleted after it runs. | |
236 int RunTaskForTest(const base::Closure& task, | |
237 const CompletionCallback& callback); | |
238 | |
239 // Trims an entry (all if |empty| is true) from the list of deleted | |
240 // entries. This method should be called directly on the cache thread. | |
241 void TrimForTest(bool empty); | |
242 | |
243 // Trims an entry (all if |empty| is true) from the list of deleted | |
244 // entries. This method should be called directly on the cache thread. | |
245 void TrimDeletedListForTest(bool empty); | |
246 | |
247 // Performs a simple self-check, and returns the number of dirty items | |
248 // or an error code (negative value). | |
249 int SelfCheck(); | |
250 | |
251 // Ensures the index is flushed to disk (a no-op on platforms with mmap). | |
252 void FlushIndex(); | |
253 | |
254 // Backend implementation. | |
255 virtual net::CacheType GetCacheType() const OVERRIDE; | |
256 virtual int32 GetEntryCount() const OVERRIDE; | |
257 virtual int OpenEntry(const std::string& key, Entry** entry, | |
258 const CompletionCallback& callback) OVERRIDE; | |
259 virtual int CreateEntry(const std::string& key, Entry** entry, | |
260 const CompletionCallback& callback) OVERRIDE; | |
261 virtual int DoomEntry(const std::string& key, | |
262 const CompletionCallback& callback) OVERRIDE; | |
263 virtual int DoomAllEntries(const CompletionCallback& callback) OVERRIDE; | |
264 virtual int DoomEntriesBetween(base::Time initial_time, | |
265 base::Time end_time, | |
266 const CompletionCallback& callback) OVERRIDE; | |
267 virtual int DoomEntriesSince(base::Time initial_time, | |
268 const CompletionCallback& callback) OVERRIDE; | |
269 virtual int OpenNextEntry(void** iter, Entry** next_entry, | |
270 const CompletionCallback& callback) OVERRIDE; | |
271 virtual void EndEnumeration(void** iter) OVERRIDE; | |
272 virtual void GetStats(StatsItems* stats) OVERRIDE; | |
273 virtual void OnExternalCacheHit(const std::string& key) OVERRIDE; | |
274 | |
275 private: | |
276 typedef base::hash_map<CacheAddr, EntryImpl*> EntriesMap; | |
277 | |
278 // Creates a new backing file for the cache index. | |
279 bool CreateBackingStore(disk_cache::File* file); | |
280 bool InitBackingStore(bool* file_created); | |
281 void AdjustMaxCacheSize(int table_len); | |
282 | |
283 bool InitStats(); | |
284 void StoreStats(); | |
285 | |
286 // Deletes the cache and starts again. | |
287 void RestartCache(bool failure); | |
288 void PrepareForRestart(); | |
289 | |
290 // Creates a new entry object. Returns zero on success, or a disk_cache error | |
291 // on failure. | |
292 int NewEntry(Addr address, EntryImpl** entry); | |
293 | |
294 // Returns a given entry from the cache. The entry to match is determined by | |
295 // key and hash, and the returned entry may be the matched one or it's parent | |
296 // on the list of entries with the same hash (or bucket). To look for a parent | |
297 // of a given entry, |entry_addr| should be grabbed from that entry, so that | |
298 // if it doesn't match the entry on the index, we know that it was replaced | |
299 // with a new entry; in this case |*match_error| will be set to true and the | |
300 // return value will be NULL. | |
301 EntryImpl* MatchEntry(const std::string& key, uint32 hash, bool find_parent, | |
302 Addr entry_addr, bool* match_error); | |
303 | |
304 // Opens the next or previous entry on a cache iteration. | |
305 EntryImpl* OpenFollowingEntry(bool forward, void** iter); | |
306 | |
307 // Opens the next or previous entry on a single list. If successful, | |
308 // |from_entry| will be updated to point to the new entry, otherwise it will | |
309 // be set to NULL; in other words, it is used as an explicit iterator. | |
310 bool OpenFollowingEntryFromList(bool forward, Rankings::List list, | |
311 CacheRankingsBlock** from_entry, | |
312 EntryImpl** next_entry); | |
313 | |
314 // Returns the entry that is pointed by |next|, from the given |list|. | |
315 EntryImpl* GetEnumeratedEntry(CacheRankingsBlock* next, Rankings::List list); | |
316 | |
317 // Re-opens an entry that was previously deleted. | |
318 EntryImpl* ResurrectEntry(EntryImpl* deleted_entry); | |
319 | |
320 void DestroyInvalidEntry(EntryImpl* entry); | |
321 | |
322 // Handles the used storage count. | |
323 void AddStorageSize(int32 bytes); | |
324 void SubstractStorageSize(int32 bytes); | |
325 | |
326 // Update the number of referenced cache entries. | |
327 void IncreaseNumRefs(); | |
328 void DecreaseNumRefs(); | |
329 void IncreaseNumEntries(); | |
330 void DecreaseNumEntries(); | |
331 | |
332 // Dumps current cache statistics to the log. | |
333 void LogStats(); | |
334 | |
335 // Send UMA stats. | |
336 void ReportStats(); | |
337 | |
338 // Upgrades the index file to version 2.1. | |
339 void UpgradeTo2_1(); | |
340 | |
341 // Performs basic checks on the index file. Returns false on failure. | 48 // Performs basic checks on the index file. Returns false on failure. |
342 bool CheckIndex(); | 49 bool CheckIndex(); |
343 | 50 |
344 // Part of the self test. Returns the number or dirty entries, or an error. | |
345 int CheckAllEntries(); | |
346 | |
347 // Part of the self test. Returns false if the entry is corrupt. | |
348 bool CheckEntry(EntryImpl* cache_entry); | |
349 | |
350 // Returns the maximum total memory for the memory buffers. | |
351 int MaxBuffersSize(); | |
352 | |
353 InFlightBackendIO background_queue_; // The controller of pending operations. | |
354 scoped_refptr<MappedFile> index_; // The main cache index. | |
355 base::FilePath path_; // Path to the folder used as backing storage. | 51 base::FilePath path_; // Path to the folder used as backing storage. |
356 Index* data_; // Pointer to the index data. | |
357 BlockFiles block_files_; // Set of files used to store all data. | 52 BlockFiles block_files_; // Set of files used to store all data. |
358 Rankings rankings_; // Rankings to be able to trim the cache. | |
359 uint32 mask_; // Binary mask to map a hash to the hash table. | |
360 int32 max_size_; // Maximum data size for this instance. | |
361 Eviction eviction_; // Handler of the eviction algorithm. | |
362 EntriesMap open_entries_; // Map of open entries. | |
363 int num_refs_; // Number of referenced cache entries. | |
364 int max_refs_; // Max number of referenced cache entries. | |
365 int num_pending_io_; // Number of pending IO operations. | |
366 int entry_count_; // Number of entries accessed lately. | |
367 int byte_count_; // Number of bytes read/written lately. | |
368 int buffer_bytes_; // Total size of the temporary entries' buffers. | |
369 int up_ticks_; // The number of timer ticks received (OnStatsTimer). | |
370 net::CacheType cache_type_; | |
371 int uma_report_; // Controls transmission of UMA data. | |
372 uint32 user_flags_; // Flags set by the user. | |
373 bool init_; // controls the initialization of the system. | 53 bool init_; // controls the initialization of the system. |
374 bool restarted_; | |
375 bool unit_test_; | |
376 bool read_only_; // Prevents updates of the rankings data (used by tools). | |
377 bool disabled_; | |
378 bool new_eviction_; // What eviction algorithm should be used. | |
379 bool first_timer_; // True if the timer has not been called. | |
380 bool user_load_; // True if we see a high load coming from the caller. | |
381 | |
382 net::NetLog* net_log_; | |
383 | |
384 Stats stats_; // Usage statistics. | |
385 scoped_ptr<base::RepeatingTimer<BackendImpl> > timer_; // Usage timer. | |
386 base::WaitableEvent done_; // Signals the end of background work. | |
387 scoped_refptr<TraceObject> trace_object_; // Initializes internal tracing. | |
388 base::WeakPtrFactory<BackendImpl> ptr_factory_; | |
389 | 54 |
390 DISALLOW_COPY_AND_ASSIGN(BackendImpl); | 55 DISALLOW_COPY_AND_ASSIGN(BackendImpl); |
391 }; | 56 }; |
392 | 57 |
393 // Returns the preferred max cache size given the available disk space. | |
394 NET_EXPORT_PRIVATE int PreferedCacheSize(int64 available); | |
395 | |
396 } // namespace disk_cache | 58 } // namespace disk_cache |
397 | 59 |
398 #endif // NET_DISK_CACHE_BACKEND_IMPL_H_ | 60 #endif // NET_DISK_CACHE_BACKEND_IMPL_H_ |
OLD | NEW |