flushb.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * flushb.c --- Hides system-dependent information for both syncing a
  3. * device to disk and to flush any buffers from disk cache.
  4. *
  5. * Copyright (C) 2000 Theodore Ts'o.
  6. *
  7. * %Begin-Header%
  8. * This file may be redistributed under the terms of the GNU Public
  9. * License.
  10. * %End-Header%
  11. */
  12. #include <stdio.h>
  13. #if HAVE_ERRNO_H
  14. #include <errno.h>
  15. #endif
  16. #if HAVE_UNISTD_H
  17. #include <unistd.h>
  18. #endif
  19. #if HAVE_SYS_IOCTL_H
  20. #include <sys/ioctl.h>
  21. #endif
  22. #if HAVE_SYS_MOUNT_H
  23. #include <sys/param.h>
  24. #include <sys/mount.h> /* This may define BLKFLSBUF */
  25. #endif
  26. #include "ext2_fs.h"
  27. #include "ext2fs.h"
  28. /*
  29. * For Linux, define BLKFLSBUF and FDFLUSH if necessary, since
  30. * not all portable header file does so for us. This really should be
  31. * fixed in the glibc header files. (Recent glibcs appear to define
  32. * BLKFLSBUF in sys/mount.h, but FDFLUSH still doesn't seem to be
  33. * defined anywhere portable.) Until then....
  34. */
  35. #ifdef __linux__
  36. #ifndef BLKFLSBUF
  37. #define BLKFLSBUF _IO(0x12,97) /* flush buffer cache */
  38. #endif
  39. #ifndef FDFLUSH
  40. #define FDFLUSH _IO(2,0x4b) /* flush floppy disk */
  41. #endif
  42. #endif
  43. /*
  44. * This function will sync a device/file, and optionally attempt to
  45. * flush the buffer cache. The latter is basically only useful for
  46. * system benchmarks and for torturing systems in burn-in tests. :)
  47. */
  48. errcode_t ext2fs_sync_device(int fd, int flushb)
  49. {
  50. /*
  51. * We always sync the device in case we're running on old
  52. * kernels for which we can lose data if we don't. (There
  53. * still is a race condition for those kernels, but this
  54. * reduces it greatly.)
  55. */
  56. if (fsync (fd) == -1)
  57. return errno;
  58. if (flushb) {
  59. #ifdef BLKFLSBUF
  60. if (ioctl (fd, BLKFLSBUF, 0) == 0)
  61. return 0;
  62. #else
  63. #ifdef __GNUC__
  64. #warning BLKFLSBUF not defined
  65. #endif /* __GNUC__ */
  66. #endif
  67. #ifdef FDFLUSH
  68. ioctl (fd, FDFLUSH, 0); /* In case this is a floppy */
  69. #else
  70. #ifdef __GNUC__
  71. #warning FDFLUSH not defined
  72. #endif /* __GNUC__ */
  73. #endif
  74. }
  75. return 0;
  76. }