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.

UsageMap.java 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.nio.ByteBuffer;
  16. import java.util.ArrayList;
  17. import java.util.BitSet;
  18. import java.util.List;
  19. import com.healthmarketscience.jackcess.util.ToStringBuilder;
  20. /**
  21. * Describes which database pages a particular table uses
  22. * @author Tim McCune
  23. */
  24. public class UsageMap
  25. {
  26. /** Inline map type */
  27. public static final byte MAP_TYPE_INLINE = 0x0;
  28. /** Reference map type, for maps that are too large to fit inline */
  29. public static final byte MAP_TYPE_REFERENCE = 0x1;
  30. /** bit index value for an invalid page number */
  31. private static final int INVALID_BIT_INDEX = -1;
  32. /** owning database */
  33. private final DatabaseImpl _database;
  34. /** Page number of the map table declaration */
  35. private final int _tablePageNum;
  36. /** Offset of the data page at which the usage map data starts */
  37. private int _startOffset;
  38. /** Offset of the data page at which the usage map declaration starts */
  39. private final short _rowStart;
  40. /** First page that this usage map applies to */
  41. private int _startPage;
  42. /** Last page that this usage map applies to */
  43. private int _endPage;
  44. /** bits representing page numbers used, offset from _startPage */
  45. private BitSet _pageNumbers = new BitSet();
  46. /** Buffer that contains the usage map table declaration page */
  47. private final ByteBuffer _tableBuffer;
  48. /** modification count on the usage map, used to keep the cursors in
  49. sync */
  50. private int _modCount;
  51. /** the current handler implementation for reading/writing the specific
  52. usage map type. note, this may change over time. */
  53. private Handler _handler;
  54. /** Error message prefix used when map type is unrecognized. */
  55. static final String MSG_PREFIX_UNRECOGNIZED_MAP = "Unrecognized map type: ";
  56. /**
  57. * @param database database that contains this usage map
  58. * @param tableBuffer Buffer that contains this map's declaration
  59. * @param pageNum Page number that this usage map is contained in
  60. * @param rowStart Offset at which the declaration starts in the buffer
  61. */
  62. private UsageMap(DatabaseImpl database, ByteBuffer tableBuffer,
  63. int pageNum, short rowStart)
  64. throws IOException
  65. {
  66. _database = database;
  67. _tableBuffer = tableBuffer;
  68. _tablePageNum = pageNum;
  69. _rowStart = rowStart;
  70. _tableBuffer.position(_rowStart + getFormat().OFFSET_USAGE_MAP_START);
  71. _startOffset = _tableBuffer.position();
  72. }
  73. public DatabaseImpl getDatabase() {
  74. return _database;
  75. }
  76. public JetFormat getFormat() {
  77. return getDatabase().getFormat();
  78. }
  79. public PageChannel getPageChannel() {
  80. return getDatabase().getPageChannel();
  81. }
  82. /**
  83. * @param database database that contains this usage map
  84. * @param buf buffer which contains the usage map row info
  85. * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
  86. * which type of map is found
  87. */
  88. public static UsageMap read(DatabaseImpl database, ByteBuffer buf)
  89. throws IOException
  90. {
  91. int umapRowNum = buf.get();
  92. int umapPageNum = ByteUtil.get3ByteInt(buf);
  93. return read(database, umapPageNum, umapRowNum, false);
  94. }
  95. /**
  96. * @param database database that contains this usage map
  97. * @param pageNum Page number that this usage map is contained in
  98. * @param rowNum Number of the row on the page that contains this usage map
  99. * @param isGlobal whether or not we are reading the "global" usage map
  100. * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
  101. * which type of map is found
  102. */
  103. static UsageMap read(DatabaseImpl database, int pageNum,
  104. int rowNum, boolean isGlobal)
  105. throws IOException
  106. {
  107. if(pageNum <= 0) {
  108. // usage maps will never appear on page 0 (or less)
  109. throw new IllegalStateException("Invalid usage map page number " + pageNum);
  110. }
  111. JetFormat format = database.getFormat();
  112. PageChannel pageChannel = database.getPageChannel();
  113. ByteBuffer tableBuffer = pageChannel.createPageBuffer();
  114. pageChannel.readPage(tableBuffer, pageNum);
  115. short rowStart = TableImpl.findRowStart(tableBuffer, rowNum, format);
  116. int rowEnd = TableImpl.findRowEnd(tableBuffer, rowNum, format);
  117. tableBuffer.limit(rowEnd);
  118. byte mapType = tableBuffer.get(rowStart);
  119. UsageMap rtn = new UsageMap(database, tableBuffer, pageNum, rowStart);
  120. rtn.initHandler(mapType, isGlobal);
  121. return rtn;
  122. }
  123. private void initHandler(byte mapType, boolean isGlobal)
  124. throws IOException
  125. {
  126. if (mapType == MAP_TYPE_INLINE) {
  127. _handler = (isGlobal ? new GlobalInlineHandler() :
  128. new InlineHandler());
  129. } else if (mapType == MAP_TYPE_REFERENCE) {
  130. _handler = (isGlobal ? new GlobalReferenceHandler() :
  131. new ReferenceHandler());
  132. } else {
  133. throw new IOException(MSG_PREFIX_UNRECOGNIZED_MAP + mapType);
  134. }
  135. }
  136. public PageCursor cursor() {
  137. return new PageCursor();
  138. }
  139. public int getPageCount() {
  140. return _pageNumbers.cardinality();
  141. }
  142. protected short getRowStart() {
  143. return _rowStart;
  144. }
  145. protected int getRowEnd() {
  146. return getTableBuffer().limit();
  147. }
  148. protected void setStartOffset(int startOffset) {
  149. _startOffset = startOffset;
  150. }
  151. protected int getStartOffset() {
  152. return _startOffset;
  153. }
  154. protected ByteBuffer getTableBuffer() {
  155. return _tableBuffer;
  156. }
  157. protected int getTablePageNumber() {
  158. return _tablePageNum;
  159. }
  160. protected int getStartPage() {
  161. return _startPage;
  162. }
  163. protected int getEndPage() {
  164. return _endPage;
  165. }
  166. protected BitSet getPageNumbers() {
  167. return _pageNumbers;
  168. }
  169. protected void setPageRange(int newStartPage, int newEndPage) {
  170. _startPage = newStartPage;
  171. _endPage = newEndPage;
  172. }
  173. protected boolean isPageWithinRange(int pageNumber)
  174. {
  175. return((pageNumber >= _startPage) && (pageNumber < _endPage));
  176. }
  177. protected int getFirstPageNumber() {
  178. return bitIndexToPageNumber(getNextBitIndex(-1),
  179. RowIdImpl.LAST_PAGE_NUMBER);
  180. }
  181. protected int getNextPageNumber(int curPage) {
  182. return bitIndexToPageNumber(
  183. getNextBitIndex(pageNumberToBitIndex(curPage)),
  184. RowIdImpl.LAST_PAGE_NUMBER);
  185. }
  186. protected int getNextBitIndex(int curIndex) {
  187. return _pageNumbers.nextSetBit(curIndex + 1);
  188. }
  189. protected int getLastPageNumber() {
  190. return bitIndexToPageNumber(getPrevBitIndex(_pageNumbers.length()),
  191. RowIdImpl.FIRST_PAGE_NUMBER);
  192. }
  193. protected int getPrevPageNumber(int curPage) {
  194. return bitIndexToPageNumber(
  195. getPrevBitIndex(pageNumberToBitIndex(curPage)),
  196. RowIdImpl.FIRST_PAGE_NUMBER);
  197. }
  198. protected int getPrevBitIndex(int curIndex) {
  199. --curIndex;
  200. while((curIndex >= 0) && !_pageNumbers.get(curIndex)) {
  201. --curIndex;
  202. }
  203. return curIndex;
  204. }
  205. protected int bitIndexToPageNumber(int bitIndex,
  206. int invalidPageNumber) {
  207. return((bitIndex >= 0) ? (_startPage + bitIndex) : invalidPageNumber);
  208. }
  209. protected int pageNumberToBitIndex(int pageNumber) {
  210. return((pageNumber >= 0) ? (pageNumber - _startPage) :
  211. INVALID_BIT_INDEX);
  212. }
  213. protected void clearTableAndPages()
  214. {
  215. // reset some values
  216. _pageNumbers.clear();
  217. _startPage = 0;
  218. _endPage = 0;
  219. ++_modCount;
  220. // clear out the table data (everything except map type)
  221. int tableStart = getRowStart() + 1;
  222. int tableEnd = getRowEnd();
  223. ByteUtil.clearRange(_tableBuffer, tableStart, tableEnd);
  224. }
  225. protected void writeTable()
  226. throws IOException
  227. {
  228. // note, we only want to write the row data with which we are working
  229. getPageChannel().writePage(_tableBuffer, _tablePageNum, _rowStart);
  230. }
  231. /**
  232. * Read in the page numbers in this inline map
  233. */
  234. protected void processMap(ByteBuffer buffer, int bufferStartPage)
  235. {
  236. int byteCount = 0;
  237. while (buffer.hasRemaining()) {
  238. byte b = buffer.get();
  239. if(b != (byte)0) {
  240. for (int i = 0; i < 8; i++) {
  241. if ((b & (1 << i)) != 0) {
  242. int pageNumberOffset = (byteCount * 8 + i) + bufferStartPage;
  243. int pageNumber = bitIndexToPageNumber(
  244. pageNumberOffset,
  245. PageChannel.INVALID_PAGE_NUMBER);
  246. if(!isPageWithinRange(pageNumber)) {
  247. throw new IllegalStateException(
  248. "found page number " + pageNumber
  249. + " in usage map outside of expected range " +
  250. _startPage + " to " + _endPage);
  251. }
  252. _pageNumbers.set(pageNumberOffset);
  253. }
  254. }
  255. }
  256. byteCount++;
  257. }
  258. }
  259. /**
  260. * Determines if the given page number is contained in this map.
  261. */
  262. public boolean containsPageNumber(int pageNumber) {
  263. return _handler.containsPageNumber(pageNumber);
  264. }
  265. /**
  266. * Add a page number to this usage map
  267. */
  268. public void addPageNumber(int pageNumber) throws IOException {
  269. ++_modCount;
  270. _handler.addOrRemovePageNumber(pageNumber, true, false);
  271. }
  272. /**
  273. * Remove a page number from this usage map
  274. */
  275. public void removePageNumber(int pageNumber)
  276. throws IOException
  277. {
  278. removePageNumber(pageNumber, true);
  279. }
  280. private void removePageNumber(int pageNumber, boolean force)
  281. throws IOException
  282. {
  283. ++_modCount;
  284. _handler.addOrRemovePageNumber(pageNumber, false, force);
  285. }
  286. protected void updateMap(int absolutePageNumber,
  287. int bufferRelativePageNumber,
  288. ByteBuffer buffer, boolean add, boolean force)
  289. throws IOException
  290. {
  291. //Find the byte to which to apply the bitmask and create the bitmask
  292. int offset = bufferRelativePageNumber / 8;
  293. int bitmask = 1 << (bufferRelativePageNumber % 8);
  294. byte b = buffer.get(_startOffset + offset);
  295. // check current value for this page number
  296. int pageNumberOffset = pageNumberToBitIndex(absolutePageNumber);
  297. boolean isOn = _pageNumbers.get(pageNumberOffset);
  298. if((isOn == add) && !force) {
  299. throw new IOException("Page number " + absolutePageNumber + " already " +
  300. ((add) ? "added to" : "removed from") +
  301. " usage map, expected range " +
  302. _startPage + " to " + _endPage);
  303. }
  304. //Apply the bitmask
  305. if (add) {
  306. b |= bitmask;
  307. _pageNumbers.set(pageNumberOffset);
  308. } else {
  309. b &= ~bitmask;
  310. _pageNumbers.clear(pageNumberOffset);
  311. }
  312. buffer.put(_startOffset + offset, b);
  313. }
  314. /**
  315. * Promotes and inline usage map to a reference usage map.
  316. */
  317. private void promoteInlineHandlerToReferenceHandler(int newPageNumber)
  318. throws IOException
  319. {
  320. // copy current page number info to new references and then clear old
  321. int oldStartPage = _startPage;
  322. BitSet oldPageNumbers = (BitSet)_pageNumbers.clone();
  323. // clear out the main table (inline usage map data and start page)
  324. clearTableAndPages();
  325. // set the new map type
  326. _tableBuffer.put(getRowStart(), MAP_TYPE_REFERENCE);
  327. // write the new table data
  328. writeTable();
  329. // set new handler
  330. _handler = new ReferenceHandler();
  331. // update new handler with old data
  332. reAddPages(oldStartPage, oldPageNumbers, newPageNumber);
  333. }
  334. private void reAddPages(int oldStartPage, BitSet oldPageNumbers,
  335. int newPageNumber)
  336. throws IOException
  337. {
  338. // add all the old pages back in
  339. for(int i = oldPageNumbers.nextSetBit(0); i >= 0;
  340. i = oldPageNumbers.nextSetBit(i + 1)) {
  341. addPageNumber(oldStartPage + i);
  342. }
  343. if(newPageNumber > PageChannel.INVALID_PAGE_NUMBER) {
  344. // and then add the new page
  345. addPageNumber(newPageNumber);
  346. }
  347. }
  348. @Override
  349. public String toString() {
  350. List<String> ranges = new ArrayList<String>();
  351. PageCursor pCursor = cursor();
  352. int curRangeStart = Integer.MIN_VALUE;
  353. int prevPage = Integer.MIN_VALUE;
  354. while(true) {
  355. int nextPage = pCursor.getNextPage();
  356. if(nextPage < 0) {
  357. break;
  358. }
  359. if(nextPage != (prevPage + 1)) {
  360. if(prevPage >= 0) {
  361. rangeToString(ranges, curRangeStart, prevPage);
  362. }
  363. curRangeStart = nextPage;
  364. }
  365. prevPage = nextPage;
  366. }
  367. if(prevPage >= 0) {
  368. rangeToString(ranges, curRangeStart, prevPage);
  369. }
  370. return ToStringBuilder.valueBuilder(
  371. _handler.getClass().getSimpleName())
  372. .append("range", "(" + _startPage + "-" + _endPage + ")")
  373. .append("pageNumbers", ranges)
  374. .toString();
  375. }
  376. private static void rangeToString(List<String> ranges, int rangeStart,
  377. int rangeEnd)
  378. {
  379. if(rangeEnd > rangeStart) {
  380. ranges.add(rangeStart + "-" + rangeEnd);
  381. } else {
  382. ranges.add(String.valueOf(rangeStart));
  383. }
  384. }
  385. private static int toValidStartPage(int startPage) {
  386. // start page must be a multiple of 8
  387. return ((startPage / 8) * 8);
  388. }
  389. private abstract class Handler
  390. {
  391. protected Handler() {
  392. }
  393. public boolean containsPageNumber(int pageNumber) {
  394. return(isPageWithinRange(pageNumber) &&
  395. getPageNumbers().get(pageNumberToBitIndex(pageNumber)));
  396. }
  397. /**
  398. * @param pageNumber Page number to add or remove from this map
  399. * @param add True to add it, false to remove it
  400. * @param force true to force add/remove and ignore certain inconsistencies
  401. */
  402. public abstract void addOrRemovePageNumber(int pageNumber, boolean add,
  403. boolean force)
  404. throws IOException;
  405. }
  406. /**
  407. * Usage map whose map is written inline in the same page. For Jet4, this
  408. * type of map can usually contains a maximum of 512 pages. Free space maps
  409. * are always inline, used space maps may be inline or reference. It has a
  410. * start page, which all page numbers in its map are calculated as starting
  411. * from.
  412. * @author Tim McCune
  413. */
  414. private class InlineHandler extends Handler
  415. {
  416. private final int _maxInlinePages;
  417. protected InlineHandler() throws IOException
  418. {
  419. _maxInlinePages = (getInlineDataEnd() - getInlineDataStart()) * 8;
  420. int startPage = getTableBuffer().getInt(getRowStart() + 1);
  421. setInlinePageRange(startPage);
  422. processMap(getTableBuffer(), 0);
  423. }
  424. protected final int getMaxInlinePages() {
  425. return _maxInlinePages;
  426. }
  427. protected final int getInlineDataStart() {
  428. return getRowStart() + getFormat().OFFSET_USAGE_MAP_START;
  429. }
  430. protected final int getInlineDataEnd() {
  431. return getRowEnd();
  432. }
  433. /**
  434. * Sets the page range for an inline usage map starting from the given
  435. * page.
  436. */
  437. private void setInlinePageRange(int startPage) {
  438. setPageRange(startPage, startPage + getMaxInlinePages());
  439. }
  440. @Override
  441. public void addOrRemovePageNumber(int pageNumber, boolean add,
  442. boolean force)
  443. throws IOException
  444. {
  445. if(isPageWithinRange(pageNumber)) {
  446. // easy enough, just update the inline data
  447. int bufferRelativePageNumber = pageNumberToBitIndex(pageNumber);
  448. updateMap(pageNumber, bufferRelativePageNumber, getTableBuffer(), add,
  449. force);
  450. // Write the updated map back to disk
  451. writeTable();
  452. } else {
  453. // uh-oh, we've split our britches. what now?
  454. addOrRemovePageNumberOutsideRange(pageNumber, add, force);
  455. }
  456. }
  457. protected void addOrRemovePageNumberOutsideRange(
  458. int pageNumber, boolean add, boolean force)
  459. throws IOException
  460. {
  461. // determine what our status is before taking action
  462. if(add) {
  463. int firstPage = getFirstPageNumber();
  464. int lastPage = getLastPageNumber();
  465. // we are adding, can we shift the bits and stay inline?
  466. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  467. // no pages currently
  468. firstPage = pageNumber;
  469. lastPage = pageNumber;
  470. } else if(pageNumber > lastPage) {
  471. lastPage = pageNumber;
  472. } else {
  473. firstPage = pageNumber;
  474. }
  475. firstPage = toValidStartPage(firstPage);
  476. if((lastPage - firstPage + 1) < getMaxInlinePages()) {
  477. // we can still fit within an inline map
  478. moveToNewStartPage(firstPage, pageNumber);
  479. } else {
  480. // not going to happen, need to promote the usage map to a
  481. // reference map
  482. promoteInlineHandlerToReferenceHandler(pageNumber);
  483. }
  484. } else {
  485. // we are removing, what does that mean?
  486. if(!force) {
  487. // this should not happen, we are removing a page which is not in
  488. // the map
  489. throw new IOException("Page number " + pageNumber +
  490. " already removed from usage map" +
  491. ", expected range " +
  492. _startPage + " to " + _endPage);
  493. }
  494. }
  495. }
  496. /**
  497. * Shifts the inline usage map so that it now starts with the given page.
  498. * @param newStartPage new page at which to start
  499. * @param newPageNumber optional page number to add once the map has been
  500. * shifted to the new start page
  501. */
  502. protected final void moveToNewStartPage(int newStartPage, int newPageNumber)
  503. throws IOException
  504. {
  505. int oldStartPage = getStartPage();
  506. BitSet oldPageNumbers = (BitSet)getPageNumbers().clone();
  507. // clear out the main table (inline usage map data and start page)
  508. clearTableAndPages();
  509. // write new start page
  510. ByteBuffer tableBuffer = getTableBuffer();
  511. tableBuffer.position(getRowStart() + 1);
  512. tableBuffer.putInt(newStartPage);
  513. // write the new table data
  514. writeTable();
  515. // set new page range
  516. setInlinePageRange(newStartPage);
  517. // put the pages back in
  518. reAddPages(oldStartPage, oldPageNumbers, newPageNumber);
  519. }
  520. }
  521. /**
  522. * Modified version of an "inline" usage map used for the global usage map.
  523. * When an inline usage map is used for the global usage map, we assume
  524. * out-of-range bits are on. We never promote the global usage map to a
  525. * reference usage map (although ms access may).
  526. *
  527. * Note, this UsageMap does not implement all the methods "correctly". Only
  528. * addPageNumber and removePageNumber should be called by PageChannel.
  529. */
  530. private class GlobalInlineHandler extends InlineHandler
  531. {
  532. private GlobalInlineHandler() throws IOException {
  533. }
  534. @Override
  535. public boolean containsPageNumber(int pageNumber) {
  536. // should never be called on global map
  537. throw new UnsupportedOperationException();
  538. }
  539. @Override
  540. protected void addOrRemovePageNumberOutsideRange(
  541. int pageNumber, boolean add, boolean force)
  542. throws IOException
  543. {
  544. // determine what our status is
  545. // for the global usage map, we can ignore out-of-range page addition
  546. // since we assuming out-of-range bits are "on". Note, we are leaving
  547. // small holes in the database here (leaving behind some free pages),
  548. // but it's not the end of the world.
  549. if(!add) {
  550. int firstPage = getFirstPageNumber();
  551. int lastPage = getLastPageNumber();
  552. // we are using an inline map and assuming that anything not
  553. // within the current range is "on". so, if we attempt to set a
  554. // bit which is before the current page, ignore it, we are not
  555. // going back for it.
  556. if((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ||
  557. (pageNumber > lastPage)) {
  558. // move to new start page, filling in as we move
  559. moveToNewStartPageForRemove(firstPage, pageNumber);
  560. }
  561. }
  562. }
  563. /**
  564. * Shifts the inline usage map so that it now starts with the given
  565. * firstPage (if valid), otherwise the newPageNumber. Any page numbers
  566. * added to the end of the usage map are set to "on".
  567. * @param firstPage current first used page
  568. * @param newPageNumber page number to remove once the map has been
  569. * shifted to the new start page
  570. */
  571. private void moveToNewStartPageForRemove(int firstPage, int newPageNumber)
  572. throws IOException
  573. {
  574. int oldEndPage = getEndPage();
  575. int newStartPage =
  576. toValidStartPage(
  577. ((firstPage <= PageChannel.INVALID_PAGE_NUMBER) ? newPageNumber :
  578. // just shift a little and discard any initial unused pages.
  579. (newPageNumber - (getMaxInlinePages() / 2))));
  580. // move the current data
  581. moveToNewStartPage(newStartPage, PageChannel.INVALID_PAGE_NUMBER);
  582. if(firstPage <= PageChannel.INVALID_PAGE_NUMBER) {
  583. // this is the common case where we left everything behind
  584. ByteUtil.fillRange(_tableBuffer, getInlineDataStart(),
  585. getInlineDataEnd());
  586. // write out the updated table
  587. writeTable();
  588. // "add" all the page numbers
  589. getPageNumbers().set(0, getMaxInlinePages());
  590. } else {
  591. // add every new page manually
  592. for(int i = oldEndPage; i < getEndPage(); ++i) {
  593. addPageNumber(i);
  594. }
  595. }
  596. // lastly, remove the new page
  597. removePageNumber(newPageNumber, false);
  598. }
  599. }
  600. /**
  601. * Usage map whose map is written across one or more entire separate pages
  602. * of page type USAGE_MAP. For Jet4, this type of map can contain 32736
  603. * pages per reference page, and a maximum of 17 reference map pages for a
  604. * total maximum of 556512 pages (2 GB).
  605. * @author Tim McCune
  606. */
  607. private class ReferenceHandler extends Handler
  608. {
  609. /** Buffer that contains the current reference map page */
  610. private final TempPageHolder _mapPageHolder =
  611. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  612. private final int _maxPagesPerUsageMapPage;
  613. private ReferenceHandler() throws IOException
  614. {
  615. _maxPagesPerUsageMapPage = ((getFormat().PAGE_SIZE -
  616. getFormat().OFFSET_USAGE_MAP_PAGE_DATA) * 8);
  617. int numUsagePages = (getRowEnd() - getRowStart() - 1) / 4;
  618. setStartOffset(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  619. setPageRange(0, (numUsagePages * _maxPagesPerUsageMapPage));
  620. // there is no "start page" for a reference usage map, so we get an
  621. // extra page reference on top of the number of page references that fit
  622. // in the table
  623. for (int i = 0; i < numUsagePages; i++) {
  624. int mapPageNum = getTableBuffer().getInt(
  625. calculateMapPagePointerOffset(i));
  626. if (mapPageNum > 0) {
  627. ByteBuffer mapPageBuffer =
  628. _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  629. byte pageType = mapPageBuffer.get();
  630. if (pageType != PageTypes.USAGE_MAP) {
  631. throw new IOException("Looking for usage map at page " +
  632. mapPageNum + ", but page type is " +
  633. pageType);
  634. }
  635. mapPageBuffer.position(getFormat().OFFSET_USAGE_MAP_PAGE_DATA);
  636. processMap(mapPageBuffer, (_maxPagesPerUsageMapPage * i));
  637. }
  638. }
  639. }
  640. protected final int getMaxPagesPerUsagePage() {
  641. return _maxPagesPerUsageMapPage;
  642. }
  643. @Override
  644. public void addOrRemovePageNumber(int pageNumber, boolean add,
  645. boolean force)
  646. throws IOException
  647. {
  648. if(!isPageWithinRange(pageNumber)) {
  649. if(force) {
  650. return;
  651. }
  652. throw new IOException("Page number " + pageNumber +
  653. " is out of supported range");
  654. }
  655. int pageIndex = (pageNumber / getMaxPagesPerUsagePage());
  656. int mapPageNum = getTableBuffer().getInt(
  657. calculateMapPagePointerOffset(pageIndex));
  658. ByteBuffer mapPageBuffer = null;
  659. if(mapPageNum > 0) {
  660. mapPageBuffer = _mapPageHolder.setPage(getPageChannel(), mapPageNum);
  661. } else {
  662. // Need to create a new usage map page
  663. mapPageBuffer = createNewUsageMapPage(pageIndex);
  664. mapPageNum = _mapPageHolder.getPageNumber();
  665. }
  666. updateMap(pageNumber,
  667. (pageNumber - (getMaxPagesPerUsagePage() * pageIndex)),
  668. mapPageBuffer, add, force);
  669. getPageChannel().writePage(mapPageBuffer, mapPageNum);
  670. }
  671. /**
  672. * Create a new usage map page and update the map declaration with a
  673. * pointer to it.
  674. * @param pageIndex Index of the page reference within the map declaration
  675. */
  676. private ByteBuffer createNewUsageMapPage(int pageIndex) throws IOException
  677. {
  678. ByteBuffer mapPageBuffer = allocateNewUsageMapPage(pageIndex);
  679. int mapPageNum = _mapPageHolder.getPageNumber();
  680. getTableBuffer().putInt(calculateMapPagePointerOffset(pageIndex),
  681. mapPageNum);
  682. writeTable();
  683. return mapPageBuffer;
  684. }
  685. private int calculateMapPagePointerOffset(int pageIndex) {
  686. return getRowStart() + getFormat().OFFSET_REFERENCE_MAP_PAGE_NUMBERS +
  687. (pageIndex * 4);
  688. }
  689. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  690. throws IOException
  691. {
  692. ByteBuffer mapPageBuffer = _mapPageHolder.setNewPage(getPageChannel());
  693. mapPageBuffer.put(PageTypes.USAGE_MAP);
  694. mapPageBuffer.put((byte) 0x01); //Unknown
  695. mapPageBuffer.putShort((short) 0); //Unknown
  696. return mapPageBuffer;
  697. }
  698. }
  699. /**
  700. * Modified version of a "reference" usage map used for the global usage
  701. * map. Since reference usage maps require allocating pages for their own
  702. * use, we need to handle potential cycles where the PageChannel is
  703. * attempting to allocate a new page (and remove it from the global usage
  704. * map) and this usage map also needs to allocate a new page. When that
  705. * happens, we stash the pending information from the PageChannel and handle
  706. * it after we have retrieved the new page.
  707. *
  708. * Note, this UsageMap does not implement all the methods "correctly". Only
  709. * addPageNumber and removePageNumber should be called by PageChannel.
  710. */
  711. private class GlobalReferenceHandler extends ReferenceHandler
  712. {
  713. private boolean _allocatingPage;
  714. private Integer _pendingPage;
  715. private GlobalReferenceHandler() throws IOException {
  716. }
  717. @Override
  718. public boolean containsPageNumber(int pageNumber) {
  719. // should never be called on global map
  720. throw new UnsupportedOperationException();
  721. }
  722. @Override
  723. public void addOrRemovePageNumber(int pageNumber, boolean add,
  724. boolean force)
  725. throws IOException
  726. {
  727. if(_allocatingPage && !add) {
  728. // we are in the midst of allocating a page for ourself, keep track of
  729. // this new page so we can mark it later...
  730. if(_pendingPage != null) {
  731. throw new IllegalStateException("should only have single pending page");
  732. }
  733. _pendingPage = pageNumber;
  734. return;
  735. }
  736. super.addOrRemovePageNumber(pageNumber, add, force);
  737. while(_pendingPage != null) {
  738. // while updating our usage map, we needed to allocate a new page (and
  739. // thus mark a new page as used). we delayed that marking so that we
  740. // didn't get into an infinite loop. now that we completed the
  741. // original updated, handle the new page. (we use a loop under the
  742. // off the wall chance that adding this page requires allocating a new
  743. // page. in theory, we could do this more than once, but not
  744. // forever).
  745. int removedPageNumber = _pendingPage;
  746. _pendingPage = null;
  747. super.addOrRemovePageNumber(removedPageNumber, false, true);
  748. }
  749. }
  750. @Override
  751. protected ByteBuffer allocateNewUsageMapPage(int pageIndex)
  752. throws IOException
  753. {
  754. try {
  755. // keep track of the fact that we are actively allocating a page for our
  756. // own use so that we can break the potential cycle.
  757. _allocatingPage = true;
  758. ByteBuffer mapPageBuffer = super.allocateNewUsageMapPage(pageIndex);
  759. // for the global usage map, all pages are "on" by default. so
  760. // whenever we add a new backing page to the usage map, we need to
  761. // turn all the pages that it represents to "on" (we essentially lazy
  762. // load this map, which is fine because we should only add pages which
  763. // represent the size of the database currently in use).
  764. int dataStart = getFormat().OFFSET_USAGE_MAP_PAGE_DATA;
  765. ByteUtil.fillRange(mapPageBuffer, dataStart,
  766. getFormat().PAGE_SIZE - dataStart);
  767. int maxPagesPerUmapPage = getMaxPagesPerUsagePage();
  768. int firstNewPage = (pageIndex * maxPagesPerUmapPage);
  769. int lastNewPage = firstNewPage + maxPagesPerUmapPage;
  770. _pageNumbers.set(firstNewPage, lastNewPage);
  771. return mapPageBuffer;
  772. } finally {
  773. _allocatingPage = false;
  774. }
  775. }
  776. }
  777. /**
  778. * Utility class to traverse over the pages in the UsageMap. Remains valid
  779. * in the face of usage map modifications.
  780. */
  781. public final class PageCursor
  782. {
  783. /** handler for moving the page cursor forward */
  784. private final DirHandler _forwardDirHandler = new ForwardDirHandler();
  785. /** handler for moving the page cursor backward */
  786. private final DirHandler _reverseDirHandler = new ReverseDirHandler();
  787. /** the current used page number */
  788. private int _curPageNumber;
  789. /** the previous used page number */
  790. private int _prevPageNumber;
  791. /** the last read modification count on the UsageMap. we track this so
  792. that the cursor can detect updates to the usage map while traversing
  793. and act accordingly */
  794. private int _lastModCount;
  795. private PageCursor() {
  796. reset();
  797. }
  798. public UsageMap getUsageMap() {
  799. return UsageMap.this;
  800. }
  801. /**
  802. * Returns the DirHandler for the given direction
  803. */
  804. private DirHandler getDirHandler(boolean moveForward) {
  805. return (moveForward ? _forwardDirHandler : _reverseDirHandler);
  806. }
  807. /**
  808. * Returns {@code true} if this cursor is up-to-date with respect to its
  809. * usage map.
  810. */
  811. public boolean isUpToDate() {
  812. return(UsageMap.this._modCount == _lastModCount);
  813. }
  814. /**
  815. * @return valid page number if there was another page to read,
  816. * {@link RowIdImpl#LAST_PAGE_NUMBER} otherwise
  817. */
  818. public int getNextPage() {
  819. return getAnotherPage(CursorImpl.MOVE_FORWARD);
  820. }
  821. /**
  822. * @return valid page number if there was another page to read,
  823. * {@link RowIdImpl#FIRST_PAGE_NUMBER} otherwise
  824. */
  825. public int getPreviousPage() {
  826. return getAnotherPage(CursorImpl.MOVE_REVERSE);
  827. }
  828. /**
  829. * Gets another page in the given direction, returning the new page.
  830. */
  831. private int getAnotherPage(boolean moveForward) {
  832. DirHandler handler = getDirHandler(moveForward);
  833. if(_curPageNumber == handler.getEndPageNumber()) {
  834. if(!isUpToDate()) {
  835. restorePosition(_prevPageNumber);
  836. // drop through and retry moving to another page
  837. } else {
  838. // at end, no more
  839. return _curPageNumber;
  840. }
  841. }
  842. checkForModification();
  843. _prevPageNumber = _curPageNumber;
  844. _curPageNumber = handler.getAnotherPageNumber(_curPageNumber);
  845. return _curPageNumber;
  846. }
  847. /**
  848. * After calling this method, getNextPage will return the first page in
  849. * the map
  850. */
  851. public void reset() {
  852. beforeFirst();
  853. }
  854. /**
  855. * After calling this method, {@link #getNextPage} will return the first
  856. * page in the map
  857. */
  858. public void beforeFirst() {
  859. reset(CursorImpl.MOVE_FORWARD);
  860. }
  861. /**
  862. * After calling this method, {@link #getPreviousPage} will return the
  863. * last page in the map
  864. */
  865. public void afterLast() {
  866. reset(CursorImpl.MOVE_REVERSE);
  867. }
  868. /**
  869. * Resets this page cursor for traversing the given direction.
  870. */
  871. protected void reset(boolean moveForward) {
  872. _curPageNumber = getDirHandler(moveForward).getBeginningPageNumber();
  873. _prevPageNumber = _curPageNumber;
  874. _lastModCount = UsageMap.this._modCount;
  875. }
  876. /**
  877. * Restores a current position for the cursor (current position becomes
  878. * previous position).
  879. */
  880. private void restorePosition(int curPageNumber)
  881. {
  882. restorePosition(curPageNumber, _curPageNumber);
  883. }
  884. /**
  885. * Restores a current and previous position for the cursor.
  886. */
  887. protected void restorePosition(int curPageNumber, int prevPageNumber)
  888. {
  889. if((curPageNumber != _curPageNumber) ||
  890. (prevPageNumber != _prevPageNumber))
  891. {
  892. _prevPageNumber = updatePosition(prevPageNumber);
  893. _curPageNumber = updatePosition(curPageNumber);
  894. _lastModCount = UsageMap.this._modCount;
  895. } else {
  896. checkForModification();
  897. }
  898. }
  899. /**
  900. * Checks the usage map for modifications an updates state accordingly.
  901. */
  902. private void checkForModification() {
  903. if(!isUpToDate()) {
  904. _prevPageNumber = updatePosition(_prevPageNumber);
  905. _curPageNumber = updatePosition(_curPageNumber);
  906. _lastModCount = UsageMap.this._modCount;
  907. }
  908. }
  909. private int updatePosition(int pageNumber) {
  910. if(pageNumber < UsageMap.this.getFirstPageNumber()) {
  911. pageNumber = RowIdImpl.FIRST_PAGE_NUMBER;
  912. } else if(pageNumber > UsageMap.this.getLastPageNumber()) {
  913. pageNumber = RowIdImpl.LAST_PAGE_NUMBER;
  914. }
  915. return pageNumber;
  916. }
  917. @Override
  918. public String toString() {
  919. return getClass().getSimpleName() + " CurPosition " + _curPageNumber +
  920. ", PrevPosition " + _prevPageNumber;
  921. }
  922. /**
  923. * Handles moving the cursor in a given direction. Separates cursor
  924. * logic from value storage.
  925. */
  926. private abstract class DirHandler {
  927. public abstract int getAnotherPageNumber(int curPageNumber);
  928. public abstract int getBeginningPageNumber();
  929. public abstract int getEndPageNumber();
  930. }
  931. /**
  932. * Handles moving the cursor forward.
  933. */
  934. private final class ForwardDirHandler extends DirHandler {
  935. @Override
  936. public int getAnotherPageNumber(int curPageNumber) {
  937. if(curPageNumber == getBeginningPageNumber()) {
  938. return UsageMap.this.getFirstPageNumber();
  939. }
  940. return UsageMap.this.getNextPageNumber(curPageNumber);
  941. }
  942. @Override
  943. public int getBeginningPageNumber() {
  944. return RowIdImpl.FIRST_PAGE_NUMBER;
  945. }
  946. @Override
  947. public int getEndPageNumber() {
  948. return RowIdImpl.LAST_PAGE_NUMBER;
  949. }
  950. }
  951. /**
  952. * Handles moving the cursor backward.
  953. */
  954. private final class ReverseDirHandler extends DirHandler {
  955. @Override
  956. public int getAnotherPageNumber(int curPageNumber) {
  957. if(curPageNumber == getBeginningPageNumber()) {
  958. return UsageMap.this.getLastPageNumber();
  959. }
  960. return UsageMap.this.getPrevPageNumber(curPageNumber);
  961. }
  962. @Override
  963. public int getBeginningPageNumber() {
  964. return RowIdImpl.LAST_PAGE_NUMBER;
  965. }
  966. @Override
  967. public int getEndPageNumber() {
  968. return RowIdImpl.FIRST_PAGE_NUMBER;
  969. }
  970. }
  971. }
  972. }