cmpxchg-xchg.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __ASM_SH_CMPXCHG_XCHG_H
  3. #define __ASM_SH_CMPXCHG_XCHG_H
  4. /*
  5. * Copyright (C) 2016 Red Hat, Inc.
  6. * Author: Michael S. Tsirkin <[email protected]>
  7. */
  8. #include <linux/bits.h>
  9. #include <linux/compiler.h>
  10. #include <asm/byteorder.h>
  11. /*
  12. * Portable implementations of 1 and 2 byte xchg using a 4 byte cmpxchg.
  13. * Note: this header isn't self-contained: before including it, __cmpxchg_u32
  14. * must be defined first.
  15. */
  16. static inline u32 __xchg_cmpxchg(volatile void *ptr, u32 x, int size)
  17. {
  18. int off = (unsigned long)ptr % sizeof(u32);
  19. volatile u32 *p = ptr - off;
  20. #ifdef __BIG_ENDIAN
  21. int bitoff = (sizeof(u32) - size - off) * BITS_PER_BYTE;
  22. #else
  23. int bitoff = off * BITS_PER_BYTE;
  24. #endif
  25. u32 bitmask = ((0x1 << size * BITS_PER_BYTE) - 1) << bitoff;
  26. u32 oldv, newv;
  27. u32 ret;
  28. do {
  29. oldv = READ_ONCE(*p);
  30. ret = (oldv & bitmask) >> bitoff;
  31. newv = (oldv & ~bitmask) | (x << bitoff);
  32. } while (__cmpxchg_u32(p, oldv, newv) != oldv);
  33. return ret;
  34. }
  35. static inline unsigned long xchg_u16(volatile u16 *m, unsigned long val)
  36. {
  37. return __xchg_cmpxchg(m, val, sizeof *m);
  38. }
  39. static inline unsigned long xchg_u8(volatile u8 *m, unsigned long val)
  40. {
  41. return __xchg_cmpxchg(m, val, sizeof *m);
  42. }
  43. #endif /* __ASM_SH_CMPXCHG_XCHG_H */