flushb.c 1.9 KB

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