fcfa801
--- a/src/calibre/__init__.py	2019-07-21 13:24:51.302383981 +0200
fcfa801
+++ b/src/calibre/__init__.py	2019-07-21 13:03:23.170204400 +0200
fcfa801
@@ -726,3 +660,21 @@
fcfa801
 def fsync(fileobj):
fcfa801
     fileobj.flush()
fcfa801
     os.fsync(fileobj.fileno())
fcfa801
+    if islinux and getattr(fileobj, 'name', None):
fcfa801
+        # On Linux kernels after 5.1.9 and 4.19.50 using fsync without any
fcfa801
+        # following activity causes Kindles to eject. Instead of fixing this in
fcfa801
+        # the obvious way, which is to have the kernel send some harmless
fcfa801
+        # filesystem activity after the FSYNC, the kernel developers seem to
fcfa801
+        # think the correct solution is to disable FSYNC using a mount flag
fcfa801
+        # which users will have to turn on manually. So instead we create some
fcfa801
+        # harmless filesystem activity, and who cares about performance.
fcfa801
+        # See https://bugs.launchpad.net/calibre/+bug/1834641
fcfa801
+        # and https://bugzilla.kernel.org/show_bug.cgi?id=203973
fcfa801
+        # To check for the existence of the bug, simply run:
fcfa801
+        # python -c "p = '/run/media/kovid/Kindle/driveinfo.calibre'; f = open(p, 'r+b'); os.fsync(f.fileno());"
fcfa801
+        # this will cause the Kindle to disconnect.
fcfa801
+        try:
fcfa801
+            os.utime(fileobj.name, None)
fcfa801
+        except Exception:
fcfa801
+            import traceback
fcfa801
+            traceback.print_exc()