alternative.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * alternative runtime patching
  3. * inspired by the x86 version
  4. *
  5. * Copyright (C) 2014 ARM Ltd.
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2 as
  9. * published by the Free Software Foundation.
  10. *
  11. * This program 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 General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #define pr_fmt(fmt) "alternatives: " fmt
  20. #include <linux/init.h>
  21. #include <linux/cpu.h>
  22. #include <asm/cacheflush.h>
  23. #include <asm/alternative.h>
  24. #include <asm/cpufeature.h>
  25. #include <linux/stop_machine.h>
  26. extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
  27. struct alt_region {
  28. struct alt_instr *begin;
  29. struct alt_instr *end;
  30. };
  31. static int __apply_alternatives(void *alt_region)
  32. {
  33. struct alt_instr *alt;
  34. struct alt_region *region = alt_region;
  35. u8 *origptr, *replptr;
  36. for (alt = region->begin; alt < region->end; alt++) {
  37. if (!cpus_have_cap(alt->cpufeature))
  38. continue;
  39. BUG_ON(alt->alt_len != alt->orig_len);
  40. pr_info_once("patching kernel code\n");
  41. origptr = (u8 *)&alt->orig_offset + alt->orig_offset;
  42. replptr = (u8 *)&alt->alt_offset + alt->alt_offset;
  43. memcpy(origptr, replptr, alt->alt_len);
  44. flush_icache_range((uintptr_t)origptr,
  45. (uintptr_t)(origptr + alt->alt_len));
  46. }
  47. return 0;
  48. }
  49. void apply_alternatives_all(void)
  50. {
  51. struct alt_region region = {
  52. .begin = __alt_instructions,
  53. .end = __alt_instructions_end,
  54. };
  55. /* better not try code patching on a live SMP system */
  56. stop_machine(__apply_alternatives, &region, NULL);
  57. }
  58. void apply_alternatives(void *start, size_t length)
  59. {
  60. struct alt_region region = {
  61. .begin = start,
  62. .end = start + length,
  63. };
  64. __apply_alternatives(&region);
  65. }
  66. void free_alternatives_memory(void)
  67. {
  68. free_reserved_area(__alt_instructions, __alt_instructions_end,
  69. 0, "alternatives");
  70. }