kfpu.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2023 Loongson Technology Corporation Limited
  4. */
  5. #include <linux/cpu.h>
  6. #include <linux/init.h>
  7. #include <asm/fpu.h>
  8. #include <asm/smp.h>
  9. static unsigned int euen_mask = CSR_EUEN_FPEN;
  10. /*
  11. * The critical section between kernel_fpu_begin() and kernel_fpu_end()
  12. * is non-reentrant. It is the caller's responsibility to avoid reentrance.
  13. * See drivers/gpu/drm/amd/display/amdgpu_dm/dc_fpu.c as an example.
  14. */
  15. static DEFINE_PER_CPU(bool, in_kernel_fpu);
  16. static DEFINE_PER_CPU(unsigned int, euen_current);
  17. static inline void fpregs_lock(void)
  18. {
  19. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  20. preempt_disable();
  21. else
  22. local_bh_disable();
  23. }
  24. static inline void fpregs_unlock(void)
  25. {
  26. if (IS_ENABLED(CONFIG_PREEMPT_RT))
  27. preempt_enable();
  28. else
  29. local_bh_enable();
  30. }
  31. void kernel_fpu_begin(void)
  32. {
  33. unsigned int *euen_curr;
  34. if (!irqs_disabled())
  35. fpregs_lock();
  36. WARN_ON(this_cpu_read(in_kernel_fpu));
  37. this_cpu_write(in_kernel_fpu, true);
  38. euen_curr = this_cpu_ptr(&euen_current);
  39. *euen_curr = csr_xchg32(euen_mask, euen_mask, LOONGARCH_CSR_EUEN);
  40. #ifdef CONFIG_CPU_HAS_LASX
  41. if (*euen_curr & CSR_EUEN_LASXEN)
  42. _save_lasx(&current->thread.fpu);
  43. else
  44. #endif
  45. #ifdef CONFIG_CPU_HAS_LSX
  46. if (*euen_curr & CSR_EUEN_LSXEN)
  47. _save_lsx(&current->thread.fpu);
  48. else
  49. #endif
  50. if (*euen_curr & CSR_EUEN_FPEN)
  51. _save_fp(&current->thread.fpu);
  52. write_fcsr(LOONGARCH_FCSR0, 0);
  53. }
  54. EXPORT_SYMBOL_GPL(kernel_fpu_begin);
  55. void kernel_fpu_end(void)
  56. {
  57. unsigned int *euen_curr;
  58. WARN_ON(!this_cpu_read(in_kernel_fpu));
  59. euen_curr = this_cpu_ptr(&euen_current);
  60. #ifdef CONFIG_CPU_HAS_LASX
  61. if (*euen_curr & CSR_EUEN_LASXEN)
  62. _restore_lasx(&current->thread.fpu);
  63. else
  64. #endif
  65. #ifdef CONFIG_CPU_HAS_LSX
  66. if (*euen_curr & CSR_EUEN_LSXEN)
  67. _restore_lsx(&current->thread.fpu);
  68. else
  69. #endif
  70. if (*euen_curr & CSR_EUEN_FPEN)
  71. _restore_fp(&current->thread.fpu);
  72. *euen_curr = csr_xchg32(*euen_curr, euen_mask, LOONGARCH_CSR_EUEN);
  73. this_cpu_write(in_kernel_fpu, false);
  74. if (!irqs_disabled())
  75. fpregs_unlock();
  76. }
  77. EXPORT_SYMBOL_GPL(kernel_fpu_end);
  78. static int __init init_euen_mask(void)
  79. {
  80. if (cpu_has_lsx)
  81. euen_mask |= CSR_EUEN_LSXEN;
  82. if (cpu_has_lasx)
  83. euen_mask |= CSR_EUEN_LASXEN;
  84. return 0;
  85. }
  86. arch_initcall(init_euen_mask);