direct_io.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #include "align.h"
  3. #include "file.h"
  4. #include <util/generic/buffer.h>
  5. // Supports Linux Direct-IO:
  6. // - Simple buffering logic.
  7. // - Default buffer size of 128KB matches VM page writeback granularity, to maximize IO throughput.
  8. // - Supports writing odd sized files by turning off direct IO for the last chunk.
  9. class TDirectIOBufferedFile {
  10. public:
  11. TDirectIOBufferedFile(const TString& path, EOpenMode oMode, size_t buflen = 1 << 17);
  12. ~TDirectIOBufferedFile();
  13. void FlushData();
  14. void Finish();
  15. size_t Read(void* buffer, size_t byteCount);
  16. void Write(const void* buffer, size_t byteCount);
  17. size_t Pread(void* buffer, size_t byteCount, ui64 offset);
  18. void Pwrite(const void* buffer, size_t byteCount, ui64 offset);
  19. inline bool IsOpen() const {
  20. return true;
  21. }
  22. inline ui64 GetWritePosition() const {
  23. return WritePosition;
  24. }
  25. inline ui64 GetLength() const {
  26. return FlushedBytes + DataLen;
  27. }
  28. inline FHANDLE GetHandle() {
  29. return File.GetHandle();
  30. }
  31. inline void FallocateNoResize(ui64 length) {
  32. File.FallocateNoResize(length);
  33. }
  34. inline void ShrinkToFit() {
  35. File.ShrinkToFit();
  36. }
  37. private:
  38. inline bool IsAligned(i64 value) {
  39. return Alignment ? value == AlignDown<i64>(value, Alignment) : true;
  40. }
  41. inline bool IsAligned(const void* value) {
  42. return Alignment ? value == AlignDown(value, Alignment) : true;
  43. }
  44. size_t PreadSafe(void* buffer, size_t byteCount, ui64 offset);
  45. size_t ReadFromFile(void* buffer, size_t byteCount, ui64 offset);
  46. void WriteToFile(const void* buf, size_t len, ui64 position);
  47. void WriteToBuffer(const void* buf, size_t len, ui64 position);
  48. void SetDirectIO(bool value);
  49. private:
  50. TFile File;
  51. size_t Alignment;
  52. size_t BufLen;
  53. size_t DataLen;
  54. void* Buffer;
  55. TBuffer BufferStorage;
  56. ui64 ReadPosition;
  57. ui64 WritePosition;
  58. ui64 FlushedBytes;
  59. ui64 FlushedToDisk;
  60. bool DirectIO;
  61. };