ClusterUsageBitmap.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /* Copyright (C) 2014 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using Utilities;
  12. namespace DiskAccessLibrary.FileSystems.NTFS
  13. {
  14. public class ClusterUsageBitmap : NTFSFile
  15. {
  16. NTFSVolume m_volume;
  17. private long m_bufferedClusterVCN = -1;
  18. private byte[] m_bufferedCluster;
  19. private bool m_isBufferDirty; // if set to true, we need to write the buffer
  20. public ClusterUsageBitmap(NTFSVolume volume) : base(volume, MasterFileTable.BitmapSegmentNumber)
  21. {
  22. m_volume = volume;
  23. }
  24. private byte[] GetBitmapCluster(long bitmapClusterVCN)
  25. {
  26. if (m_bufferedClusterVCN != bitmapClusterVCN)
  27. {
  28. if (m_isBufferDirty)
  29. {
  30. FlushBuffer();
  31. }
  32. m_bufferedClusterVCN = bitmapClusterVCN;
  33. // ClusterUsageBitmap is always non-resident
  34. m_bufferedCluster = FileRecord.NonResidentDataRecord.ReadDataCluster(Volume, bitmapClusterVCN);
  35. }
  36. return m_bufferedCluster;
  37. }
  38. private void FlushBuffer()
  39. {
  40. FileRecord.NonResidentDataRecord.WriteDataClusters(Volume, m_bufferedClusterVCN, m_bufferedCluster);
  41. m_isBufferDirty = false;
  42. }
  43. /// <param name="lcn">Logical cluster number</param>
  44. private bool IsClusterFree(ulong lcn)
  45. {
  46. long bitmapClusterVCN = ((long)(lcn / 8)) / Volume.BytesPerCluster;
  47. byte[] bitmap = GetBitmapCluster(bitmapClusterVCN);
  48. int lcnByteOffset = (int)(((long)(lcn / 8)) % Volume.BytesPerCluster);
  49. int lcnBitIndex = (int)(lcn % 8);
  50. bool isInUse = ((bitmap[lcnByteOffset] >> lcnBitIndex) & 0x01) != 0;
  51. return !isInUse;
  52. }
  53. private void UpdateClusterStatus(ulong lcn, bool isUsed)
  54. {
  55. long bitmapClusterVCN = (long)(lcn / (8 * (uint)Volume.BytesPerCluster));
  56. // bitmap will reference m_bufferedCluster
  57. byte[] bitmap = GetBitmapCluster(bitmapClusterVCN);
  58. ulong clusterIndexInBitmap = lcn % (8 * (uint)Volume.BytesPerCluster);
  59. UpdateClusterStatus(bitmap, clusterIndexInBitmap, true);
  60. m_isBufferDirty = true;
  61. }
  62. public KeyValuePairList<ulong, long> AllocateClusters(ulong desiredStartLCN, long numberOfClusters)
  63. {
  64. KeyValuePairList<ulong, long> freeClusterRunList = FindClustersToAllocate(desiredStartLCN, numberOfClusters);
  65. // mark the clusters as used in the volume bitmap
  66. for (int index = 0; index < freeClusterRunList.Count; index++)
  67. {
  68. ulong runStartLCN = freeClusterRunList[index].Key;
  69. long runLength = freeClusterRunList[index].Value;
  70. for (uint position = 0; position < runLength; position++)
  71. {
  72. UpdateClusterStatus(runStartLCN + position, true);
  73. }
  74. }
  75. if (m_isBufferDirty)
  76. {
  77. FlushBuffer();
  78. }
  79. return freeClusterRunList;
  80. }
  81. /// <summary>
  82. /// Return list of free cluster runs, key is cluster LCN, value is run length
  83. /// </summary>
  84. private KeyValuePairList<ulong, long> FindClustersToAllocate(ulong desiredStartLCN, long numberOfClusters)
  85. {
  86. KeyValuePairList<ulong, long> result = new KeyValuePairList<ulong, long>();
  87. long leftToAllocate;
  88. ulong endLCN = (ulong)(m_volume.Size / m_volume.BytesPerCluster) - 1;
  89. KeyValuePairList<ulong, long> segment = FindClustersToAllocate(desiredStartLCN, endLCN, numberOfClusters, out leftToAllocate);
  90. result.AddRange(segment);
  91. if (leftToAllocate > 0 && desiredStartLCN > 0)
  92. {
  93. segment = FindClustersToAllocate(0, desiredStartLCN - 1, leftToAllocate, out leftToAllocate);
  94. result.AddRange(segment);
  95. }
  96. if (leftToAllocate > 0)
  97. {
  98. throw new Exception("Could not allocate clusters. Not enough free disk space");
  99. }
  100. return result;
  101. }
  102. /// <param name="clustersToAllocate">Number of clusters to allocate</param>
  103. private KeyValuePairList<ulong, long> FindClustersToAllocate(ulong startLCN, ulong endLCN, long clustersToAllocate, out long leftToAllocate)
  104. {
  105. KeyValuePairList<ulong, long> result = new KeyValuePairList<ulong, long>();
  106. leftToAllocate = clustersToAllocate;
  107. ulong runStartLCN = 0; // temporary
  108. long runLength = 0;
  109. ulong nextLCN = startLCN;
  110. while (nextLCN <= endLCN && leftToAllocate > 0)
  111. {
  112. if (IsClusterFree(nextLCN))
  113. {
  114. if (runLength == 0)
  115. {
  116. runStartLCN = nextLCN;
  117. runLength = 1;
  118. }
  119. else
  120. {
  121. runLength++;
  122. }
  123. leftToAllocate--;
  124. }
  125. else
  126. {
  127. if (runLength > 0)
  128. {
  129. result.Add(runStartLCN, runLength);
  130. runLength = 0;
  131. // add this run
  132. }
  133. }
  134. nextLCN++;
  135. }
  136. // add the last run
  137. if (runLength > 0)
  138. {
  139. result.Add(runStartLCN, runLength);
  140. }
  141. return result;
  142. }
  143. private byte CountNumberOfFreeClusters(byte bitmap)
  144. {
  145. byte result = 0;
  146. for (int bitIndex = 0; bitIndex < 8; bitIndex++)
  147. {
  148. bool isFree = ((bitmap >> bitIndex) & 0x01) == 0;
  149. if (isFree)
  150. {
  151. result++;
  152. }
  153. }
  154. return result;
  155. }
  156. // Each bit in the $Bitmap file represents a cluster.
  157. // The size of the $Bitmap file is always a multiple of 8 bytes, extra bits are always set to 1.
  158. public long CountNumberOfFreeClusters()
  159. {
  160. int transferSizeInClusters = Settings.MaximumTransferSizeLBA / m_volume.SectorsPerCluster;
  161. ulong endLCN = (ulong)(m_volume.Size / m_volume.BytesPerCluster) - 1;
  162. long lastClusterVCN = ((long)(endLCN / 8)) / Volume.BytesPerCluster;
  163. long result = 0;
  164. // build lookup table
  165. byte[] lookup = new byte[256];
  166. for (int index = 0; index < 256; index++)
  167. {
  168. lookup[index] = CountNumberOfFreeClusters((byte)index);
  169. }
  170. // extra bits will be marked as used, so no need for special treatment
  171. for (long bitmapVcn = 0; bitmapVcn < lastClusterVCN; bitmapVcn += transferSizeInClusters)
  172. {
  173. byte[] bitmap = FileRecord.NonResidentDataRecord.ReadDataClusters(Volume, bitmapVcn, transferSizeInClusters);
  174. for (int index = 0; index < bitmap.Length; index++)
  175. {
  176. result += lookup[bitmap[index]];
  177. }
  178. }
  179. return result;
  180. }
  181. public static void UpdateClusterStatus(byte[] bitmap, ulong clusterIndexInBitmap, bool isUsed)
  182. {
  183. ulong byteOffset = (ulong)clusterIndexInBitmap / 8;
  184. int bitOffset = (int)clusterIndexInBitmap % 8;
  185. if (isUsed)
  186. {
  187. bitmap[byteOffset] |= (byte)(0x01 << bitOffset);
  188. }
  189. else
  190. {
  191. bitmap[byteOffset] &= (byte)(~(0x01 << bitOffset));
  192. }
  193. }
  194. }
  195. }