SysMembarrier.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/portability/SysMembarrier.h>
  17. #include <mutex>
  18. #include <folly/Portability.h>
  19. #include <folly/portability/SysSyscall.h>
  20. #include <folly/portability/Unistd.h>
  21. #if FOLLY_X64 && !FOLLY_MOBILE && defined(__linux__)
  22. #define FOLLY_USE_SYS_MEMBARRIER 1
  23. #if !defined(__NR_membarrier)
  24. #define __NR_membarrier 324
  25. #endif
  26. #if __has_include(<linux/membarrier.h>)
  27. #include <linux/membarrier.h> // @manual
  28. #else
  29. #define MEMBARRIER_CMD_QUERY 0
  30. #define MEMBARRIER_CMD_SHARED 1
  31. #endif
  32. #endif
  33. namespace folly {
  34. namespace detail {
  35. bool sysMembarrierAvailable() {
  36. if (!kIsLinux) {
  37. return false;
  38. }
  39. #if FOLLY_USE_SYS_MEMBARRIER
  40. auto r = syscall(__NR_membarrier, MEMBARRIER_CMD_QUERY, /* flags = */ 0);
  41. if (r == -1) {
  42. return false;
  43. }
  44. return r & MEMBARRIER_CMD_SHARED;
  45. #else
  46. return false;
  47. #endif
  48. }
  49. int sysMembarrier() {
  50. #if FOLLY_USE_SYS_MEMBARRIER
  51. return syscall(__NR_membarrier, MEMBARRIER_CMD_SHARED, /* flags = */ 0);
  52. #else
  53. return -1;
  54. #endif
  55. }
  56. } // namespace detail
  57. } // namespace folly