FarManager icon indicating copy to clipboard operation
FarManager copied to clipboard

Add Bypass system cache option to Copy/Move dialog

Open check4game opened this issue 2 years ago • 9 comments

Summary

Обход системного кэша при копировании/перемещении больших файлов между папками или между разными дисками

References

Checklist

  • [x] I have followed the contributing guidelines.
  • [ ] I have discussed this with project maintainers:
    If not checked, I accept that this work might be rejected in favor of a different grand plan.

Details

Мне видится что будет полезным отключать системный кэш, для таких операций ( позволяет ускорить процесс по времени и исключить вытеснение пользовательских данных из системного кэша на файловых серверах)

Обход системного кэша, осуществляется через установку флага COPY_FILE_NO_BUFFERING при вызове функции CopyFileEx.

Дополнительно введен минимальный размер файла для которого данный флаг устанавливается

Заранее прошу извинить если что-то забыл указать по данному улучшению, я делаю это впервые.

check4game avatar Dec 04 '23 13:12 check4game

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
No Duplication information No Duplication information

sonarqubecloud[bot] avatar Dec 04 '23 13:12 sonarqubecloud[bot]

On general idea:

Sounds interesting, but do you just think it will be useful, or have you actually measured it and noticed a substantial difference? What other known file managers, copy tools etc. implement this?

On implementation:

  1. We have 2 copy routines: a CopyFileEx call and a ReadFile + WriteFile loop. The current change only covers the CopyFileEx path. If we decide to add it, the other one must be covered too, supposedly using FILE_FLAG_NO_BUFFERING.

    • There are certain requirements when working without buffering. We will need to ensure that memory buffers and file reads and writes are properly aligned, including when dealing with sparse files.
  2. "Large file" is a relative concept. 1 GB file is probably "large" for a system with 4 GB RAM, but probably "nothing" for a system with 64 GB RAM. I doubt that an average user can figure out on their own where to draw the line. I suspect that an average user will most likely set it incorrectly, making things worse. If we decide to add it, the limit should probably be calculated automatically (e.g. 10-20% of RAM) and applied automatically without exposing any knobs to the user.

alabuzhev avatar Dec 04 '23 17:12 alabuzhev

On general idea:

Sounds interesting, but do you just think it will be useful, or have you actually measured it and noticed a substantial difference? What other known file managers, copy tools etc. implement this?

On implementation:

  1. We have 2 copy routines: a CopyFileEx call and a ReadFile + WriteFile loop. The current change only covers the CopyFileEx path. If we decide to add it, the other one must be covered too, supposedly using FILE_FLAG_NO_BUFFERING.

    • There are certain requirements when working without buffering. We will need to ensure that memory buffers and file reads and writes are properly aligned, including when dealing with sparse files.
  2. "Large file" is a relative concept. 1 GB file is probably "large" for a system with 4 GB RAM, but probably "nothing" for a system with 64 GB RAM. I doubt that an average user can figure out on their own where to draw the line. I suspect that an average user will most likely set it incorrectly, making things worse. If we decide to add it, the limit should probably be calculated automatically (e.g. 10-20% of RAM) and applied automatically without exposing any knobs to the user.

Спасибо за комментарий,

  1. да я понимаю что код содержит также ветку которая использует Read/Write цикл для копирования файла, но мне показалось что он оставлен только для уникальных случаев копирования, для 95% подходит ветка CopyFileEx
  2. да для этой ветки возможна реализация через FILE_FLAG_NO_BUFFERING, я это понимаю....
  3. если согласиться с Вами что 1GB файл не является "большим" в системе с 64GB памяти, то что можно будет сказать если я копирую 100 файлов по 1GB? при копировании в авто режиме (10-20% RAM) данные этих файлов забьют весь доступный кэш, тем самым вытеснят все пользовательские данные из кэша
  4. по моему коду видно, что я специально не стал запоминать выбор этой опции при повторном вызове диалога копирования/перемещения, это сделано специально, пользователь должен осознанно использовать эту функцию при копировании/перемещении файлов

check4game avatar Dec 04 '23 18:12 check4game

в дополнение....

5 возможно использование предела размера файла в качестве переключателя было моим поспешным решением, потому как затеняет причину использования отключения системного кэша 6 моя идея в первую очередь была в том что бы быть уверенным что операция записи последнего блока файла будет где-то совсем рядом по времени после того как файл будет закрыт в Far, а не через несколько минут, после того как система завершит сброс страниц из кэша на диск, это особенно важно для операции MOVE 7 я знаю только консольные утилиты xcopy & robocopy которые позволяют это делать, но я уже много лет использую Far и считаю что он является оптимальным вариантом для работы с файлами на windows

check4game avatar Dec 04 '23 20:12 check4game

6 моя идея в первую очередь была в том что бы быть уверенным что операция записи последнего блока файла будет где-то совсем рядом по времени после того как файл будет закрыт в Far, а не через несколько минут, после того как система завершит сброс страниц из кэша на диск, это особенно важно для операции MOVE

+1 for a control to ensure the completion of a write operation is sequenced before the closing of the dialog. Off by default of course. Also, a well-written explanation in the help topic(s) is a must (I can help here).

Now, I am not sure that synchronizing the completion of a write operation (main goal here?) and turning off system cache are synonymous. If Far performs an async I/O and closes the dialog as soon as writing of the last buffer was initiated (I do not know; did not check), the user still cannot be sure that the data were successfully written.

MKadaner avatar Dec 05 '23 02:12 MKadaner

я записал ролик, как ведет себя система при копировании файла без COPY_FILE_NO_BUFFERING и с COPY_FILE_NO_BUFFERING

https://www.youtube.com/watch?v=KPMpGOOyZXg

check4game avatar Dec 05 '23 15:12 check4game

Now, I am not sure that synchronizing the completion of a write operation (main goal here?) and turning off system cache are synonymous. If Far performs an async I/O and closes the dialog as soon as writing of the last buffer was initiated (I do not know; did not check), the user still cannot be sure that the data were successfully written.

1 да это не основная цель, хотя конечно можно рассмотреть и этот вариант для параноиков 2 по коду Far используется CopyFileEx или синхронные Read/Write

check4game avatar Dec 05 '23 16:12 check4game

данные этих файлов забьют весь доступный кэш, тем самым вытеснят все пользовательские данные из кэша

Yep, you're right. But by this logic manual limit doesn't make much sense too: there always can be too many "small" files.

Perhaps a single checkbox "Bypass write cache", not persisted anywhere, would be the optimal choice.

alabuzhev avatar Dec 05 '23 18:12 alabuzhev

данные этих файлов забьют весь доступный кэш, тем самым вытеснят все пользовательские данные из кэша

Yep, you're right. But by this logic manual limit doesn't make much sense too: there always can be too many "small" files.

Perhaps a single checkbox "Bypass write cache", not persisted anywhere, would be the optimal choice.

да я тоже думаю что достаточно одного флага, без сохранения состояния.

check4game avatar Dec 05 '23 20:12 check4game