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

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