You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

80 line
1.9 KiB

  1. /*
  2. * This file is part of the libopencm3 project.
  3. *
  4. * Copyright (C) 2012 Fergus Noble <fergusnoble@gmail.com>
  5. *
  6. * This library is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Lesser General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this library. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <libopencm3/cm3/sync.h>
  20. /* DMB is supported on CM0 */
  21. void __dmb()
  22. {
  23. __asm__ volatile ("dmb");
  24. }
  25. /* Those are defined only on CM3 or CM4 */
  26. #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
  27. uint32_t __ldrex(volatile uint32_t *addr)
  28. {
  29. uint32_t res;
  30. __asm__ volatile ("ldrex %0, [%1]" : "=r" (res) : "r" (addr));
  31. return res;
  32. }
  33. uint32_t __strex(uint32_t val, volatile uint32_t *addr)
  34. {
  35. uint32_t res;
  36. __asm__ volatile ("strex %0, %2, [%1]"
  37. : "=&r" (res) : "r" (addr), "r" (val));
  38. return res;
  39. }
  40. void mutex_lock(mutex_t *m)
  41. {
  42. while (!mutex_trylock(m));
  43. }
  44. /* returns 1 if the lock was acquired */
  45. uint32_t mutex_trylock(mutex_t *m)
  46. {
  47. uint32_t status = 1;
  48. /* If the mutex is unlocked. */
  49. if (__ldrex(m) == MUTEX_UNLOCKED) {
  50. /* Try to lock it. */
  51. status = __strex(MUTEX_LOCKED, m);
  52. }
  53. /* Execute the mysterious Data Memory Barrier instruction! */
  54. __dmb();
  55. /* Did we get the lock? If not then try again
  56. * by calling this function once more. */
  57. return status == 0;
  58. }
  59. void mutex_unlock(mutex_t *m)
  60. {
  61. /* Ensure accesses to protected resource are finished */
  62. __dmb();
  63. /* Free the lock. */
  64. *m = MUTEX_UNLOCKED;
  65. }
  66. #endif