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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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.Collection;
  47. import java.util.Collections;
  48. import java.util.Map;
  49. import java.util.concurrent.ConcurrentHashMap;
  50. import java.util.concurrent.atomic.AtomicLong;
  51. import java.util.concurrent.atomic.AtomicReferenceArray;
  52. import java.util.concurrent.locks.ReentrantLock;
  53. import org.eclipse.jgit.internal.JGitText;
  54. /**
  55. * Caches slices of a {@link DfsPackFile} in memory for faster read access.
  56. * <p>
  57. * The DfsBlockCache serves as a Java based "buffer cache", loading segments of
  58. * a DfsPackFile into the JVM heap prior to use. As JGit often wants to do reads
  59. * of only tiny slices of a file, the DfsBlockCache tries to smooth out these
  60. * tiny reads into larger block-sized IO operations.
  61. * <p>
  62. * Whenever a cache miss occurs, loading is invoked by exactly one thread for
  63. * the given <code>(DfsPackKey,position)</code> key tuple. This is ensured by an
  64. * array of locks, with the tuple hashed to a lock instance.
  65. * <p>
  66. * Its too expensive during object access to be accurate with a least recently
  67. * used (LRU) algorithm. Strictly ordering every read is a lot of overhead that
  68. * typically doesn't yield a corresponding benefit to the application. This
  69. * cache implements a clock replacement algorithm, giving each block one chance
  70. * to have been accessed during a sweep of the cache to save itself from
  71. * eviction.
  72. * <p>
  73. * Entities created by the cache are held under hard references, preventing the
  74. * Java VM from clearing anything. Blocks are discarded by the replacement
  75. * algorithm when adding a new block would cause the cache to exceed its
  76. * configured maximum size.
  77. * <p>
  78. * The key tuple is passed through to methods as a pair of parameters rather
  79. * than as a single Object, thus reducing the transient memory allocations of
  80. * callers. It is more efficient to avoid the allocation, as we can't be 100%
  81. * sure that a JIT would be able to stack-allocate a key tuple.
  82. * <p>
  83. * The internal hash table does not expand at runtime, instead it is fixed in
  84. * size at cache creation time. The internal lock table used to gate load
  85. * invocations is also fixed in size.
  86. */
  87. public final class DfsBlockCache {
  88. private static volatile DfsBlockCache cache;
  89. static {
  90. reconfigure(new DfsBlockCacheConfig());
  91. }
  92. /**
  93. * Modify the configuration of the window cache.
  94. * <p>
  95. * The new configuration is applied immediately, and the existing cache is
  96. * cleared.
  97. *
  98. * @param cfg
  99. * the new window cache configuration.
  100. * @throws IllegalArgumentException
  101. * the cache configuration contains one or more invalid
  102. * settings, usually too low of a limit.
  103. */
  104. public static void reconfigure(DfsBlockCacheConfig cfg) {
  105. DfsBlockCache nc = new DfsBlockCache(cfg);
  106. DfsBlockCache oc = cache;
  107. cache = nc;
  108. if (oc != null) {
  109. for (DfsPackFile pack : oc.getPackFiles())
  110. pack.key.cachedSize.set(0);
  111. }
  112. }
  113. /** @return the currently active DfsBlockCache. */
  114. public static DfsBlockCache getInstance() {
  115. return cache;
  116. }
  117. /** Number of entries in {@link #table}. */
  118. private final int tableSize;
  119. /** Hash bucket directory; entries are chained below. */
  120. private final AtomicReferenceArray<HashEntry> table;
  121. /** Locks to prevent concurrent loads for same (PackFile,position). */
  122. private final ReentrantLock[] loadLocks;
  123. /** Maximum number of bytes the cache should hold. */
  124. private final long maxBytes;
  125. /**
  126. * Suggested block size to read from pack files in.
  127. * <p>
  128. * If a pack file does not have a native block size, this size will be used.
  129. * <p>
  130. * If a pack file has a native size, a whole multiple of the native size
  131. * will be used until it matches this size.
  132. */
  133. private final int blockSize;
  134. /** As {@link #blockSize} is a power of 2, bits to shift for a / blockSize. */
  135. private final int blockSizeShift;
  136. /** Cache of pack files, indexed by description. */
  137. private final Map<DfsPackDescription, DfsPackFile> packCache;
  138. /** View of pack files in the pack cache. */
  139. private final Collection<DfsPackFile> packFiles;
  140. /** Number of times a block was found in the cache. */
  141. private final AtomicLong statHit;
  142. /** Number of times a block was not found, and had to be loaded. */
  143. private final AtomicLong statMiss;
  144. /** Number of blocks evicted due to cache being full. */
  145. private volatile long statEvict;
  146. /** Protects the clock and its related data. */
  147. private final ReentrantLock clockLock;
  148. /** Current position of the clock. */
  149. private Ref clockHand;
  150. /** Number of bytes currently loaded in the cache. */
  151. private volatile long liveBytes;
  152. private DfsBlockCache(final DfsBlockCacheConfig cfg) {
  153. tableSize = tableSize(cfg);
  154. if (tableSize < 1)
  155. throw new IllegalArgumentException(JGitText.get().tSizeMustBeGreaterOrEqual1);
  156. table = new AtomicReferenceArray<HashEntry>(tableSize);
  157. loadLocks = new ReentrantLock[32];
  158. for (int i = 0; i < loadLocks.length; i++)
  159. loadLocks[i] = new ReentrantLock(true /* fair */);
  160. int eb = (int) (tableSize * .1);
  161. if (64 < eb)
  162. eb = 64;
  163. else if (eb < 4)
  164. eb = 4;
  165. if (tableSize < eb)
  166. eb = tableSize;
  167. maxBytes = cfg.getBlockLimit();
  168. blockSize = cfg.getBlockSize();
  169. blockSizeShift = Integer.numberOfTrailingZeros(blockSize);
  170. clockLock = new ReentrantLock(true /* fair */);
  171. clockHand = new Ref<Object>(new DfsPackKey(), -1, 0, null);
  172. clockHand.next = clockHand;
  173. packCache = new ConcurrentHashMap<DfsPackDescription, DfsPackFile>(
  174. 16, 0.75f, 1);
  175. packFiles = Collections.unmodifiableCollection(packCache.values());
  176. statHit = new AtomicLong();
  177. statMiss = new AtomicLong();
  178. }
  179. /** @return total number of bytes in the cache. */
  180. public long getCurrentSize() {
  181. return liveBytes;
  182. }
  183. /** @return 0..100, defining how full the cache is. */
  184. public long getFillPercentage() {
  185. return getCurrentSize() * 100 / maxBytes;
  186. }
  187. /** @return number of requests for items in the cache. */
  188. public long getHitCount() {
  189. return statHit.get();
  190. }
  191. /** @return number of requests for items not in the cache. */
  192. public long getMissCount() {
  193. return statMiss.get();
  194. }
  195. /** @return total number of requests (hit + miss). */
  196. public long getTotalRequestCount() {
  197. return getHitCount() + getMissCount();
  198. }
  199. /** @return 0..100, defining number of cache hits. */
  200. public long getHitRatio() {
  201. long hits = statHit.get();
  202. long miss = statMiss.get();
  203. long total = hits + miss;
  204. if (total == 0)
  205. return 0;
  206. return hits * 100 / total;
  207. }
  208. /** @return number of evictions performed due to cache being full. */
  209. public long getEvictions() {
  210. return statEvict;
  211. }
  212. /**
  213. * Get the pack files stored in this cache.
  214. *
  215. * @return a collection of pack files, some of which may not actually be
  216. * present; the caller should check the pack's cached size.
  217. */
  218. public Collection<DfsPackFile> getPackFiles() {
  219. return packFiles;
  220. }
  221. DfsPackFile getOrCreate(DfsPackDescription dsc, DfsPackKey key) {
  222. // TODO This table grows without bound. It needs to clean up
  223. // entries that aren't in cache anymore, and aren't being used
  224. // by a live DfsObjDatabase reference.
  225. synchronized (packCache) {
  226. DfsPackFile pack = packCache.get(dsc);
  227. if (pack != null && pack.invalid()) {
  228. packCache.remove(dsc);
  229. pack = null;
  230. }
  231. if (pack == null) {
  232. if (key == null)
  233. key = new DfsPackKey();
  234. pack = new DfsPackFile(this, dsc, key);
  235. packCache.put(dsc, pack);
  236. }
  237. return pack;
  238. }
  239. }
  240. private int hash(int packHash, long off) {
  241. return packHash + (int) (off >>> blockSizeShift);
  242. }
  243. int getBlockSize() {
  244. return blockSize;
  245. }
  246. private static int tableSize(final DfsBlockCacheConfig cfg) {
  247. final int wsz = cfg.getBlockSize();
  248. final long limit = cfg.getBlockLimit();
  249. if (wsz <= 0)
  250. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  251. if (limit < wsz)
  252. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  253. return (int) Math.min(5 * (limit / wsz) / 2, Integer.MAX_VALUE);
  254. }
  255. /**
  256. * Lookup a cached object, creating and loading it if it doesn't exist.
  257. *
  258. * @param pack
  259. * the pack that "contains" the cached object.
  260. * @param position
  261. * offset within <code>pack</code> of the object.
  262. * @param ctx
  263. * current thread's reader.
  264. * @return the object reference.
  265. * @throws IOException
  266. * the reference was not in the cache and could not be loaded.
  267. */
  268. DfsBlock getOrLoad(DfsPackFile pack, long position, DfsReader ctx)
  269. throws IOException {
  270. final long requestedPosition = position;
  271. position = pack.alignToBlock(position);
  272. DfsPackKey key = pack.key;
  273. int slot = slot(key, position);
  274. HashEntry e1 = table.get(slot);
  275. DfsBlock v = scan(e1, key, position);
  276. if (v != null) {
  277. statHit.incrementAndGet();
  278. return v;
  279. }
  280. reserveSpace(blockSize);
  281. ReentrantLock regionLock = lockFor(key, position);
  282. regionLock.lock();
  283. try {
  284. HashEntry e2 = table.get(slot);
  285. if (e2 != e1) {
  286. v = scan(e2, key, position);
  287. if (v != null) {
  288. statHit.incrementAndGet();
  289. creditSpace(blockSize);
  290. return v;
  291. }
  292. }
  293. statMiss.incrementAndGet();
  294. boolean credit = true;
  295. try {
  296. v = pack.readOneBlock(position, ctx);
  297. credit = false;
  298. } finally {
  299. if (credit)
  300. creditSpace(blockSize);
  301. }
  302. if (position != v.start) {
  303. // The file discovered its blockSize and adjusted.
  304. position = v.start;
  305. slot = slot(key, position);
  306. e2 = table.get(slot);
  307. }
  308. key.cachedSize.addAndGet(v.size());
  309. Ref<DfsBlock> ref = new Ref<DfsBlock>(key, position, v.size(), v);
  310. ref.hot = true;
  311. for (;;) {
  312. HashEntry n = new HashEntry(clean(e2), ref);
  313. if (table.compareAndSet(slot, e2, n))
  314. break;
  315. e2 = table.get(slot);
  316. }
  317. addToClock(ref, blockSize - v.size());
  318. } finally {
  319. regionLock.unlock();
  320. }
  321. // If the block size changed from the default, it is possible the block
  322. // that was loaded is the wrong block for the requested position.
  323. if (v.contains(pack.key, requestedPosition))
  324. return v;
  325. return getOrLoad(pack, requestedPosition, ctx);
  326. }
  327. @SuppressWarnings("unchecked")
  328. private void reserveSpace(int reserve) {
  329. clockLock.lock();
  330. try {
  331. long live = liveBytes + reserve;
  332. if (maxBytes < live) {
  333. Ref prev = clockHand;
  334. Ref hand = clockHand.next;
  335. do {
  336. if (hand.hot) {
  337. // Value was recently touched. Clear
  338. // hot and give it another chance.
  339. hand.hot = false;
  340. prev = hand;
  341. hand = hand.next;
  342. continue;
  343. } else if (prev == hand)
  344. break;
  345. // No recent access since last scan, kill
  346. // value and remove from clock.
  347. Ref dead = hand;
  348. hand = hand.next;
  349. prev.next = hand;
  350. dead.next = null;
  351. dead.value = null;
  352. live -= dead.size;
  353. dead.pack.cachedSize.addAndGet(-dead.size);
  354. statEvict++;
  355. } while (maxBytes < live);
  356. clockHand = prev;
  357. }
  358. liveBytes = live;
  359. } finally {
  360. clockLock.unlock();
  361. }
  362. }
  363. private void creditSpace(int credit) {
  364. clockLock.lock();
  365. liveBytes -= credit;
  366. clockLock.unlock();
  367. }
  368. private void addToClock(Ref ref, int credit) {
  369. clockLock.lock();
  370. try {
  371. if (credit != 0)
  372. liveBytes -= credit;
  373. Ref ptr = clockHand;
  374. ref.next = ptr.next;
  375. ptr.next = ref;
  376. clockHand = ref;
  377. } finally {
  378. clockLock.unlock();
  379. }
  380. }
  381. void put(DfsBlock v) {
  382. put(v.pack, v.start, v.size(), v);
  383. }
  384. <T> Ref<T> put(DfsPackKey key, long pos, int size, T v) {
  385. int slot = slot(key, pos);
  386. HashEntry e1 = table.get(slot);
  387. Ref<T> ref = scanRef(e1, key, pos);
  388. if (ref != null)
  389. return ref;
  390. reserveSpace(size);
  391. ReentrantLock regionLock = lockFor(key, pos);
  392. regionLock.lock();
  393. try {
  394. HashEntry e2 = table.get(slot);
  395. if (e2 != e1) {
  396. ref = scanRef(e2, key, pos);
  397. if (ref != null) {
  398. creditSpace(size);
  399. return ref;
  400. }
  401. }
  402. key.cachedSize.addAndGet(size);
  403. ref = new Ref<T>(key, pos, size, v);
  404. ref.hot = true;
  405. for (;;) {
  406. HashEntry n = new HashEntry(clean(e2), ref);
  407. if (table.compareAndSet(slot, e2, n))
  408. break;
  409. e2 = table.get(slot);
  410. }
  411. addToClock(ref, 0);
  412. } finally {
  413. regionLock.unlock();
  414. }
  415. return ref;
  416. }
  417. boolean contains(DfsPackKey key, long position) {
  418. return scan(table.get(slot(key, position)), key, position) != null;
  419. }
  420. @SuppressWarnings("unchecked")
  421. <T> T get(DfsPackKey key, long position) {
  422. T val = (T) scan(table.get(slot(key, position)), key, position);
  423. if (val == null)
  424. statMiss.incrementAndGet();
  425. else
  426. statHit.incrementAndGet();
  427. return val;
  428. }
  429. private <T> T scan(HashEntry n, DfsPackKey pack, long position) {
  430. Ref<T> r = scanRef(n, pack, position);
  431. return r != null ? r.get() : null;
  432. }
  433. @SuppressWarnings("unchecked")
  434. private <T> Ref<T> scanRef(HashEntry n, DfsPackKey pack, long position) {
  435. for (; n != null; n = n.next) {
  436. Ref<T> r = n.ref;
  437. if (r.pack == pack && r.position == position)
  438. return r.get() != null ? r : null;
  439. }
  440. return null;
  441. }
  442. void remove(DfsPackFile pack) {
  443. synchronized (packCache) {
  444. packCache.remove(pack.getPackDescription());
  445. }
  446. }
  447. private int slot(DfsPackKey pack, long position) {
  448. return (hash(pack.hash, position) >>> 1) % tableSize;
  449. }
  450. private ReentrantLock lockFor(DfsPackKey pack, long position) {
  451. return loadLocks[(hash(pack.hash, position) >>> 1) % loadLocks.length];
  452. }
  453. private static HashEntry clean(HashEntry top) {
  454. while (top != null && top.ref.next == null)
  455. top = top.next;
  456. if (top == null)
  457. return null;
  458. HashEntry n = clean(top.next);
  459. return n == top.next ? top : new HashEntry(n, top.ref);
  460. }
  461. private static final class HashEntry {
  462. /** Next entry in the hash table's chain list. */
  463. final HashEntry next;
  464. /** The referenced object. */
  465. final Ref ref;
  466. HashEntry(HashEntry n, Ref r) {
  467. next = n;
  468. ref = r;
  469. }
  470. }
  471. static final class Ref<T> {
  472. final DfsPackKey pack;
  473. final long position;
  474. final int size;
  475. volatile T value;
  476. Ref next;
  477. volatile boolean hot;
  478. Ref(DfsPackKey pack, long position, int size, T v) {
  479. this.pack = pack;
  480. this.position = position;
  481. this.size = size;
  482. this.value = v;
  483. }
  484. T get() {
  485. T v = value;
  486. if (v != null)
  487. hot = true;
  488. return v;
  489. }
  490. boolean has() {
  491. return value != null;
  492. }
  493. }
  494. }