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.

WindowCache.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /*
  2. * Copyright (C) 2008-2009, 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.file;
  45. import java.io.IOException;
  46. import java.lang.ref.ReferenceQueue;
  47. import java.lang.ref.SoftReference;
  48. import java.util.Random;
  49. import java.util.concurrent.atomic.AtomicInteger;
  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. import org.eclipse.jgit.storage.file.WindowCacheConfig;
  55. /**
  56. * Caches slices of a {@link PackFile} in memory for faster read access.
  57. * <p>
  58. * The WindowCache serves as a Java based "buffer cache", loading segments of a
  59. * PackFile into the JVM heap prior to use. As JGit often wants to do reads of
  60. * only tiny slices of a file, the WindowCache tries to smooth out these tiny
  61. * reads into larger block-sized IO operations.
  62. * <p>
  63. * Whenever a cache miss occurs, {@link #load(PackFile, long)} is invoked by
  64. * exactly one thread for the given <code>(PackFile,position)</code> key tuple.
  65. * This is ensured by an array of locks, with the tuple hashed to a lock
  66. * instance.
  67. * <p>
  68. * During a miss, older entries are evicted from the cache so long as
  69. * {@link #isFull()} returns true.
  70. * <p>
  71. * Its too expensive during object access to be 100% accurate with a least
  72. * recently used (LRU) algorithm. Strictly ordering every read is a lot of
  73. * overhead that typically doesn't yield a corresponding benefit to the
  74. * application.
  75. * <p>
  76. * This cache implements a loose LRU policy by randomly picking a window
  77. * comprised of roughly 10% of the cache, and evicting the oldest accessed entry
  78. * within that window.
  79. * <p>
  80. * Entities created by the cache are held under SoftReferences, permitting the
  81. * Java runtime's garbage collector to evict entries when heap memory gets low.
  82. * Most JREs implement a loose least recently used algorithm for this eviction.
  83. * <p>
  84. * The internal hash table does not expand at runtime, instead it is fixed in
  85. * size at cache creation time. The internal lock table used to gate load
  86. * invocations is also fixed in size.
  87. * <p>
  88. * The key tuple is passed through to methods as a pair of parameters rather
  89. * than as a single Object, thus reducing the transient memory allocations of
  90. * callers. It is more efficient to avoid the allocation, as we can't be 100%
  91. * sure that a JIT would be able to stack-allocate a key tuple.
  92. * <p>
  93. * This cache has an implementation rule such that:
  94. * <ul>
  95. * <li>{@link #load(PackFile, long)} is invoked by at most one thread at a time
  96. * for a given <code>(PackFile,position)</code> tuple.</li>
  97. * <li>For every <code>load()</code> invocation there is exactly one
  98. * {@link #createRef(PackFile, long, ByteWindow)} invocation to wrap a
  99. * SoftReference around the cached entity.</li>
  100. * <li>For every Reference created by <code>createRef()</code> there will be
  101. * exactly one call to {@link #clear(Ref)} to cleanup any resources associated
  102. * with the (now expired) cached entity.</li>
  103. * </ul>
  104. * <p>
  105. * Therefore, it is safe to perform resource accounting increments during the
  106. * {@link #load(PackFile, long)} or
  107. * {@link #createRef(PackFile, long, ByteWindow)} methods, and matching
  108. * decrements during {@link #clear(Ref)}. Implementors may need to override
  109. * {@link #createRef(PackFile, long, ByteWindow)} in order to embed additional
  110. * accounting information into an implementation specific {@link Ref} subclass,
  111. * as the cached entity may have already been evicted by the JRE's garbage
  112. * collector.
  113. * <p>
  114. * To maintain higher concurrency workloads, during eviction only one thread
  115. * performs the eviction work, while other threads can continue to insert new
  116. * objects in parallel. This means that the cache can be temporarily over limit,
  117. * especially if the nominated eviction thread is being starved relative to the
  118. * other threads.
  119. */
  120. public class WindowCache {
  121. private static final int bits(int newSize) {
  122. if (newSize < 4096)
  123. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  124. if (Integer.bitCount(newSize) != 1)
  125. throw new IllegalArgumentException(JGitText.get().windowSizeMustBePowerOf2);
  126. return Integer.numberOfTrailingZeros(newSize);
  127. }
  128. private static final Random rng = new Random();
  129. private static volatile WindowCache cache;
  130. private static volatile int streamFileThreshold;
  131. static {
  132. reconfigure(new WindowCacheConfig());
  133. }
  134. /**
  135. * Modify the configuration of the window cache.
  136. * <p>
  137. * The new configuration is applied immediately. If the new limits are
  138. * smaller than what what is currently cached, older entries will be purged
  139. * as soon as possible to allow the cache to meet the new limit.
  140. *
  141. * @deprecated use {@code cfg.install()} to avoid internal reference.
  142. * @param cfg
  143. * the new window cache configuration.
  144. * @throws IllegalArgumentException
  145. * the cache configuration contains one or more invalid
  146. * settings, usually too low of a limit.
  147. */
  148. @Deprecated
  149. public static void reconfigure(final WindowCacheConfig cfg) {
  150. final WindowCache nc = new WindowCache(cfg);
  151. final WindowCache oc = cache;
  152. if (oc != null)
  153. oc.removeAll();
  154. cache = nc;
  155. streamFileThreshold = cfg.getStreamFileThreshold();
  156. DeltaBaseCache.reconfigure(cfg);
  157. }
  158. static int getStreamFileThreshold() {
  159. return streamFileThreshold;
  160. }
  161. static WindowCache getInstance() {
  162. return cache;
  163. }
  164. static final ByteWindow get(final PackFile pack, final long offset)
  165. throws IOException {
  166. final WindowCache c = cache;
  167. final ByteWindow r = c.getOrLoad(pack, c.toStart(offset));
  168. if (c != cache) {
  169. // The cache was reconfigured while we were using the old one
  170. // to load this window. The window is still valid, but our
  171. // cache may think its still live. Ensure the window is removed
  172. // from the old cache so resources can be released.
  173. //
  174. c.removeAll();
  175. }
  176. return r;
  177. }
  178. static final void purge(final PackFile pack) {
  179. cache.removeAll(pack);
  180. }
  181. /** ReferenceQueue to cleanup released and garbage collected windows. */
  182. private final ReferenceQueue<ByteWindow> queue;
  183. /** Number of entries in {@link #table}. */
  184. private final int tableSize;
  185. /** Access clock for loose LRU. */
  186. private final AtomicLong clock;
  187. /** Hash bucket directory; entries are chained below. */
  188. private final AtomicReferenceArray<Entry> table;
  189. /** Locks to prevent concurrent loads for same (PackFile,position). */
  190. private final Lock[] locks;
  191. /** Lock to elect the eviction thread after a load occurs. */
  192. private final ReentrantLock evictLock;
  193. /** Number of {@link #table} buckets to scan for an eviction window. */
  194. private final int evictBatch;
  195. private final int maxFiles;
  196. private final long maxBytes;
  197. private final boolean mmap;
  198. private final int windowSizeShift;
  199. private final int windowSize;
  200. private final AtomicInteger openFiles;
  201. private final AtomicLong openBytes;
  202. private WindowCache(final WindowCacheConfig cfg) {
  203. tableSize = tableSize(cfg);
  204. final int lockCount = lockCount(cfg);
  205. if (tableSize < 1)
  206. throw new IllegalArgumentException(JGitText.get().tSizeMustBeGreaterOrEqual1);
  207. if (lockCount < 1)
  208. throw new IllegalArgumentException(JGitText.get().lockCountMustBeGreaterOrEqual1);
  209. queue = new ReferenceQueue<ByteWindow>();
  210. clock = new AtomicLong(1);
  211. table = new AtomicReferenceArray<Entry>(tableSize);
  212. locks = new Lock[lockCount];
  213. for (int i = 0; i < locks.length; i++)
  214. locks[i] = new Lock();
  215. evictLock = new ReentrantLock();
  216. int eb = (int) (tableSize * .1);
  217. if (64 < eb)
  218. eb = 64;
  219. else if (eb < 4)
  220. eb = 4;
  221. if (tableSize < eb)
  222. eb = tableSize;
  223. evictBatch = eb;
  224. maxFiles = cfg.getPackedGitOpenFiles();
  225. maxBytes = cfg.getPackedGitLimit();
  226. mmap = cfg.isPackedGitMMAP();
  227. windowSizeShift = bits(cfg.getPackedGitWindowSize());
  228. windowSize = 1 << windowSizeShift;
  229. openFiles = new AtomicInteger();
  230. openBytes = new AtomicLong();
  231. if (maxFiles < 1)
  232. throw new IllegalArgumentException(JGitText.get().openFilesMustBeAtLeast1);
  233. if (maxBytes < windowSize)
  234. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  235. }
  236. int getOpenFiles() {
  237. return openFiles.get();
  238. }
  239. long getOpenBytes() {
  240. return openBytes.get();
  241. }
  242. private int hash(final int packHash, final long off) {
  243. return packHash + (int) (off >>> windowSizeShift);
  244. }
  245. private ByteWindow load(final PackFile pack, final long offset)
  246. throws IOException {
  247. if (pack.beginWindowCache())
  248. openFiles.incrementAndGet();
  249. try {
  250. if (mmap)
  251. return pack.mmap(offset, windowSize);
  252. return pack.read(offset, windowSize);
  253. } catch (IOException e) {
  254. close(pack);
  255. throw e;
  256. } catch (RuntimeException e) {
  257. close(pack);
  258. throw e;
  259. } catch (Error e) {
  260. close(pack);
  261. throw e;
  262. }
  263. }
  264. private Ref createRef(final PackFile p, final long o, final ByteWindow v) {
  265. final Ref ref = new Ref(p, o, v, queue);
  266. openBytes.addAndGet(ref.size);
  267. return ref;
  268. }
  269. private void clear(final Ref ref) {
  270. openBytes.addAndGet(-ref.size);
  271. close(ref.pack);
  272. }
  273. private void close(final PackFile pack) {
  274. if (pack.endWindowCache())
  275. openFiles.decrementAndGet();
  276. }
  277. private boolean isFull() {
  278. return maxFiles < openFiles.get() || maxBytes < openBytes.get();
  279. }
  280. private long toStart(final long offset) {
  281. return (offset >>> windowSizeShift) << windowSizeShift;
  282. }
  283. private static int tableSize(final WindowCacheConfig cfg) {
  284. final int wsz = cfg.getPackedGitWindowSize();
  285. final long limit = cfg.getPackedGitLimit();
  286. if (wsz <= 0)
  287. throw new IllegalArgumentException(JGitText.get().invalidWindowSize);
  288. if (limit < wsz)
  289. throw new IllegalArgumentException(JGitText.get().windowSizeMustBeLesserThanLimit);
  290. return (int) Math.min(5 * (limit / wsz) / 2, 2000000000);
  291. }
  292. private static int lockCount(final WindowCacheConfig cfg) {
  293. return Math.max(cfg.getPackedGitOpenFiles(), 32);
  294. }
  295. /**
  296. * Lookup a cached object, creating and loading it if it doesn't exist.
  297. *
  298. * @param pack
  299. * the pack that "contains" the cached object.
  300. * @param position
  301. * offset within <code>pack</code> of the object.
  302. * @return the object reference.
  303. * @throws IOException
  304. * the object reference was not in the cache and could not be
  305. * obtained by {@link #load(PackFile, long)}.
  306. */
  307. private ByteWindow getOrLoad(final PackFile pack, final long position)
  308. throws IOException {
  309. final int slot = slot(pack, position);
  310. final Entry e1 = table.get(slot);
  311. ByteWindow v = scan(e1, pack, position);
  312. if (v != null)
  313. return v;
  314. synchronized (lock(pack, position)) {
  315. Entry e2 = table.get(slot);
  316. if (e2 != e1) {
  317. v = scan(e2, pack, position);
  318. if (v != null)
  319. return v;
  320. }
  321. v = load(pack, position);
  322. final Ref ref = createRef(pack, position, v);
  323. hit(ref);
  324. for (;;) {
  325. final Entry n = new Entry(clean(e2), ref);
  326. if (table.compareAndSet(slot, e2, n))
  327. break;
  328. e2 = table.get(slot);
  329. }
  330. }
  331. if (evictLock.tryLock()) {
  332. try {
  333. gc();
  334. evict();
  335. } finally {
  336. evictLock.unlock();
  337. }
  338. }
  339. return v;
  340. }
  341. private ByteWindow scan(Entry n, final PackFile pack, final long position) {
  342. for (; n != null; n = n.next) {
  343. final Ref r = n.ref;
  344. if (r.pack == pack && r.position == position) {
  345. final ByteWindow v = r.get();
  346. if (v != null) {
  347. hit(r);
  348. return v;
  349. }
  350. n.kill();
  351. break;
  352. }
  353. }
  354. return null;
  355. }
  356. private void hit(final Ref r) {
  357. // We don't need to be 100% accurate here. Its sufficient that at least
  358. // one thread performs the increment. Any other concurrent access at
  359. // exactly the same time can simply use the same clock value.
  360. //
  361. // Consequently we attempt the set, but we don't try to recover should
  362. // it fail. This is why we don't use getAndIncrement() here.
  363. //
  364. final long c = clock.get();
  365. clock.compareAndSet(c, c + 1);
  366. r.lastAccess = c;
  367. }
  368. private void evict() {
  369. while (isFull()) {
  370. int ptr = rng.nextInt(tableSize);
  371. Entry old = null;
  372. int slot = 0;
  373. for (int b = evictBatch - 1; b >= 0; b--, ptr++) {
  374. if (tableSize <= ptr)
  375. ptr = 0;
  376. for (Entry e = table.get(ptr); e != null; e = e.next) {
  377. if (e.dead)
  378. continue;
  379. if (old == null || e.ref.lastAccess < old.ref.lastAccess) {
  380. old = e;
  381. slot = ptr;
  382. }
  383. }
  384. }
  385. if (old != null) {
  386. old.kill();
  387. gc();
  388. final Entry e1 = table.get(slot);
  389. table.compareAndSet(slot, e1, clean(e1));
  390. }
  391. }
  392. }
  393. /**
  394. * Clear every entry from the cache.
  395. * <p>
  396. * This is a last-ditch effort to clear out the cache, such as before it
  397. * gets replaced by another cache that is configured differently. This
  398. * method tries to force every cached entry through {@link #clear(Ref)} to
  399. * ensure that resources are correctly accounted for and cleaned up by the
  400. * subclass. A concurrent reader loading entries while this method is
  401. * running may cause resource accounting failures.
  402. */
  403. private void removeAll() {
  404. for (int s = 0; s < tableSize; s++) {
  405. Entry e1;
  406. do {
  407. e1 = table.get(s);
  408. for (Entry e = e1; e != null; e = e.next)
  409. e.kill();
  410. } while (!table.compareAndSet(s, e1, null));
  411. }
  412. gc();
  413. }
  414. /**
  415. * Clear all entries related to a single file.
  416. * <p>
  417. * Typically this method is invoked during {@link PackFile#close()}, when we
  418. * know the pack is never going to be useful to us again (for example, it no
  419. * longer exists on disk). A concurrent reader loading an entry from this
  420. * same pack may cause the pack to become stuck in the cache anyway.
  421. *
  422. * @param pack
  423. * the file to purge all entries of.
  424. */
  425. private void removeAll(final PackFile pack) {
  426. for (int s = 0; s < tableSize; s++) {
  427. final Entry e1 = table.get(s);
  428. boolean hasDead = false;
  429. for (Entry e = e1; e != null; e = e.next) {
  430. if (e.ref.pack == pack) {
  431. e.kill();
  432. hasDead = true;
  433. } else if (e.dead)
  434. hasDead = true;
  435. }
  436. if (hasDead)
  437. table.compareAndSet(s, e1, clean(e1));
  438. }
  439. gc();
  440. }
  441. private void gc() {
  442. Ref r;
  443. while ((r = (Ref) queue.poll()) != null) {
  444. // Sun's Java 5 and 6 implementation have a bug where a Reference
  445. // can be enqueued and dequeued twice on the same reference queue
  446. // due to a race condition within ReferenceQueue.enqueue(Reference).
  447. //
  448. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6837858
  449. //
  450. // We CANNOT permit a Reference to come through us twice, as it will
  451. // skew the resource counters we maintain. Our canClear() check here
  452. // provides a way to skip the redundant dequeues, if any.
  453. //
  454. if (r.canClear()) {
  455. clear(r);
  456. boolean found = false;
  457. final int s = slot(r.pack, r.position);
  458. final Entry e1 = table.get(s);
  459. for (Entry n = e1; n != null; n = n.next) {
  460. if (n.ref == r) {
  461. n.dead = true;
  462. found = true;
  463. break;
  464. }
  465. }
  466. if (found)
  467. table.compareAndSet(s, e1, clean(e1));
  468. }
  469. }
  470. }
  471. private int slot(final PackFile pack, final long position) {
  472. return (hash(pack.hash, position) >>> 1) % tableSize;
  473. }
  474. private Lock lock(final PackFile pack, final long position) {
  475. return locks[(hash(pack.hash, position) >>> 1) % locks.length];
  476. }
  477. private static Entry clean(Entry top) {
  478. while (top != null && top.dead) {
  479. top.ref.enqueue();
  480. top = top.next;
  481. }
  482. if (top == null)
  483. return null;
  484. final Entry n = clean(top.next);
  485. return n == top.next ? top : new Entry(n, top.ref);
  486. }
  487. private static class Entry {
  488. /** Next entry in the hash table's chain list. */
  489. final Entry next;
  490. /** The referenced object. */
  491. final Ref ref;
  492. /**
  493. * Marked true when ref.get() returns null and the ref is dead.
  494. * <p>
  495. * A true here indicates that the ref is no longer accessible, and that
  496. * we therefore need to eventually purge this Entry object out of the
  497. * bucket's chain.
  498. */
  499. volatile boolean dead;
  500. Entry(final Entry n, final Ref r) {
  501. next = n;
  502. ref = r;
  503. }
  504. final void kill() {
  505. dead = true;
  506. ref.enqueue();
  507. }
  508. }
  509. /** A soft reference wrapped around a cached object. */
  510. private static class Ref extends SoftReference<ByteWindow> {
  511. final PackFile pack;
  512. final long position;
  513. final int size;
  514. long lastAccess;
  515. private boolean cleared;
  516. protected Ref(final PackFile pack, final long position,
  517. final ByteWindow v, final ReferenceQueue<ByteWindow> queue) {
  518. super(v, queue);
  519. this.pack = pack;
  520. this.position = position;
  521. this.size = v.size();
  522. }
  523. final synchronized boolean canClear() {
  524. if (cleared)
  525. return false;
  526. cleared = true;
  527. return true;
  528. }
  529. }
  530. private static final class Lock {
  531. // Used only for its implicit monitor.
  532. }
  533. }