You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DfsBlockCache.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (C) 2008-2011, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.dfs;
  45. import java.io.IOException;
  46. import java.util.concurrent.atomic.AtomicLong;
  47. import java.util.concurrent.atomic.AtomicReferenceArray;
  48. import java.util.concurrent.locks.ReentrantLock;
  49. import org.eclipse.jgit.annotations.Nullable;
  50. import org.eclipse.jgit.internal.JGitText;
  51. /**
  52. * Caches slices of a {@link BlockBasedFile} in memory for faster read access.
  53. * <p>
  54. * The DfsBlockCache serves as a Java based "buffer cache", loading segments of
  55. * a BlockBasedFile into the JVM heap prior to use. As JGit often wants to do
  56. * reads of only tiny slices of a file, the DfsBlockCache tries to smooth out
  57. * these tiny reads into larger block-sized IO operations.
  58. * <p>
  59. * Whenever a cache miss occurs, loading is invoked by exactly one thread for
  60. * the given <code>(DfsPackKey,position)</code> key tuple. This is ensured by an
  61. * array of locks, with the tuple hashed to a lock instance.
  62. * <p>
  63. * Its too expensive during object access to be accurate with a least recently
  64. * used (LRU) algorithm. Strictly ordering every read is a lot of overhead that
  65. * typically doesn't yield a corresponding benefit to the application. This
  66. * cache implements a clock replacement algorithm, giving each block one chance
  67. * to have been accessed during a sweep of the cache to save itself from
  68. * eviction.
  69. * <p>
  70. * Entities created by the cache are held under hard references, preventing the
  71. * Java VM from clearing anything. Blocks are discarded by the replacement
  72. * algorithm when adding a new block would cause the cache to exceed its
  73. * configured maximum size.
  74. * <p>
  75. * The key tuple is passed through to methods as a pair of parameters rather
  76. * than as a single Object, thus reducing the transient memory allocations of
  77. * callers. It is more efficient to avoid the allocation, as we can't be 100%
  78. * sure that a JIT would be able to stack-allocate a key tuple.
  79. * <p>
  80. * The internal hash table does not expand at runtime, instead it is fixed in
  81. * size at cache creation time. The internal lock table used to gate load
  82. * invocations is also fixed in size.
  83. */
  84. public final class DfsBlockCache {
  85. private static volatile DfsBlockCache cache;
  86. static {
  87. reconfigure(new DfsBlockCacheConfig());
  88. }
  89. /**
  90. * Modify the configuration of the window cache.
  91. * <p>
  92. * The new configuration is applied immediately, and the existing cache is
  93. * cleared.
  94. *
  95. * @param cfg
  96. * the new window cache configuration.
  97. * @throws IllegalArgumentException
  98. * the cache configuration contains one or more invalid
  99. * settings, usually too low of a limit.
  100. */
  101. public static void reconfigure(DfsBlockCacheConfig cfg) {
  102. cache = new DfsBlockCache(cfg);
  103. }
  104. /** @return the currently active DfsBlockCache. */
  105. public static DfsBlockCache getInstance() {
  106. return cache;
  107. }
  108. /** Number of entries in {@link #table}. */
  109. private final int tableSize;
  110. /** Hash bucket directory; entries are chained below. */
  111. private final AtomicReferenceArray<HashEntry> table;
  112. /** Locks to prevent concurrent loads for same (PackFile,position). */
  113. private final ReentrantLock[] loadLocks;
  114. /** Maximum number of bytes the cache should hold. */
  115. private final long maxBytes;
  116. /** Pack files smaller than this size can be copied through the cache. */
  117. private final long maxStreamThroughCache;
  118. /**
  119. * Suggested block size to read from pack files in.
  120. * <p>
  121. * If a pack file does not have a native block size, this size will be used.
  122. * <p>
  123. * If a pack file has a native size, a whole multiple of the native size
  124. * will be used until it matches this size.
  125. * <p>
  126. * The value for blockSize must be a power of 2.
  127. */
  128. private final int blockSize;
  129. /** As {@link #blockSize} is a power of 2, bits to shift for a / blockSize. */
  130. private final int blockSizeShift;
  131. /** Number of times a block was found in the cache. */
  132. private final AtomicLong statHit;
  133. /** Number of times a block was not found, and had to be loaded. */
  134. private final AtomicLong statMiss;
  135. /** Number of blocks evicted due to cache being full. */
  136. private volatile long statEvict;
  137. /** Protects the clock and its related data. */
  138. private final ReentrantLock clockLock;
  139. /** Current position of the clock. */
  140. private Ref clockHand;
  141. /** Number of bytes currently loaded in the cache. */
  142. private volatile long liveBytes;
  143. @SuppressWarnings("unchecked")
  144. private DfsBlockCache(final DfsBlockCacheConfig cfg) {
  145. tableSize = tableSize(cfg);
  146. if (tableSize < 1)
  147. throw new IllegalArgumentException(JGitText.get().tSizeMustBeGreaterOrEqual1);
  148. table = new AtomicReferenceArray<>(tableSize);
  149. loadLocks = new ReentrantLock[cfg.getConcurrencyLevel()];
  150. for (int i = 0; i < loadLocks.length; i++)
  151. loadLocks[i] = new ReentrantLock(true /* fair */);
  152. maxBytes = cfg.getBlockLimit();
  153. maxStreamThroughCache = (long) (maxBytes * cfg.getStreamRatio());
  154. blockSize = cfg.getBlockSize();
  155. blockSizeShift = Integer.numberOfTrailingZeros(blockSize);
  156. clockLock = new ReentrantLock(true /* fair */);
  157. clockHand = new Ref<>(DfsStreamKey.of(""), -1, 0, null); //$NON-NLS-1$
  158. clockHand.next = clockHand;
  159. statHit = new AtomicLong();
  160. statMiss = new AtomicLong();
  161. }
  162. boolean shouldCopyThroughCache(long length) {
  163. return length <= maxStreamThroughCache;
  164. }
  165. /** @return total number of bytes in the cache. */
  166. public long getCurrentSize() {
  167. return liveBytes;
  168. }
  169. /** @return 0..100, defining how full the cache is. */
  170. public long getFillPercentage() {
  171. return getCurrentSize() * 100 / maxBytes;
  172. }
  173. /** @return number of requests for items in the cache. */
  174. public long getHitCount() {
  175. return statHit.get();
  176. }
  177. /** @return number of requests for items not in the cache. */
  178. public long getMissCount() {
  179. return statMiss.get();
  180. }
  181. /** @return total number of requests (hit + miss). */
  182. public long getTotalRequestCount() {
  183. return getHitCount() + getMissCount();
  184. }
  185. /** @return 0..100, defining number of cache hits. */
  186. public long getHitRatio() {
  187. long hits = statHit.get();
  188. long miss = statMiss.get();
  189. long total = hits + miss;
  190. if (total == 0)
  191. return 0;
  192. return hits * 100 / total;
  193. }
  194. /** @return number of evictions performed due to cache being full. */
  195. public long getEvictions() {
  196. return statEvict;
  197. }
  198. private int hash(int packHash, long off) {
  199. return packHash + (int) (off >>> blockSizeShift);
  200. }
  201. int getBlockSize() {
  202. return blockSize;
  203. }
  204. private static int tableSize(final DfsBlockCacheConfig cfg) {
  205. final int wsz = cfg.getBlockSize();
  206. final long limit = cfg.getBlockLimit();
  207. if (wsz <= 0)
  208. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  209. if (limit < wsz)
  210. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  211. return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE);
  212. }
  213. /**
  214. * Lookup a cached object, creating and loading it if it doesn't exist.
  215. *
  216. * @param file
  217. * the pack that "contains" the cached object.
  218. * @param position
  219. * offset within <code>pack</code> of the object.
  220. * @param ctx
  221. * current thread's reader.
  222. * @param fileChannel
  223. * optional channel to read {@code pack}.
  224. * @return the object reference.
  225. * @throws IOException
  226. * the reference was not in the cache and could not be loaded.
  227. */
  228. DfsBlock getOrLoad(BlockBasedFile file, long position, DfsReader ctx,
  229. @Nullable ReadableChannel fileChannel) throws IOException {
  230. final long requestedPosition = position;
  231. position = file.alignToBlock(position);
  232. DfsStreamKey key = file.key;
  233. int slot = slot(key, position);
  234. HashEntry e1 = table.get(slot);
  235. DfsBlock v = scan(e1, key, position);
  236. if (v != null) {
  237. ctx.stats.blockCacheHit++;
  238. statHit.incrementAndGet();
  239. return v;
  240. }
  241. reserveSpace(blockSize);
  242. ReentrantLock regionLock = lockFor(key, position);
  243. regionLock.lock();
  244. try {
  245. HashEntry e2 = table.get(slot);
  246. if (e2 != e1) {
  247. v = scan(e2, key, position);
  248. if (v != null) {
  249. ctx.stats.blockCacheHit++;
  250. statHit.incrementAndGet();
  251. creditSpace(blockSize);
  252. return v;
  253. }
  254. }
  255. statMiss.incrementAndGet();
  256. boolean credit = true;
  257. try {
  258. v = file.readOneBlock(position, ctx, fileChannel);
  259. credit = false;
  260. } finally {
  261. if (credit)
  262. creditSpace(blockSize);
  263. }
  264. if (position != v.start) {
  265. // The file discovered its blockSize and adjusted.
  266. position = v.start;
  267. slot = slot(key, position);
  268. e2 = table.get(slot);
  269. }
  270. Ref<DfsBlock> ref = new Ref<>(key, position, v.size(), v);
  271. ref.hot = true;
  272. for (;;) {
  273. HashEntry n = new HashEntry(clean(e2), ref);
  274. if (table.compareAndSet(slot, e2, n))
  275. break;
  276. e2 = table.get(slot);
  277. }
  278. addToClock(ref, blockSize - v.size());
  279. } finally {
  280. regionLock.unlock();
  281. }
  282. // If the block size changed from the default, it is possible the block
  283. // that was loaded is the wrong block for the requested position.
  284. if (v.contains(file.key, requestedPosition))
  285. return v;
  286. return getOrLoad(file, requestedPosition, ctx, fileChannel);
  287. }
  288. @SuppressWarnings("unchecked")
  289. private void reserveSpace(int reserve) {
  290. clockLock.lock();
  291. try {
  292. long live = liveBytes + reserve;
  293. if (maxBytes < live) {
  294. Ref prev = clockHand;
  295. Ref hand = clockHand.next;
  296. do {
  297. if (hand.hot) {
  298. // Value was recently touched. Clear
  299. // hot and give it another chance.
  300. hand.hot = false;
  301. prev = hand;
  302. hand = hand.next;
  303. continue;
  304. } else if (prev == hand)
  305. break;
  306. // No recent access since last scan, kill
  307. // value and remove from clock.
  308. Ref dead = hand;
  309. hand = hand.next;
  310. prev.next = hand;
  311. dead.next = null;
  312. dead.value = null;
  313. live -= dead.size;
  314. statEvict++;
  315. } while (maxBytes < live);
  316. clockHand = prev;
  317. }
  318. liveBytes = live;
  319. } finally {
  320. clockLock.unlock();
  321. }
  322. }
  323. private void creditSpace(int credit) {
  324. clockLock.lock();
  325. liveBytes -= credit;
  326. clockLock.unlock();
  327. }
  328. @SuppressWarnings("unchecked")
  329. private void addToClock(Ref ref, int credit) {
  330. clockLock.lock();
  331. try {
  332. if (credit != 0)
  333. liveBytes -= credit;
  334. Ref ptr = clockHand;
  335. ref.next = ptr.next;
  336. ptr.next = ref;
  337. clockHand = ref;
  338. } finally {
  339. clockLock.unlock();
  340. }
  341. }
  342. void put(DfsBlock v) {
  343. put(v.stream, v.start, v.size(), v);
  344. }
  345. <T> Ref<T> putRef(DfsStreamKey key, long size, T v) {
  346. return put(key, 0, (int) Math.min(size, Integer.MAX_VALUE), v);
  347. }
  348. <T> Ref<T> put(DfsStreamKey key, long pos, int size, T v) {
  349. int slot = slot(key, pos);
  350. HashEntry e1 = table.get(slot);
  351. Ref<T> ref = scanRef(e1, key, pos);
  352. if (ref != null)
  353. return ref;
  354. reserveSpace(size);
  355. ReentrantLock regionLock = lockFor(key, pos);
  356. regionLock.lock();
  357. try {
  358. HashEntry e2 = table.get(slot);
  359. if (e2 != e1) {
  360. ref = scanRef(e2, key, pos);
  361. if (ref != null) {
  362. creditSpace(size);
  363. return ref;
  364. }
  365. }
  366. ref = new Ref<>(key, pos, size, v);
  367. ref.hot = true;
  368. for (;;) {
  369. HashEntry n = new HashEntry(clean(e2), ref);
  370. if (table.compareAndSet(slot, e2, n))
  371. break;
  372. e2 = table.get(slot);
  373. }
  374. addToClock(ref, 0);
  375. } finally {
  376. regionLock.unlock();
  377. }
  378. return ref;
  379. }
  380. boolean contains(DfsStreamKey key, long position) {
  381. return scan(table.get(slot(key, position)), key, position) != null;
  382. }
  383. @SuppressWarnings("unchecked")
  384. <T> T get(DfsStreamKey key, long position) {
  385. T val = (T) scan(table.get(slot(key, position)), key, position);
  386. if (val == null)
  387. statMiss.incrementAndGet();
  388. else
  389. statHit.incrementAndGet();
  390. return val;
  391. }
  392. private <T> T scan(HashEntry n, DfsStreamKey key, long position) {
  393. Ref<T> r = scanRef(n, key, position);
  394. return r != null ? r.get() : null;
  395. }
  396. <T> Ref<T> getRef(DfsStreamKey key) {
  397. Ref<T> r = scanRef(table.get(slot(key, 0)), key, 0);
  398. if (r != null)
  399. statHit.incrementAndGet();
  400. else
  401. statMiss.incrementAndGet();
  402. return r;
  403. }
  404. @SuppressWarnings("unchecked")
  405. private <T> Ref<T> scanRef(HashEntry n, DfsStreamKey key, long position) {
  406. for (; n != null; n = n.next) {
  407. Ref<T> r = n.ref;
  408. if (r.position == position && r.key.equals(key))
  409. return r.get() != null ? r : null;
  410. }
  411. return null;
  412. }
  413. private int slot(DfsStreamKey key, long position) {
  414. return (hash(key.hash, position) >>> 1) % tableSize;
  415. }
  416. private ReentrantLock lockFor(DfsStreamKey key, long position) {
  417. return loadLocks[(hash(key.hash, position) >>> 1) % loadLocks.length];
  418. }
  419. private static HashEntry clean(HashEntry top) {
  420. while (top != null && top.ref.next == null)
  421. top = top.next;
  422. if (top == null)
  423. return null;
  424. HashEntry n = clean(top.next);
  425. return n == top.next ? top : new HashEntry(n, top.ref);
  426. }
  427. private static final class HashEntry {
  428. /** Next entry in the hash table's chain list. */
  429. final HashEntry next;
  430. /** The referenced object. */
  431. final Ref ref;
  432. HashEntry(HashEntry n, Ref r) {
  433. next = n;
  434. ref = r;
  435. }
  436. }
  437. static final class Ref<T> {
  438. final DfsStreamKey key;
  439. final long position;
  440. final int size;
  441. volatile T value;
  442. Ref next;
  443. volatile boolean hot;
  444. Ref(DfsStreamKey key, long position, int size, T v) {
  445. this.key = key;
  446. this.position = position;
  447. this.size = size;
  448. this.value = v;
  449. }
  450. T get() {
  451. T v = value;
  452. if (v != null)
  453. hot = true;
  454. return v;
  455. }
  456. boolean has() {
  457. return value != null;
  458. }
  459. }
  460. }