PhysicalDisk.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /* Copyright (C) 2014-2016 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.Runtime.InteropServices;
  11. using System.Security;
  12. using System.Text;
  13. using Microsoft.Win32.SafeHandles;
  14. using Utilities;
  15. namespace DiskAccessLibrary
  16. {
  17. public class PhysicalDisk : Disk, IDiskGeometry
  18. {
  19. // ReadFile failed with ERROR_INVALID_FUNCTION when transfer size was > 4880 sectors when working with an iSCSI drive
  20. // Note: The size of the internal buffer has no meaningful impact on performance, instead you should look at MaximumTransferSizeLBA.
  21. public const int MaximumDirectTransferSizeLBA = 2048; // 1 MB (assuming 512-byte sectors)
  22. private int m_physicalDiskIndex;
  23. private int m_bytesPerSector;
  24. private long m_size;
  25. private bool m_isReadOnly;
  26. private string m_description;
  27. private string m_serialNumber;
  28. // CHS:
  29. private long m_cylinders;
  30. private int m_tracksPerCylinder; // a.k.a. heads
  31. private int m_sectorsPerTrack;
  32. public PhysicalDisk(int physicalDiskIndex) : this(physicalDiskIndex, false)
  33. {
  34. }
  35. public PhysicalDisk(int physicalDiskIndex, bool isReadOnly)
  36. {
  37. m_physicalDiskIndex = physicalDiskIndex;
  38. m_isReadOnly = isReadOnly;
  39. PopulateDiskInfo(); // We must do it before any read request use the disk handle
  40. PopulateDescription();
  41. }
  42. public override byte[] ReadSectors(long sectorIndex, int sectorCount)
  43. {
  44. if (sectorCount > MaximumDirectTransferSizeLBA)
  45. {
  46. // we must read one segment at the time, and copy the segments to a big bufffer
  47. byte[] buffer = new byte[sectorCount * m_bytesPerSector];
  48. for (int sectorOffset = 0; sectorOffset < sectorCount; sectorOffset += MaximumDirectTransferSizeLBA)
  49. {
  50. int leftToRead = sectorCount - sectorOffset;
  51. int sectorsToRead = (int)Math.Min(leftToRead, MaximumDirectTransferSizeLBA);
  52. byte[] segment = ReadSectorsUnbuffered(sectorIndex + sectorOffset, sectorsToRead);
  53. Array.Copy(segment, 0, buffer, sectorOffset * m_bytesPerSector, segment.Length);
  54. }
  55. return buffer;
  56. }
  57. else
  58. {
  59. return ReadSectorsUnbuffered(sectorIndex, sectorCount);
  60. }
  61. }
  62. /// <summary>
  63. /// Sector refers to physical disk blocks, we can only read complete blocks
  64. /// </summary>
  65. public byte[] ReadSectorsUnbuffered(long sectorIndex, int sectorCount)
  66. {
  67. bool releaseHandle;
  68. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.Read, ShareMode.ReadWrite, out releaseHandle);
  69. if (!handle.IsInvalid)
  70. {
  71. FileStreamEx stream = new FileStreamEx(handle, FileAccess.Read);
  72. byte[] buffer = new byte[m_bytesPerSector * sectorCount];
  73. try
  74. {
  75. stream.Seek(sectorIndex * m_bytesPerSector, SeekOrigin.Begin);
  76. stream.Read(buffer, 0, m_bytesPerSector * sectorCount);
  77. }
  78. finally
  79. {
  80. stream.Close(releaseHandle);
  81. if (releaseHandle)
  82. {
  83. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  84. }
  85. }
  86. return buffer;
  87. }
  88. else
  89. {
  90. // we always release invalid handle
  91. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  92. // get error code and throw
  93. int errorCode = Marshal.GetLastWin32Error();
  94. string message = String.Format("Failed to read sector {0} from disk {1}.", sectorIndex, m_physicalDiskIndex);
  95. IOExceptionHelper.ThrowIOError(errorCode, message);
  96. return null; // this line will not be reached
  97. }
  98. }
  99. public override void WriteSectors(long sectorIndex, byte[] data)
  100. {
  101. if (data.Length % m_bytesPerSector > 0)
  102. {
  103. throw new IOException("Cannot write partial sectors");
  104. }
  105. int sectorCount = data.Length / m_bytesPerSector;
  106. if (sectorCount > MaximumDirectTransferSizeLBA)
  107. {
  108. // we must write one segment at the time
  109. for (int sectorOffset = 0; sectorOffset < sectorCount; sectorOffset += MaximumDirectTransferSizeLBA)
  110. {
  111. int leftToWrite = sectorCount - sectorOffset;
  112. int sectorsToWrite = (int)Math.Min(leftToWrite, MaximumDirectTransferSizeLBA);
  113. byte[] segment = new byte[sectorsToWrite * m_bytesPerSector];
  114. Array.Copy(data, sectorOffset * m_bytesPerSector, segment, 0, sectorsToWrite * m_bytesPerSector);
  115. WriteSectorsUnbuffered(sectorIndex + sectorOffset, segment);
  116. }
  117. }
  118. else
  119. {
  120. WriteSectorsUnbuffered(sectorIndex, data);
  121. }
  122. }
  123. public void WriteSectorsUnbuffered(long sectorIndex, byte[] data)
  124. {
  125. if (data.Length % m_bytesPerSector > 0)
  126. {
  127. throw new IOException("Cannot write partial sectors");
  128. }
  129. if (IsReadOnly)
  130. {
  131. throw new UnauthorizedAccessException("Attempted to perform write on a readonly disk");
  132. }
  133. bool releaseHandle;
  134. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.ReadWrite, ShareMode.Read, out releaseHandle);
  135. if (!handle.IsInvalid)
  136. {
  137. FileStreamEx stream = new FileStreamEx(handle, FileAccess.Write);
  138. try
  139. {
  140. stream.Seek(sectorIndex * m_bytesPerSector, SeekOrigin.Begin);
  141. stream.Write(data, 0, data.Length);
  142. stream.Flush();
  143. }
  144. finally
  145. {
  146. stream.Close(releaseHandle);
  147. if (releaseHandle)
  148. {
  149. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  150. }
  151. }
  152. }
  153. else
  154. {
  155. // we always release invalid handle
  156. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  157. // get error code and throw
  158. int errorCode = Marshal.GetLastWin32Error();
  159. string message = String.Format("Failed to write to sector {0} of disk {1}.", sectorIndex, m_physicalDiskIndex);
  160. IOExceptionHelper.ThrowIOError(errorCode, message);
  161. }
  162. }
  163. public bool ExclusiveLock()
  164. {
  165. bool releaseHandle;
  166. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.ReadWrite, ShareMode.Read, out releaseHandle);
  167. if (releaseHandle) // new allocation
  168. {
  169. if (!handle.IsInvalid)
  170. {
  171. return true;
  172. }
  173. else
  174. {
  175. // we always release invalid handle
  176. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  177. return false;
  178. }
  179. }
  180. else
  181. {
  182. return false;
  183. }
  184. }
  185. public bool ReleaseLock()
  186. {
  187. return PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  188. }
  189. /// <summary>
  190. /// Invalidates the cached partition table and re-enumerates the device
  191. /// </summary>
  192. /// <exception cref="System.IO.IOException"></exception>
  193. public void UpdateProperties()
  194. {
  195. bool releaseHandle;
  196. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.ReadWrite, ShareMode.Read, out releaseHandle);
  197. if (!handle.IsInvalid)
  198. {
  199. bool success = PhysicalDiskControl.UpdateDiskProperties(handle);
  200. if (!success)
  201. {
  202. throw new IOException("Failed to update disk properties");
  203. }
  204. if (releaseHandle)
  205. {
  206. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  207. }
  208. }
  209. else
  210. {
  211. // we always release invalid handle
  212. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  213. }
  214. }
  215. private void PopulateDiskInfo()
  216. {
  217. bool releaseHandle;
  218. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.Read, ShareMode.ReadWrite, out releaseHandle);
  219. if (!handle.IsInvalid)
  220. {
  221. if (!PhysicalDiskControl.IsMediaAccesible(handle))
  222. {
  223. throw new DeviceNotReadyException();
  224. }
  225. DISK_GEOMETRY diskGeometry = PhysicalDiskControl.GetDiskGeometryAndSize(handle, out m_size);
  226. if (releaseHandle)
  227. {
  228. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  229. }
  230. m_bytesPerSector = (int)diskGeometry.BytesPerSector;
  231. // CHS:
  232. m_cylinders = diskGeometry.Cylinders;
  233. m_tracksPerCylinder = (int)diskGeometry.TracksPerCylinder;
  234. m_sectorsPerTrack = (int)diskGeometry.SectorsPerTrack;
  235. }
  236. else
  237. {
  238. // we always release invalid handle
  239. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  240. // get error code and throw
  241. int errorCode = Marshal.GetLastWin32Error();
  242. string message = String.Format("Failed to access disk {0}.", m_physicalDiskIndex);
  243. if (errorCode == (int)Win32Error.ERROR_FILE_NOT_FOUND)
  244. {
  245. throw new DriveNotFoundException(message);
  246. }
  247. else
  248. {
  249. IOExceptionHelper.ThrowIOError(errorCode, message);
  250. }
  251. }
  252. }
  253. private void PopulateDescription()
  254. {
  255. bool releaseHandle;
  256. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.Read, ShareMode.ReadWrite, out releaseHandle);
  257. if (!handle.IsInvalid)
  258. {
  259. m_description = PhysicalDiskControl.GetDeviceDescription(handle);
  260. m_serialNumber = PhysicalDiskControl.GetDeviceSerialNumber(handle);
  261. if (releaseHandle)
  262. {
  263. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  264. }
  265. }
  266. else
  267. {
  268. // we always release invalid handle
  269. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  270. // get error code and throw
  271. int errorCode = Marshal.GetLastWin32Error();
  272. string message = String.Format("Failed to access disk {0}.", m_physicalDiskIndex);
  273. if (errorCode == (int)Win32Error.ERROR_FILE_NOT_FOUND)
  274. {
  275. throw new DriveNotFoundException(message);
  276. }
  277. else
  278. {
  279. IOExceptionHelper.ThrowIOError(errorCode, message);
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// Available on Windows Vista and newer
  285. /// </summary>
  286. public bool? GetOnlineStatus(out string err)
  287. {
  288. bool isReadOnly;
  289. return GetOnlineStatus(out isReadOnly,out err);
  290. }
  291. /// <summary>
  292. /// Available on Windows Vista and newer
  293. /// </summary>
  294. /// <exception cref="System.IO.IOException"></exception>
  295. public bool? GetOnlineStatus(out bool isReadOnly,out string err)
  296. {
  297. bool releaseHandle;
  298. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.ReadWrite, ShareMode.Read, out releaseHandle);
  299. if (!handle.IsInvalid)
  300. {
  301. bool isOnline = PhysicalDiskControl.GetOnlineStatus(handle, out isReadOnly);
  302. if (releaseHandle)
  303. {
  304. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  305. }
  306. err = null;
  307. return isOnline;
  308. }
  309. else
  310. {
  311. // we always release invalid handle
  312. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  313. // get error code and throw
  314. int errorCode = Marshal.GetLastWin32Error();
  315. isReadOnly = false;
  316. err = $"Failed to get disk {m_physicalDiskIndex} online status, Win32 Error: {errorCode}";
  317. return null;
  318. }
  319. }
  320. /// <summary>
  321. /// Available on Windows Vista and newer
  322. /// </summary>
  323. public bool SetOnlineStatus(bool online)
  324. {
  325. return SetOnlineStatus(online, false);
  326. }
  327. /// <summary>
  328. /// Available on Windows Vista and newer
  329. /// </summary>
  330. /// <exception cref="System.IO.IOException"></exception>
  331. public bool SetOnlineStatus(bool online, bool persist)
  332. {
  333. bool releaseHandle;
  334. SafeFileHandle handle = PhysicalDiskHandlePool.ObtainHandle(m_physicalDiskIndex, FileAccess.ReadWrite, ShareMode.Read, out releaseHandle);
  335. if (!handle.IsInvalid)
  336. {
  337. bool success = PhysicalDiskControl.SetOnlineStatus(handle, online, persist);
  338. if (releaseHandle)
  339. {
  340. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  341. }
  342. return success;
  343. }
  344. else
  345. {
  346. // we always release invalid handle
  347. PhysicalDiskHandlePool.ReleaseHandle(m_physicalDiskIndex);
  348. int errorCode = Marshal.GetLastWin32Error();
  349. if (errorCode == (int)Win32Error.ERROR_SHARING_VIOLATION)
  350. {
  351. return false;
  352. }
  353. else
  354. {
  355. string message = String.Format("Failed to take disk {0} offline, Win32 Error: {1}", m_physicalDiskIndex, errorCode);
  356. throw new IOException(message);
  357. }
  358. }
  359. }
  360. public int PhysicalDiskIndex
  361. {
  362. get
  363. {
  364. return m_physicalDiskIndex;
  365. }
  366. }
  367. public override int BytesPerSector
  368. {
  369. get
  370. {
  371. return m_bytesPerSector;
  372. }
  373. }
  374. public override long Size
  375. {
  376. get
  377. {
  378. return m_size;
  379. }
  380. }
  381. public override bool IsReadOnly
  382. {
  383. get
  384. {
  385. return m_isReadOnly;
  386. }
  387. }
  388. public string Description
  389. {
  390. get
  391. {
  392. return m_description;
  393. }
  394. }
  395. public string SerialNumber
  396. {
  397. get
  398. {
  399. return m_serialNumber;
  400. }
  401. }
  402. public long Cylinders
  403. {
  404. get
  405. {
  406. return m_cylinders;
  407. }
  408. }
  409. /// <summary>
  410. /// a.k.a heads
  411. /// </summary>
  412. public int TracksPerCylinder
  413. {
  414. get
  415. {
  416. return m_tracksPerCylinder;
  417. }
  418. }
  419. public int SectorsPerTrack
  420. {
  421. get
  422. {
  423. return m_sectorsPerTrack;
  424. }
  425. }
  426. }
  427. }