alternative.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #define pr_fmt(fmt) "SMP alternatives: " fmt
  3. #include <linux/module.h>
  4. #include <linux/sched.h>
  5. #include <linux/perf_event.h>
  6. #include <linux/mutex.h>
  7. #include <linux/list.h>
  8. #include <linux/stringify.h>
  9. #include <linux/highmem.h>
  10. #include <linux/mm.h>
  11. #include <linux/vmalloc.h>
  12. #include <linux/memory.h>
  13. #include <linux/stop_machine.h>
  14. #include <linux/slab.h>
  15. #include <linux/kdebug.h>
  16. #include <linux/kprobes.h>
  17. #include <linux/mmu_context.h>
  18. #include <linux/bsearch.h>
  19. #include <linux/sync_core.h>
  20. #include <asm/text-patching.h>
  21. #include <asm/alternative.h>
  22. #include <asm/sections.h>
  23. #include <asm/mce.h>
  24. #include <asm/nmi.h>
  25. #include <asm/cacheflush.h>
  26. #include <asm/tlbflush.h>
  27. #include <asm/insn.h>
  28. #include <asm/io.h>
  29. #include <asm/fixmap.h>
  30. #include <asm/paravirt.h>
  31. #include <asm/asm-prototypes.h>
  32. int __read_mostly alternatives_patched;
  33. EXPORT_SYMBOL_GPL(alternatives_patched);
  34. #define MAX_PATCH_LEN (255-1)
  35. static int __initdata_or_module debug_alternative;
  36. static int __init debug_alt(char *str)
  37. {
  38. debug_alternative = 1;
  39. return 1;
  40. }
  41. __setup("debug-alternative", debug_alt);
  42. static int noreplace_smp;
  43. static int __init setup_noreplace_smp(char *str)
  44. {
  45. noreplace_smp = 1;
  46. return 1;
  47. }
  48. __setup("noreplace-smp", setup_noreplace_smp);
  49. #define DPRINTK(fmt, args...) \
  50. do { \
  51. if (debug_alternative) \
  52. printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
  53. } while (0)
  54. #define DUMP_BYTES(buf, len, fmt, args...) \
  55. do { \
  56. if (unlikely(debug_alternative)) { \
  57. int j; \
  58. \
  59. if (!(len)) \
  60. break; \
  61. \
  62. printk(KERN_DEBUG pr_fmt(fmt), ##args); \
  63. for (j = 0; j < (len) - 1; j++) \
  64. printk(KERN_CONT "%02hhx ", buf[j]); \
  65. printk(KERN_CONT "%02hhx\n", buf[j]); \
  66. } \
  67. } while (0)
  68. static const unsigned char x86nops[] =
  69. {
  70. BYTES_NOP1,
  71. BYTES_NOP2,
  72. BYTES_NOP3,
  73. BYTES_NOP4,
  74. BYTES_NOP5,
  75. BYTES_NOP6,
  76. BYTES_NOP7,
  77. BYTES_NOP8,
  78. };
  79. const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
  80. {
  81. NULL,
  82. x86nops,
  83. x86nops + 1,
  84. x86nops + 1 + 2,
  85. x86nops + 1 + 2 + 3,
  86. x86nops + 1 + 2 + 3 + 4,
  87. x86nops + 1 + 2 + 3 + 4 + 5,
  88. x86nops + 1 + 2 + 3 + 4 + 5 + 6,
  89. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
  90. };
  91. /* Use this to add nops to a buffer, then text_poke the whole buffer. */
  92. static void __init_or_module add_nops(void *insns, unsigned int len)
  93. {
  94. while (len > 0) {
  95. unsigned int noplen = len;
  96. if (noplen > ASM_NOP_MAX)
  97. noplen = ASM_NOP_MAX;
  98. memcpy(insns, x86_nops[noplen], noplen);
  99. insns += noplen;
  100. len -= noplen;
  101. }
  102. }
  103. extern s32 __retpoline_sites[], __retpoline_sites_end[];
  104. extern s32 __return_sites[], __return_sites_end[];
  105. extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[];
  106. extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
  107. extern s32 __smp_locks[], __smp_locks_end[];
  108. void text_poke_early(void *addr, const void *opcode, size_t len);
  109. /*
  110. * Are we looking at a near JMP with a 1 or 4-byte displacement.
  111. */
  112. static inline bool is_jmp(const u8 opcode)
  113. {
  114. return opcode == 0xeb || opcode == 0xe9;
  115. }
  116. static void __init_or_module
  117. recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
  118. {
  119. u8 *next_rip, *tgt_rip;
  120. s32 n_dspl, o_dspl;
  121. int repl_len;
  122. if (a->replacementlen != 5)
  123. return;
  124. o_dspl = *(s32 *)(insn_buff + 1);
  125. /* next_rip of the replacement JMP */
  126. next_rip = repl_insn + a->replacementlen;
  127. /* target rip of the replacement JMP */
  128. tgt_rip = next_rip + o_dspl;
  129. n_dspl = tgt_rip - orig_insn;
  130. DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
  131. if (tgt_rip - orig_insn >= 0) {
  132. if (n_dspl - 2 <= 127)
  133. goto two_byte_jmp;
  134. else
  135. goto five_byte_jmp;
  136. /* negative offset */
  137. } else {
  138. if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
  139. goto two_byte_jmp;
  140. else
  141. goto five_byte_jmp;
  142. }
  143. two_byte_jmp:
  144. n_dspl -= 2;
  145. insn_buff[0] = 0xeb;
  146. insn_buff[1] = (s8)n_dspl;
  147. add_nops(insn_buff + 2, 3);
  148. repl_len = 2;
  149. goto done;
  150. five_byte_jmp:
  151. n_dspl -= 5;
  152. insn_buff[0] = 0xe9;
  153. *(s32 *)&insn_buff[1] = n_dspl;
  154. repl_len = 5;
  155. done:
  156. DPRINTK("final displ: 0x%08x, JMP 0x%lx",
  157. n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
  158. }
  159. /*
  160. * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
  161. *
  162. * @instr: instruction byte stream
  163. * @instrlen: length of the above
  164. * @off: offset within @instr where the first NOP has been detected
  165. *
  166. * Return: number of NOPs found (and replaced).
  167. */
  168. static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
  169. {
  170. unsigned long flags;
  171. int i = off, nnops;
  172. while (i < instrlen) {
  173. if (instr[i] != 0x90)
  174. break;
  175. i++;
  176. }
  177. nnops = i - off;
  178. if (nnops <= 1)
  179. return nnops;
  180. local_irq_save(flags);
  181. add_nops(instr + off, nnops);
  182. local_irq_restore(flags);
  183. DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
  184. return nnops;
  185. }
  186. /*
  187. * "noinline" to cause control flow change and thus invalidate I$ and
  188. * cause refetch after modification.
  189. */
  190. static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
  191. {
  192. struct insn insn;
  193. int i = 0;
  194. /*
  195. * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
  196. * ones.
  197. */
  198. for (;;) {
  199. if (insn_decode_kernel(&insn, &instr[i]))
  200. return;
  201. /*
  202. * See if this and any potentially following NOPs can be
  203. * optimized.
  204. */
  205. if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
  206. i += optimize_nops_range(instr, len, i);
  207. else
  208. i += insn.length;
  209. if (i >= len)
  210. return;
  211. }
  212. }
  213. /*
  214. * Replace instructions with better alternatives for this CPU type. This runs
  215. * before SMP is initialized to avoid SMP problems with self modifying code.
  216. * This implies that asymmetric systems where APs have less capabilities than
  217. * the boot processor are not handled. Tough. Make sure you disable such
  218. * features by hand.
  219. *
  220. * Marked "noinline" to cause control flow change and thus insn cache
  221. * to refetch changed I$ lines.
  222. */
  223. void __init_or_module noinline apply_alternatives(struct alt_instr *start,
  224. struct alt_instr *end)
  225. {
  226. struct alt_instr *a;
  227. u8 *instr, *replacement;
  228. u8 insn_buff[MAX_PATCH_LEN];
  229. DPRINTK("alt table %px, -> %px", start, end);
  230. /*
  231. * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
  232. * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
  233. * During the process, KASAN becomes confused seeing partial LA57
  234. * conversion and triggers a false-positive out-of-bound report.
  235. *
  236. * Disable KASAN until the patching is complete.
  237. */
  238. kasan_disable_current();
  239. /*
  240. * The scan order should be from start to end. A later scanned
  241. * alternative code can overwrite previously scanned alternative code.
  242. * Some kernel functions (e.g. memcpy, memset, etc) use this order to
  243. * patch code.
  244. *
  245. * So be careful if you want to change the scan order to any other
  246. * order.
  247. */
  248. for (a = start; a < end; a++) {
  249. int insn_buff_sz = 0;
  250. /* Mask away "NOT" flag bit for feature to test. */
  251. u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
  252. instr = (u8 *)&a->instr_offset + a->instr_offset;
  253. replacement = (u8 *)&a->repl_offset + a->repl_offset;
  254. BUG_ON(a->instrlen > sizeof(insn_buff));
  255. BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
  256. /*
  257. * Patch if either:
  258. * - feature is present
  259. * - feature not present but ALTINSTR_FLAG_INV is set to mean,
  260. * patch if feature is *NOT* present.
  261. */
  262. if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
  263. goto next;
  264. DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
  265. (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
  266. feature >> 5,
  267. feature & 0x1f,
  268. instr, instr, a->instrlen,
  269. replacement, a->replacementlen);
  270. DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
  271. DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
  272. memcpy(insn_buff, replacement, a->replacementlen);
  273. insn_buff_sz = a->replacementlen;
  274. /*
  275. * 0xe8 is a relative jump; fix the offset.
  276. *
  277. * Instruction length is checked before the opcode to avoid
  278. * accessing uninitialized bytes for zero-length replacements.
  279. */
  280. if (a->replacementlen == 5 && *insn_buff == 0xe8) {
  281. *(s32 *)(insn_buff + 1) += replacement - instr;
  282. DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
  283. *(s32 *)(insn_buff + 1),
  284. (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
  285. }
  286. if (a->replacementlen && is_jmp(replacement[0]))
  287. recompute_jump(a, instr, replacement, insn_buff);
  288. for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
  289. insn_buff[insn_buff_sz] = 0x90;
  290. DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
  291. text_poke_early(instr, insn_buff, insn_buff_sz);
  292. next:
  293. optimize_nops(instr, a->instrlen);
  294. }
  295. kasan_enable_current();
  296. }
  297. static inline bool is_jcc32(struct insn *insn)
  298. {
  299. /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
  300. return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
  301. }
  302. #if defined(CONFIG_RETPOLINE) && defined(CONFIG_OBJTOOL)
  303. /*
  304. * CALL/JMP *%\reg
  305. */
  306. static int emit_indirect(int op, int reg, u8 *bytes)
  307. {
  308. int i = 0;
  309. u8 modrm;
  310. switch (op) {
  311. case CALL_INSN_OPCODE:
  312. modrm = 0x10; /* Reg = 2; CALL r/m */
  313. break;
  314. case JMP32_INSN_OPCODE:
  315. modrm = 0x20; /* Reg = 4; JMP r/m */
  316. break;
  317. default:
  318. WARN_ON_ONCE(1);
  319. return -1;
  320. }
  321. if (reg >= 8) {
  322. bytes[i++] = 0x41; /* REX.B prefix */
  323. reg -= 8;
  324. }
  325. modrm |= 0xc0; /* Mod = 3 */
  326. modrm += reg;
  327. bytes[i++] = 0xff; /* opcode */
  328. bytes[i++] = modrm;
  329. return i;
  330. }
  331. /*
  332. * Rewrite the compiler generated retpoline thunk calls.
  333. *
  334. * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
  335. * indirect instructions, avoiding the extra indirection.
  336. *
  337. * For example, convert:
  338. *
  339. * CALL __x86_indirect_thunk_\reg
  340. *
  341. * into:
  342. *
  343. * CALL *%\reg
  344. *
  345. * It also tries to inline spectre_v2=retpoline,lfence when size permits.
  346. */
  347. static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
  348. {
  349. retpoline_thunk_t *target;
  350. int reg, ret, i = 0;
  351. u8 op, cc;
  352. target = addr + insn->length + insn->immediate.value;
  353. reg = target - __x86_indirect_thunk_array;
  354. if (WARN_ON_ONCE(reg & ~0xf))
  355. return -1;
  356. /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
  357. BUG_ON(reg == 4);
  358. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
  359. !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
  360. return -1;
  361. op = insn->opcode.bytes[0];
  362. /*
  363. * Convert:
  364. *
  365. * Jcc.d32 __x86_indirect_thunk_\reg
  366. *
  367. * into:
  368. *
  369. * Jncc.d8 1f
  370. * [ LFENCE ]
  371. * JMP *%\reg
  372. * [ NOP ]
  373. * 1:
  374. */
  375. if (is_jcc32(insn)) {
  376. cc = insn->opcode.bytes[1] & 0xf;
  377. cc ^= 1; /* invert condition */
  378. bytes[i++] = 0x70 + cc; /* Jcc.d8 */
  379. bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
  380. /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
  381. op = JMP32_INSN_OPCODE;
  382. }
  383. /*
  384. * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
  385. */
  386. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
  387. bytes[i++] = 0x0f;
  388. bytes[i++] = 0xae;
  389. bytes[i++] = 0xe8; /* LFENCE */
  390. }
  391. ret = emit_indirect(op, reg, bytes + i);
  392. if (ret < 0)
  393. return ret;
  394. i += ret;
  395. /*
  396. * The compiler is supposed to EMIT an INT3 after every unconditional
  397. * JMP instruction due to AMD BTC. However, if the compiler is too old
  398. * or SLS isn't enabled, we still need an INT3 after indirect JMPs
  399. * even on Intel.
  400. */
  401. if (op == JMP32_INSN_OPCODE && i < insn->length)
  402. bytes[i++] = INT3_INSN_OPCODE;
  403. for (; i < insn->length;)
  404. bytes[i++] = BYTES_NOP1;
  405. return i;
  406. }
  407. /*
  408. * Generated by 'objtool --retpoline'.
  409. */
  410. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
  411. {
  412. s32 *s;
  413. for (s = start; s < end; s++) {
  414. void *addr = (void *)s + *s;
  415. struct insn insn;
  416. int len, ret;
  417. u8 bytes[16];
  418. u8 op1, op2;
  419. ret = insn_decode_kernel(&insn, addr);
  420. if (WARN_ON_ONCE(ret < 0))
  421. continue;
  422. op1 = insn.opcode.bytes[0];
  423. op2 = insn.opcode.bytes[1];
  424. switch (op1) {
  425. case CALL_INSN_OPCODE:
  426. case JMP32_INSN_OPCODE:
  427. break;
  428. case 0x0f: /* escape */
  429. if (op2 >= 0x80 && op2 <= 0x8f)
  430. break;
  431. fallthrough;
  432. default:
  433. WARN_ON_ONCE(1);
  434. continue;
  435. }
  436. DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
  437. addr, addr, insn.length,
  438. addr + insn.length + insn.immediate.value);
  439. len = patch_retpoline(addr, &insn, bytes);
  440. if (len == insn.length) {
  441. optimize_nops(bytes, len);
  442. DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
  443. DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
  444. text_poke_early(addr, bytes, len);
  445. }
  446. }
  447. }
  448. #ifdef CONFIG_RETHUNK
  449. /*
  450. * Rewrite the compiler generated return thunk tail-calls.
  451. *
  452. * For example, convert:
  453. *
  454. * JMP __x86_return_thunk
  455. *
  456. * into:
  457. *
  458. * RET
  459. */
  460. static int patch_return(void *addr, struct insn *insn, u8 *bytes)
  461. {
  462. int i = 0;
  463. if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
  464. return -1;
  465. bytes[i++] = RET_INSN_OPCODE;
  466. for (; i < insn->length;)
  467. bytes[i++] = INT3_INSN_OPCODE;
  468. return i;
  469. }
  470. void __init_or_module noinline apply_returns(s32 *start, s32 *end)
  471. {
  472. s32 *s;
  473. for (s = start; s < end; s++) {
  474. void *dest = NULL, *addr = (void *)s + *s;
  475. struct insn insn;
  476. int len, ret;
  477. u8 bytes[16];
  478. u8 op;
  479. ret = insn_decode_kernel(&insn, addr);
  480. if (WARN_ON_ONCE(ret < 0))
  481. continue;
  482. op = insn.opcode.bytes[0];
  483. if (op == JMP32_INSN_OPCODE)
  484. dest = addr + insn.length + insn.immediate.value;
  485. if (__static_call_fixup(addr, op, dest) ||
  486. WARN_ONCE(dest != &__x86_return_thunk,
  487. "missing return thunk: %pS-%pS: %*ph",
  488. addr, dest, 5, addr))
  489. continue;
  490. DPRINTK("return thunk at: %pS (%px) len: %d to: %pS",
  491. addr, addr, insn.length,
  492. addr + insn.length + insn.immediate.value);
  493. len = patch_return(addr, &insn, bytes);
  494. if (len == insn.length) {
  495. DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
  496. DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
  497. text_poke_early(addr, bytes, len);
  498. }
  499. }
  500. }
  501. #else
  502. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  503. #endif /* CONFIG_RETHUNK */
  504. #else /* !CONFIG_RETPOLINE || !CONFIG_OBJTOOL */
  505. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
  506. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  507. #endif /* CONFIG_RETPOLINE && CONFIG_OBJTOOL */
  508. #ifdef CONFIG_X86_KERNEL_IBT
  509. /*
  510. * Generated by: objtool --ibt
  511. */
  512. void __init_or_module noinline apply_ibt_endbr(s32 *start, s32 *end)
  513. {
  514. s32 *s;
  515. for (s = start; s < end; s++) {
  516. u32 endbr, poison = gen_endbr_poison();
  517. void *addr = (void *)s + *s;
  518. if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr)))
  519. continue;
  520. if (WARN_ON_ONCE(!is_endbr(endbr)))
  521. continue;
  522. DPRINTK("ENDBR at: %pS (%px)", addr, addr);
  523. /*
  524. * When we have IBT, the lack of ENDBR will trigger #CP
  525. */
  526. DUMP_BYTES(((u8*)addr), 4, "%px: orig: ", addr);
  527. DUMP_BYTES(((u8*)&poison), 4, "%px: repl: ", addr);
  528. text_poke_early(addr, &poison, 4);
  529. }
  530. }
  531. #else
  532. void __init_or_module noinline apply_ibt_endbr(s32 *start, s32 *end) { }
  533. #endif /* CONFIG_X86_KERNEL_IBT */
  534. #ifdef CONFIG_SMP
  535. static void alternatives_smp_lock(const s32 *start, const s32 *end,
  536. u8 *text, u8 *text_end)
  537. {
  538. const s32 *poff;
  539. for (poff = start; poff < end; poff++) {
  540. u8 *ptr = (u8 *)poff + *poff;
  541. if (!*poff || ptr < text || ptr >= text_end)
  542. continue;
  543. /* turn DS segment override prefix into lock prefix */
  544. if (*ptr == 0x3e)
  545. text_poke(ptr, ((unsigned char []){0xf0}), 1);
  546. }
  547. }
  548. static void alternatives_smp_unlock(const s32 *start, const s32 *end,
  549. u8 *text, u8 *text_end)
  550. {
  551. const s32 *poff;
  552. for (poff = start; poff < end; poff++) {
  553. u8 *ptr = (u8 *)poff + *poff;
  554. if (!*poff || ptr < text || ptr >= text_end)
  555. continue;
  556. /* turn lock prefix into DS segment override prefix */
  557. if (*ptr == 0xf0)
  558. text_poke(ptr, ((unsigned char []){0x3E}), 1);
  559. }
  560. }
  561. struct smp_alt_module {
  562. /* what is this ??? */
  563. struct module *mod;
  564. char *name;
  565. /* ptrs to lock prefixes */
  566. const s32 *locks;
  567. const s32 *locks_end;
  568. /* .text segment, needed to avoid patching init code ;) */
  569. u8 *text;
  570. u8 *text_end;
  571. struct list_head next;
  572. };
  573. static LIST_HEAD(smp_alt_modules);
  574. static bool uniproc_patched = false; /* protected by text_mutex */
  575. void __init_or_module alternatives_smp_module_add(struct module *mod,
  576. char *name,
  577. void *locks, void *locks_end,
  578. void *text, void *text_end)
  579. {
  580. struct smp_alt_module *smp;
  581. mutex_lock(&text_mutex);
  582. if (!uniproc_patched)
  583. goto unlock;
  584. if (num_possible_cpus() == 1)
  585. /* Don't bother remembering, we'll never have to undo it. */
  586. goto smp_unlock;
  587. smp = kzalloc(sizeof(*smp), GFP_KERNEL);
  588. if (NULL == smp)
  589. /* we'll run the (safe but slow) SMP code then ... */
  590. goto unlock;
  591. smp->mod = mod;
  592. smp->name = name;
  593. smp->locks = locks;
  594. smp->locks_end = locks_end;
  595. smp->text = text;
  596. smp->text_end = text_end;
  597. DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
  598. smp->locks, smp->locks_end,
  599. smp->text, smp->text_end, smp->name);
  600. list_add_tail(&smp->next, &smp_alt_modules);
  601. smp_unlock:
  602. alternatives_smp_unlock(locks, locks_end, text, text_end);
  603. unlock:
  604. mutex_unlock(&text_mutex);
  605. }
  606. void __init_or_module alternatives_smp_module_del(struct module *mod)
  607. {
  608. struct smp_alt_module *item;
  609. mutex_lock(&text_mutex);
  610. list_for_each_entry(item, &smp_alt_modules, next) {
  611. if (mod != item->mod)
  612. continue;
  613. list_del(&item->next);
  614. kfree(item);
  615. break;
  616. }
  617. mutex_unlock(&text_mutex);
  618. }
  619. void alternatives_enable_smp(void)
  620. {
  621. struct smp_alt_module *mod;
  622. /* Why bother if there are no other CPUs? */
  623. BUG_ON(num_possible_cpus() == 1);
  624. mutex_lock(&text_mutex);
  625. if (uniproc_patched) {
  626. pr_info("switching to SMP code\n");
  627. BUG_ON(num_online_cpus() != 1);
  628. clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
  629. clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
  630. list_for_each_entry(mod, &smp_alt_modules, next)
  631. alternatives_smp_lock(mod->locks, mod->locks_end,
  632. mod->text, mod->text_end);
  633. uniproc_patched = false;
  634. }
  635. mutex_unlock(&text_mutex);
  636. }
  637. /*
  638. * Return 1 if the address range is reserved for SMP-alternatives.
  639. * Must hold text_mutex.
  640. */
  641. int alternatives_text_reserved(void *start, void *end)
  642. {
  643. struct smp_alt_module *mod;
  644. const s32 *poff;
  645. u8 *text_start = start;
  646. u8 *text_end = end;
  647. lockdep_assert_held(&text_mutex);
  648. list_for_each_entry(mod, &smp_alt_modules, next) {
  649. if (mod->text > text_end || mod->text_end < text_start)
  650. continue;
  651. for (poff = mod->locks; poff < mod->locks_end; poff++) {
  652. const u8 *ptr = (const u8 *)poff + *poff;
  653. if (text_start <= ptr && text_end > ptr)
  654. return 1;
  655. }
  656. }
  657. return 0;
  658. }
  659. #endif /* CONFIG_SMP */
  660. #ifdef CONFIG_PARAVIRT
  661. void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
  662. struct paravirt_patch_site *end)
  663. {
  664. struct paravirt_patch_site *p;
  665. char insn_buff[MAX_PATCH_LEN];
  666. for (p = start; p < end; p++) {
  667. unsigned int used;
  668. BUG_ON(p->len > MAX_PATCH_LEN);
  669. /* prep the buffer with the original instructions */
  670. memcpy(insn_buff, p->instr, p->len);
  671. used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
  672. BUG_ON(used > p->len);
  673. /* Pad the rest with nops */
  674. add_nops(insn_buff + used, p->len - used);
  675. text_poke_early(p->instr, insn_buff, p->len);
  676. }
  677. }
  678. extern struct paravirt_patch_site __start_parainstructions[],
  679. __stop_parainstructions[];
  680. #endif /* CONFIG_PARAVIRT */
  681. /*
  682. * Self-test for the INT3 based CALL emulation code.
  683. *
  684. * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
  685. * properly and that there is a stack gap between the INT3 frame and the
  686. * previous context. Without this gap doing a virtual PUSH on the interrupted
  687. * stack would corrupt the INT3 IRET frame.
  688. *
  689. * See entry_{32,64}.S for more details.
  690. */
  691. /*
  692. * We define the int3_magic() function in assembly to control the calling
  693. * convention such that we can 'call' it from assembly.
  694. */
  695. extern void int3_magic(unsigned int *ptr); /* defined in asm */
  696. asm (
  697. " .pushsection .init.text, \"ax\", @progbits\n"
  698. " .type int3_magic, @function\n"
  699. "int3_magic:\n"
  700. ANNOTATE_NOENDBR
  701. " movl $1, (%" _ASM_ARG1 ")\n"
  702. ASM_RET
  703. " .size int3_magic, .-int3_magic\n"
  704. " .popsection\n"
  705. );
  706. extern void int3_selftest_ip(void); /* defined in asm below */
  707. static int __init
  708. int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
  709. {
  710. unsigned long selftest = (unsigned long)&int3_selftest_ip;
  711. struct die_args *args = data;
  712. struct pt_regs *regs = args->regs;
  713. OPTIMIZER_HIDE_VAR(selftest);
  714. if (!regs || user_mode(regs))
  715. return NOTIFY_DONE;
  716. if (val != DIE_INT3)
  717. return NOTIFY_DONE;
  718. if (regs->ip - INT3_INSN_SIZE != selftest)
  719. return NOTIFY_DONE;
  720. int3_emulate_call(regs, (unsigned long)&int3_magic);
  721. return NOTIFY_STOP;
  722. }
  723. /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
  724. static noinline void __init int3_selftest(void)
  725. {
  726. static __initdata struct notifier_block int3_exception_nb = {
  727. .notifier_call = int3_exception_notify,
  728. .priority = INT_MAX-1, /* last */
  729. };
  730. unsigned int val = 0;
  731. BUG_ON(register_die_notifier(&int3_exception_nb));
  732. /*
  733. * Basically: int3_magic(&val); but really complicated :-)
  734. *
  735. * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
  736. * notifier above will emulate CALL for us.
  737. */
  738. asm volatile ("int3_selftest_ip:\n\t"
  739. ANNOTATE_NOENDBR
  740. " int3; nop; nop; nop; nop\n\t"
  741. : ASM_CALL_CONSTRAINT
  742. : __ASM_SEL_RAW(a, D) (&val)
  743. : "memory");
  744. BUG_ON(val != 1);
  745. unregister_die_notifier(&int3_exception_nb);
  746. }
  747. void __init alternative_instructions(void)
  748. {
  749. int3_selftest();
  750. /*
  751. * The patching is not fully atomic, so try to avoid local
  752. * interruptions that might execute the to be patched code.
  753. * Other CPUs are not running.
  754. */
  755. stop_nmi();
  756. /*
  757. * Don't stop machine check exceptions while patching.
  758. * MCEs only happen when something got corrupted and in this
  759. * case we must do something about the corruption.
  760. * Ignoring it is worse than an unlikely patching race.
  761. * Also machine checks tend to be broadcast and if one CPU
  762. * goes into machine check the others follow quickly, so we don't
  763. * expect a machine check to cause undue problems during to code
  764. * patching.
  765. */
  766. /*
  767. * Paravirt patching and alternative patching can be combined to
  768. * replace a function call with a short direct code sequence (e.g.
  769. * by setting a constant return value instead of doing that in an
  770. * external function).
  771. * In order to make this work the following sequence is required:
  772. * 1. set (artificial) features depending on used paravirt
  773. * functions which can later influence alternative patching
  774. * 2. apply paravirt patching (generally replacing an indirect
  775. * function call with a direct one)
  776. * 3. apply alternative patching (e.g. replacing a direct function
  777. * call with a custom code sequence)
  778. * Doing paravirt patching after alternative patching would clobber
  779. * the optimization of the custom code with a function call again.
  780. */
  781. paravirt_set_cap();
  782. /*
  783. * First patch paravirt functions, such that we overwrite the indirect
  784. * call with the direct call.
  785. */
  786. apply_paravirt(__parainstructions, __parainstructions_end);
  787. /*
  788. * Rewrite the retpolines, must be done before alternatives since
  789. * those can rewrite the retpoline thunks.
  790. */
  791. apply_retpolines(__retpoline_sites, __retpoline_sites_end);
  792. apply_returns(__return_sites, __return_sites_end);
  793. /*
  794. * Then patch alternatives, such that those paravirt calls that are in
  795. * alternatives can be overwritten by their immediate fragments.
  796. */
  797. apply_alternatives(__alt_instructions, __alt_instructions_end);
  798. apply_ibt_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
  799. #ifdef CONFIG_SMP
  800. /* Patch to UP if other cpus not imminent. */
  801. if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
  802. uniproc_patched = true;
  803. alternatives_smp_module_add(NULL, "core kernel",
  804. __smp_locks, __smp_locks_end,
  805. _text, _etext);
  806. }
  807. if (!uniproc_patched || num_possible_cpus() == 1) {
  808. free_init_pages("SMP alternatives",
  809. (unsigned long)__smp_locks,
  810. (unsigned long)__smp_locks_end);
  811. }
  812. #endif
  813. restart_nmi();
  814. alternatives_patched = 1;
  815. }
  816. /**
  817. * text_poke_early - Update instructions on a live kernel at boot time
  818. * @addr: address to modify
  819. * @opcode: source of the copy
  820. * @len: length to copy
  821. *
  822. * When you use this code to patch more than one byte of an instruction
  823. * you need to make sure that other CPUs cannot execute this code in parallel.
  824. * Also no thread must be currently preempted in the middle of these
  825. * instructions. And on the local CPU you need to be protected against NMI or
  826. * MCE handlers seeing an inconsistent instruction while you patch.
  827. */
  828. void __init_or_module text_poke_early(void *addr, const void *opcode,
  829. size_t len)
  830. {
  831. unsigned long flags;
  832. if (boot_cpu_has(X86_FEATURE_NX) &&
  833. is_module_text_address((unsigned long)addr)) {
  834. /*
  835. * Modules text is marked initially as non-executable, so the
  836. * code cannot be running and speculative code-fetches are
  837. * prevented. Just change the code.
  838. */
  839. memcpy(addr, opcode, len);
  840. } else {
  841. local_irq_save(flags);
  842. memcpy(addr, opcode, len);
  843. local_irq_restore(flags);
  844. sync_core();
  845. /*
  846. * Could also do a CLFLUSH here to speed up CPU recovery; but
  847. * that causes hangs on some VIA CPUs.
  848. */
  849. }
  850. }
  851. typedef struct {
  852. struct mm_struct *mm;
  853. } temp_mm_state_t;
  854. /*
  855. * Using a temporary mm allows to set temporary mappings that are not accessible
  856. * by other CPUs. Such mappings are needed to perform sensitive memory writes
  857. * that override the kernel memory protections (e.g., W^X), without exposing the
  858. * temporary page-table mappings that are required for these write operations to
  859. * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
  860. * mapping is torn down.
  861. *
  862. * Context: The temporary mm needs to be used exclusively by a single core. To
  863. * harden security IRQs must be disabled while the temporary mm is
  864. * loaded, thereby preventing interrupt handler bugs from overriding
  865. * the kernel memory protection.
  866. */
  867. static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
  868. {
  869. temp_mm_state_t temp_state;
  870. lockdep_assert_irqs_disabled();
  871. /*
  872. * Make sure not to be in TLB lazy mode, as otherwise we'll end up
  873. * with a stale address space WITHOUT being in lazy mode after
  874. * restoring the previous mm.
  875. */
  876. if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
  877. leave_mm(smp_processor_id());
  878. temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
  879. switch_mm_irqs_off(NULL, mm, current);
  880. /*
  881. * If breakpoints are enabled, disable them while the temporary mm is
  882. * used. Userspace might set up watchpoints on addresses that are used
  883. * in the temporary mm, which would lead to wrong signals being sent or
  884. * crashes.
  885. *
  886. * Note that breakpoints are not disabled selectively, which also causes
  887. * kernel breakpoints (e.g., perf's) to be disabled. This might be
  888. * undesirable, but still seems reasonable as the code that runs in the
  889. * temporary mm should be short.
  890. */
  891. if (hw_breakpoint_active())
  892. hw_breakpoint_disable();
  893. return temp_state;
  894. }
  895. static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
  896. {
  897. lockdep_assert_irqs_disabled();
  898. switch_mm_irqs_off(NULL, prev_state.mm, current);
  899. /*
  900. * Restore the breakpoints if they were disabled before the temporary mm
  901. * was loaded.
  902. */
  903. if (hw_breakpoint_active())
  904. hw_breakpoint_restore();
  905. }
  906. __ro_after_init struct mm_struct *poking_mm;
  907. __ro_after_init unsigned long poking_addr;
  908. static void text_poke_memcpy(void *dst, const void *src, size_t len)
  909. {
  910. memcpy(dst, src, len);
  911. }
  912. static void text_poke_memset(void *dst, const void *src, size_t len)
  913. {
  914. int c = *(const int *)src;
  915. memset(dst, c, len);
  916. }
  917. typedef void text_poke_f(void *dst, const void *src, size_t len);
  918. static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
  919. {
  920. bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
  921. struct page *pages[2] = {NULL};
  922. temp_mm_state_t prev;
  923. unsigned long flags;
  924. pte_t pte, *ptep;
  925. spinlock_t *ptl;
  926. pgprot_t pgprot;
  927. /*
  928. * While boot memory allocator is running we cannot use struct pages as
  929. * they are not yet initialized. There is no way to recover.
  930. */
  931. BUG_ON(!after_bootmem);
  932. if (!core_kernel_text((unsigned long)addr)) {
  933. pages[0] = vmalloc_to_page(addr);
  934. if (cross_page_boundary)
  935. pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
  936. } else {
  937. pages[0] = virt_to_page(addr);
  938. WARN_ON(!PageReserved(pages[0]));
  939. if (cross_page_boundary)
  940. pages[1] = virt_to_page(addr + PAGE_SIZE);
  941. }
  942. /*
  943. * If something went wrong, crash and burn since recovery paths are not
  944. * implemented.
  945. */
  946. BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
  947. /*
  948. * Map the page without the global bit, as TLB flushing is done with
  949. * flush_tlb_mm_range(), which is intended for non-global PTEs.
  950. */
  951. pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
  952. /*
  953. * The lock is not really needed, but this allows to avoid open-coding.
  954. */
  955. ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
  956. /*
  957. * This must not fail; preallocated in poking_init().
  958. */
  959. VM_BUG_ON(!ptep);
  960. local_irq_save(flags);
  961. pte = mk_pte(pages[0], pgprot);
  962. set_pte_at(poking_mm, poking_addr, ptep, pte);
  963. if (cross_page_boundary) {
  964. pte = mk_pte(pages[1], pgprot);
  965. set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
  966. }
  967. /*
  968. * Loading the temporary mm behaves as a compiler barrier, which
  969. * guarantees that the PTE will be set at the time memcpy() is done.
  970. */
  971. prev = use_temporary_mm(poking_mm);
  972. kasan_disable_current();
  973. func((u8 *)poking_addr + offset_in_page(addr), src, len);
  974. kasan_enable_current();
  975. /*
  976. * Ensure that the PTE is only cleared after the instructions of memcpy
  977. * were issued by using a compiler barrier.
  978. */
  979. barrier();
  980. pte_clear(poking_mm, poking_addr, ptep);
  981. if (cross_page_boundary)
  982. pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
  983. /*
  984. * Loading the previous page-table hierarchy requires a serializing
  985. * instruction that already allows the core to see the updated version.
  986. * Xen-PV is assumed to serialize execution in a similar manner.
  987. */
  988. unuse_temporary_mm(prev);
  989. /*
  990. * Flushing the TLB might involve IPIs, which would require enabled
  991. * IRQs, but not if the mm is not used, as it is in this point.
  992. */
  993. flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
  994. (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
  995. PAGE_SHIFT, false);
  996. if (func == text_poke_memcpy) {
  997. /*
  998. * If the text does not match what we just wrote then something is
  999. * fundamentally screwy; there's nothing we can really do about that.
  1000. */
  1001. BUG_ON(memcmp(addr, src, len));
  1002. }
  1003. local_irq_restore(flags);
  1004. pte_unmap_unlock(ptep, ptl);
  1005. return addr;
  1006. }
  1007. /**
  1008. * text_poke - Update instructions on a live kernel
  1009. * @addr: address to modify
  1010. * @opcode: source of the copy
  1011. * @len: length to copy
  1012. *
  1013. * Only atomic text poke/set should be allowed when not doing early patching.
  1014. * It means the size must be writable atomically and the address must be aligned
  1015. * in a way that permits an atomic write. It also makes sure we fit on a single
  1016. * page.
  1017. *
  1018. * Note that the caller must ensure that if the modified code is part of a
  1019. * module, the module would not be removed during poking. This can be achieved
  1020. * by registering a module notifier, and ordering module removal and patching
  1021. * trough a mutex.
  1022. */
  1023. void *text_poke(void *addr, const void *opcode, size_t len)
  1024. {
  1025. lockdep_assert_held(&text_mutex);
  1026. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1027. }
  1028. /**
  1029. * text_poke_kgdb - Update instructions on a live kernel by kgdb
  1030. * @addr: address to modify
  1031. * @opcode: source of the copy
  1032. * @len: length to copy
  1033. *
  1034. * Only atomic text poke/set should be allowed when not doing early patching.
  1035. * It means the size must be writable atomically and the address must be aligned
  1036. * in a way that permits an atomic write. It also makes sure we fit on a single
  1037. * page.
  1038. *
  1039. * Context: should only be used by kgdb, which ensures no other core is running,
  1040. * despite the fact it does not hold the text_mutex.
  1041. */
  1042. void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
  1043. {
  1044. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1045. }
  1046. /**
  1047. * text_poke_copy - Copy instructions into (an unused part of) RX memory
  1048. * @addr: address to modify
  1049. * @opcode: source of the copy
  1050. * @len: length to copy, could be more than 2x PAGE_SIZE
  1051. *
  1052. * Not safe against concurrent execution; useful for JITs to dump
  1053. * new code blocks into unused regions of RX memory. Can be used in
  1054. * conjunction with synchronize_rcu_tasks() to wait for existing
  1055. * execution to quiesce after having made sure no existing functions
  1056. * pointers are live.
  1057. */
  1058. void *text_poke_copy(void *addr, const void *opcode, size_t len)
  1059. {
  1060. unsigned long start = (unsigned long)addr;
  1061. size_t patched = 0;
  1062. if (WARN_ON_ONCE(core_kernel_text(start)))
  1063. return NULL;
  1064. mutex_lock(&text_mutex);
  1065. while (patched < len) {
  1066. unsigned long ptr = start + patched;
  1067. size_t s;
  1068. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1069. __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
  1070. patched += s;
  1071. }
  1072. mutex_unlock(&text_mutex);
  1073. return addr;
  1074. }
  1075. /**
  1076. * text_poke_set - memset into (an unused part of) RX memory
  1077. * @addr: address to modify
  1078. * @c: the byte to fill the area with
  1079. * @len: length to copy, could be more than 2x PAGE_SIZE
  1080. *
  1081. * This is useful to overwrite unused regions of RX memory with illegal
  1082. * instructions.
  1083. */
  1084. void *text_poke_set(void *addr, int c, size_t len)
  1085. {
  1086. unsigned long start = (unsigned long)addr;
  1087. size_t patched = 0;
  1088. if (WARN_ON_ONCE(core_kernel_text(start)))
  1089. return NULL;
  1090. mutex_lock(&text_mutex);
  1091. while (patched < len) {
  1092. unsigned long ptr = start + patched;
  1093. size_t s;
  1094. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1095. __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
  1096. patched += s;
  1097. }
  1098. mutex_unlock(&text_mutex);
  1099. return addr;
  1100. }
  1101. static void do_sync_core(void *info)
  1102. {
  1103. sync_core();
  1104. }
  1105. void text_poke_sync(void)
  1106. {
  1107. on_each_cpu(do_sync_core, NULL, 1);
  1108. }
  1109. /*
  1110. * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
  1111. * this thing. When len == 6 everything is prefixed with 0x0f and we map
  1112. * opcode to Jcc.d8, using len to distinguish.
  1113. */
  1114. struct text_poke_loc {
  1115. /* addr := _stext + rel_addr */
  1116. s32 rel_addr;
  1117. s32 disp;
  1118. u8 len;
  1119. u8 opcode;
  1120. const u8 text[POKE_MAX_OPCODE_SIZE];
  1121. /* see text_poke_bp_batch() */
  1122. u8 old;
  1123. };
  1124. struct bp_patching_desc {
  1125. struct text_poke_loc *vec;
  1126. int nr_entries;
  1127. atomic_t refs;
  1128. };
  1129. static struct bp_patching_desc bp_desc;
  1130. static __always_inline
  1131. struct bp_patching_desc *try_get_desc(void)
  1132. {
  1133. struct bp_patching_desc *desc = &bp_desc;
  1134. if (!arch_atomic_inc_not_zero(&desc->refs))
  1135. return NULL;
  1136. return desc;
  1137. }
  1138. static __always_inline void put_desc(void)
  1139. {
  1140. struct bp_patching_desc *desc = &bp_desc;
  1141. smp_mb__before_atomic();
  1142. arch_atomic_dec(&desc->refs);
  1143. }
  1144. static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
  1145. {
  1146. return _stext + tp->rel_addr;
  1147. }
  1148. static __always_inline int patch_cmp(const void *key, const void *elt)
  1149. {
  1150. struct text_poke_loc *tp = (struct text_poke_loc *) elt;
  1151. if (key < text_poke_addr(tp))
  1152. return -1;
  1153. if (key > text_poke_addr(tp))
  1154. return 1;
  1155. return 0;
  1156. }
  1157. noinstr int poke_int3_handler(struct pt_regs *regs)
  1158. {
  1159. struct bp_patching_desc *desc;
  1160. struct text_poke_loc *tp;
  1161. int ret = 0;
  1162. void *ip;
  1163. if (user_mode(regs))
  1164. return 0;
  1165. /*
  1166. * Having observed our INT3 instruction, we now must observe
  1167. * bp_desc with non-zero refcount:
  1168. *
  1169. * bp_desc.refs = 1 INT3
  1170. * WMB RMB
  1171. * write INT3 if (bp_desc.refs != 0)
  1172. */
  1173. smp_rmb();
  1174. desc = try_get_desc();
  1175. if (!desc)
  1176. return 0;
  1177. /*
  1178. * Discount the INT3. See text_poke_bp_batch().
  1179. */
  1180. ip = (void *) regs->ip - INT3_INSN_SIZE;
  1181. /*
  1182. * Skip the binary search if there is a single member in the vector.
  1183. */
  1184. if (unlikely(desc->nr_entries > 1)) {
  1185. tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
  1186. sizeof(struct text_poke_loc),
  1187. patch_cmp);
  1188. if (!tp)
  1189. goto out_put;
  1190. } else {
  1191. tp = desc->vec;
  1192. if (text_poke_addr(tp) != ip)
  1193. goto out_put;
  1194. }
  1195. ip += tp->len;
  1196. switch (tp->opcode) {
  1197. case INT3_INSN_OPCODE:
  1198. /*
  1199. * Someone poked an explicit INT3, they'll want to handle it,
  1200. * do not consume.
  1201. */
  1202. goto out_put;
  1203. case RET_INSN_OPCODE:
  1204. int3_emulate_ret(regs);
  1205. break;
  1206. case CALL_INSN_OPCODE:
  1207. int3_emulate_call(regs, (long)ip + tp->disp);
  1208. break;
  1209. case JMP32_INSN_OPCODE:
  1210. case JMP8_INSN_OPCODE:
  1211. int3_emulate_jmp(regs, (long)ip + tp->disp);
  1212. break;
  1213. case 0x70 ... 0x7f: /* Jcc */
  1214. int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp);
  1215. break;
  1216. default:
  1217. BUG();
  1218. }
  1219. ret = 1;
  1220. out_put:
  1221. put_desc();
  1222. return ret;
  1223. }
  1224. #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
  1225. static struct text_poke_loc tp_vec[TP_VEC_MAX];
  1226. static int tp_vec_nr;
  1227. /**
  1228. * text_poke_bp_batch() -- update instructions on live kernel on SMP
  1229. * @tp: vector of instructions to patch
  1230. * @nr_entries: number of entries in the vector
  1231. *
  1232. * Modify multi-byte instruction by using int3 breakpoint on SMP.
  1233. * We completely avoid stop_machine() here, and achieve the
  1234. * synchronization using int3 breakpoint.
  1235. *
  1236. * The way it is done:
  1237. * - For each entry in the vector:
  1238. * - add a int3 trap to the address that will be patched
  1239. * - sync cores
  1240. * - For each entry in the vector:
  1241. * - update all but the first byte of the patched range
  1242. * - sync cores
  1243. * - For each entry in the vector:
  1244. * - replace the first byte (int3) by the first byte of
  1245. * replacing opcode
  1246. * - sync cores
  1247. */
  1248. static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
  1249. {
  1250. unsigned char int3 = INT3_INSN_OPCODE;
  1251. unsigned int i;
  1252. int do_sync;
  1253. lockdep_assert_held(&text_mutex);
  1254. bp_desc.vec = tp;
  1255. bp_desc.nr_entries = nr_entries;
  1256. /*
  1257. * Corresponds to the implicit memory barrier in try_get_desc() to
  1258. * ensure reading a non-zero refcount provides up to date bp_desc data.
  1259. */
  1260. atomic_set_release(&bp_desc.refs, 1);
  1261. /*
  1262. * Corresponding read barrier in int3 notifier for making sure the
  1263. * nr_entries and handler are correctly ordered wrt. patching.
  1264. */
  1265. smp_wmb();
  1266. /*
  1267. * First step: add a int3 trap to the address that will be patched.
  1268. */
  1269. for (i = 0; i < nr_entries; i++) {
  1270. tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
  1271. text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
  1272. }
  1273. text_poke_sync();
  1274. /*
  1275. * Second step: update all but the first byte of the patched range.
  1276. */
  1277. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  1278. u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, };
  1279. u8 _new[POKE_MAX_OPCODE_SIZE+1];
  1280. const u8 *new = tp[i].text;
  1281. int len = tp[i].len;
  1282. if (len - INT3_INSN_SIZE > 0) {
  1283. memcpy(old + INT3_INSN_SIZE,
  1284. text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  1285. len - INT3_INSN_SIZE);
  1286. if (len == 6) {
  1287. _new[0] = 0x0f;
  1288. memcpy(_new + 1, new, 5);
  1289. new = _new;
  1290. }
  1291. text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  1292. new + INT3_INSN_SIZE,
  1293. len - INT3_INSN_SIZE);
  1294. do_sync++;
  1295. }
  1296. /*
  1297. * Emit a perf event to record the text poke, primarily to
  1298. * support Intel PT decoding which must walk the executable code
  1299. * to reconstruct the trace. The flow up to here is:
  1300. * - write INT3 byte
  1301. * - IPI-SYNC
  1302. * - write instruction tail
  1303. * At this point the actual control flow will be through the
  1304. * INT3 and handler and not hit the old or new instruction.
  1305. * Intel PT outputs FUP/TIP packets for the INT3, so the flow
  1306. * can still be decoded. Subsequently:
  1307. * - emit RECORD_TEXT_POKE with the new instruction
  1308. * - IPI-SYNC
  1309. * - write first byte
  1310. * - IPI-SYNC
  1311. * So before the text poke event timestamp, the decoder will see
  1312. * either the old instruction flow or FUP/TIP of INT3. After the
  1313. * text poke event timestamp, the decoder will see either the
  1314. * new instruction flow or FUP/TIP of INT3. Thus decoders can
  1315. * use the timestamp as the point at which to modify the
  1316. * executable code.
  1317. * The old instruction is recorded so that the event can be
  1318. * processed forwards or backwards.
  1319. */
  1320. perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len);
  1321. }
  1322. if (do_sync) {
  1323. /*
  1324. * According to Intel, this core syncing is very likely
  1325. * not necessary and we'd be safe even without it. But
  1326. * better safe than sorry (plus there's not only Intel).
  1327. */
  1328. text_poke_sync();
  1329. }
  1330. /*
  1331. * Third step: replace the first byte (int3) by the first byte of
  1332. * replacing opcode.
  1333. */
  1334. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  1335. u8 byte = tp[i].text[0];
  1336. if (tp[i].len == 6)
  1337. byte = 0x0f;
  1338. if (byte == INT3_INSN_OPCODE)
  1339. continue;
  1340. text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE);
  1341. do_sync++;
  1342. }
  1343. if (do_sync)
  1344. text_poke_sync();
  1345. /*
  1346. * Remove and wait for refs to be zero.
  1347. */
  1348. if (!atomic_dec_and_test(&bp_desc.refs))
  1349. atomic_cond_read_acquire(&bp_desc.refs, !VAL);
  1350. }
  1351. static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
  1352. const void *opcode, size_t len, const void *emulate)
  1353. {
  1354. struct insn insn;
  1355. int ret, i = 0;
  1356. if (len == 6)
  1357. i = 1;
  1358. memcpy((void *)tp->text, opcode+i, len-i);
  1359. if (!emulate)
  1360. emulate = opcode;
  1361. ret = insn_decode_kernel(&insn, emulate);
  1362. BUG_ON(ret < 0);
  1363. tp->rel_addr = addr - (void *)_stext;
  1364. tp->len = len;
  1365. tp->opcode = insn.opcode.bytes[0];
  1366. if (is_jcc32(&insn)) {
  1367. /*
  1368. * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
  1369. */
  1370. tp->opcode = insn.opcode.bytes[1] - 0x10;
  1371. }
  1372. switch (tp->opcode) {
  1373. case RET_INSN_OPCODE:
  1374. case JMP32_INSN_OPCODE:
  1375. case JMP8_INSN_OPCODE:
  1376. /*
  1377. * Control flow instructions without implied execution of the
  1378. * next instruction can be padded with INT3.
  1379. */
  1380. for (i = insn.length; i < len; i++)
  1381. BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
  1382. break;
  1383. default:
  1384. BUG_ON(len != insn.length);
  1385. };
  1386. switch (tp->opcode) {
  1387. case INT3_INSN_OPCODE:
  1388. case RET_INSN_OPCODE:
  1389. break;
  1390. case CALL_INSN_OPCODE:
  1391. case JMP32_INSN_OPCODE:
  1392. case JMP8_INSN_OPCODE:
  1393. case 0x70 ... 0x7f: /* Jcc */
  1394. tp->disp = insn.immediate.value;
  1395. break;
  1396. default: /* assume NOP */
  1397. switch (len) {
  1398. case 2: /* NOP2 -- emulate as JMP8+0 */
  1399. BUG_ON(memcmp(emulate, x86_nops[len], len));
  1400. tp->opcode = JMP8_INSN_OPCODE;
  1401. tp->disp = 0;
  1402. break;
  1403. case 5: /* NOP5 -- emulate as JMP32+0 */
  1404. BUG_ON(memcmp(emulate, x86_nops[len], len));
  1405. tp->opcode = JMP32_INSN_OPCODE;
  1406. tp->disp = 0;
  1407. break;
  1408. default: /* unknown instruction */
  1409. BUG();
  1410. }
  1411. break;
  1412. }
  1413. }
  1414. /*
  1415. * We hard rely on the tp_vec being ordered; ensure this is so by flushing
  1416. * early if needed.
  1417. */
  1418. static bool tp_order_fail(void *addr)
  1419. {
  1420. struct text_poke_loc *tp;
  1421. if (!tp_vec_nr)
  1422. return false;
  1423. if (!addr) /* force */
  1424. return true;
  1425. tp = &tp_vec[tp_vec_nr - 1];
  1426. if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
  1427. return true;
  1428. return false;
  1429. }
  1430. static void text_poke_flush(void *addr)
  1431. {
  1432. if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
  1433. text_poke_bp_batch(tp_vec, tp_vec_nr);
  1434. tp_vec_nr = 0;
  1435. }
  1436. }
  1437. void text_poke_finish(void)
  1438. {
  1439. text_poke_flush(NULL);
  1440. }
  1441. void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
  1442. {
  1443. struct text_poke_loc *tp;
  1444. if (unlikely(system_state == SYSTEM_BOOTING)) {
  1445. text_poke_early(addr, opcode, len);
  1446. return;
  1447. }
  1448. text_poke_flush(addr);
  1449. tp = &tp_vec[tp_vec_nr++];
  1450. text_poke_loc_init(tp, addr, opcode, len, emulate);
  1451. }
  1452. /**
  1453. * text_poke_bp() -- update instructions on live kernel on SMP
  1454. * @addr: address to patch
  1455. * @opcode: opcode of new instruction
  1456. * @len: length to copy
  1457. * @emulate: instruction to be emulated
  1458. *
  1459. * Update a single instruction with the vector in the stack, avoiding
  1460. * dynamically allocated memory. This function should be used when it is
  1461. * not possible to allocate memory.
  1462. */
  1463. void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
  1464. {
  1465. struct text_poke_loc tp;
  1466. if (unlikely(system_state == SYSTEM_BOOTING)) {
  1467. text_poke_early(addr, opcode, len);
  1468. return;
  1469. }
  1470. text_poke_loc_init(&tp, addr, opcode, len, emulate);
  1471. text_poke_bp_batch(&tp, 1);
  1472. }