cmpxchg-emu.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Emulated 1-byte cmpxchg operation for architectures lacking direct
  4. * support for this size. This is implemented in terms of 4-byte cmpxchg
  5. * operations.
  6. *
  7. * Copyright (C) 2024 Paul E. McKenney.
  8. */
  9. #include <linux/types.h>
  10. #include <linux/export.h>
  11. #include <linux/instrumented.h>
  12. #include <linux/atomic.h>
  13. #include <linux/panic.h>
  14. #include <linux/bug.h>
  15. #include <asm-generic/rwonce.h>
  16. #include <linux/cmpxchg-emu.h>
  17. union u8_32 {
  18. u8 b[4];
  19. u32 w;
  20. };
  21. /* Emulate one-byte cmpxchg() in terms of 4-byte cmpxchg. */
  22. uintptr_t cmpxchg_emu_u8(volatile u8 *p, uintptr_t old, uintptr_t new)
  23. {
  24. u32 *p32 = (u32 *)(((uintptr_t)p) & ~0x3);
  25. int i = ((uintptr_t)p) & 0x3;
  26. union u8_32 old32;
  27. union u8_32 new32;
  28. u32 ret;
  29. ret = READ_ONCE(*p32);
  30. do {
  31. old32.w = ret;
  32. if (old32.b[i] != old)
  33. return old32.b[i];
  34. new32.w = old32.w;
  35. new32.b[i] = new;
  36. instrument_atomic_read_write(p, 1);
  37. ret = data_race(cmpxchg(p32, old32.w, new32.w)); // Overridden above.
  38. } while (ret != old32.w);
  39. return old;
  40. }
  41. EXPORT_SYMBOL_GPL(cmpxchg_emu_u8);