alternative.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  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. #include <asm/cfi.h>
  33. int __read_mostly alternatives_patched;
  34. EXPORT_SYMBOL_GPL(alternatives_patched);
  35. #define MAX_PATCH_LEN (255-1)
  36. #define DA_ALL (~0)
  37. #define DA_ALT 0x01
  38. #define DA_RET 0x02
  39. #define DA_RETPOLINE 0x04
  40. #define DA_ENDBR 0x08
  41. #define DA_SMP 0x10
  42. static unsigned int debug_alternative;
  43. static int __init debug_alt(char *str)
  44. {
  45. if (str && *str == '=')
  46. str++;
  47. if (!str || kstrtouint(str, 0, &debug_alternative))
  48. debug_alternative = DA_ALL;
  49. return 1;
  50. }
  51. __setup("debug-alternative", debug_alt);
  52. static int noreplace_smp;
  53. static int __init setup_noreplace_smp(char *str)
  54. {
  55. noreplace_smp = 1;
  56. return 1;
  57. }
  58. __setup("noreplace-smp", setup_noreplace_smp);
  59. #define DPRINTK(type, fmt, args...) \
  60. do { \
  61. if (debug_alternative & DA_##type) \
  62. printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
  63. } while (0)
  64. #define DUMP_BYTES(type, buf, len, fmt, args...) \
  65. do { \
  66. if (unlikely(debug_alternative & DA_##type)) { \
  67. int j; \
  68. \
  69. if (!(len)) \
  70. break; \
  71. \
  72. printk(KERN_DEBUG pr_fmt(fmt), ##args); \
  73. for (j = 0; j < (len) - 1; j++) \
  74. printk(KERN_CONT "%02hhx ", buf[j]); \
  75. printk(KERN_CONT "%02hhx\n", buf[j]); \
  76. } \
  77. } while (0)
  78. static const unsigned char x86nops[] =
  79. {
  80. BYTES_NOP1,
  81. BYTES_NOP2,
  82. BYTES_NOP3,
  83. BYTES_NOP4,
  84. BYTES_NOP5,
  85. BYTES_NOP6,
  86. BYTES_NOP7,
  87. BYTES_NOP8,
  88. #ifdef CONFIG_64BIT
  89. BYTES_NOP9,
  90. BYTES_NOP10,
  91. BYTES_NOP11,
  92. #endif
  93. };
  94. const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
  95. {
  96. NULL,
  97. x86nops,
  98. x86nops + 1,
  99. x86nops + 1 + 2,
  100. x86nops + 1 + 2 + 3,
  101. x86nops + 1 + 2 + 3 + 4,
  102. x86nops + 1 + 2 + 3 + 4 + 5,
  103. x86nops + 1 + 2 + 3 + 4 + 5 + 6,
  104. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
  105. #ifdef CONFIG_64BIT
  106. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
  107. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
  108. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
  109. #endif
  110. };
  111. /*
  112. * Nomenclature for variable names to simplify and clarify this code and ease
  113. * any potential staring at it:
  114. *
  115. * @instr: source address of the original instructions in the kernel text as
  116. * generated by the compiler.
  117. *
  118. * @buf: temporary buffer on which the patching operates. This buffer is
  119. * eventually text-poked into the kernel image.
  120. *
  121. * @replacement/@repl: pointer to the opcodes which are replacing @instr, located
  122. * in the .altinstr_replacement section.
  123. */
  124. /*
  125. * Fill the buffer with a single effective instruction of size @len.
  126. *
  127. * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
  128. * for every single-byte NOP, try to generate the maximally available NOP of
  129. * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
  130. * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
  131. * *jump* over instead of executing long and daft NOPs.
  132. */
  133. static void add_nop(u8 *buf, unsigned int len)
  134. {
  135. u8 *target = buf + len;
  136. if (!len)
  137. return;
  138. if (len <= ASM_NOP_MAX) {
  139. memcpy(buf, x86_nops[len], len);
  140. return;
  141. }
  142. if (len < 128) {
  143. __text_gen_insn(buf, JMP8_INSN_OPCODE, buf, target, JMP8_INSN_SIZE);
  144. buf += JMP8_INSN_SIZE;
  145. } else {
  146. __text_gen_insn(buf, JMP32_INSN_OPCODE, buf, target, JMP32_INSN_SIZE);
  147. buf += JMP32_INSN_SIZE;
  148. }
  149. for (;buf < target; buf++)
  150. *buf = INT3_INSN_OPCODE;
  151. }
  152. extern s32 __retpoline_sites[], __retpoline_sites_end[];
  153. extern s32 __return_sites[], __return_sites_end[];
  154. extern s32 __cfi_sites[], __cfi_sites_end[];
  155. extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[];
  156. extern s32 __smp_locks[], __smp_locks_end[];
  157. void text_poke_early(void *addr, const void *opcode, size_t len);
  158. /*
  159. * Matches NOP and NOPL, not any of the other possible NOPs.
  160. */
  161. static bool insn_is_nop(struct insn *insn)
  162. {
  163. /* Anything NOP, but no REP NOP */
  164. if (insn->opcode.bytes[0] == 0x90 &&
  165. (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3))
  166. return true;
  167. /* NOPL */
  168. if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F)
  169. return true;
  170. /* TODO: more nops */
  171. return false;
  172. }
  173. /*
  174. * Find the offset of the first non-NOP instruction starting at @offset
  175. * but no further than @len.
  176. */
  177. static int skip_nops(u8 *buf, int offset, int len)
  178. {
  179. struct insn insn;
  180. for (; offset < len; offset += insn.length) {
  181. if (insn_decode_kernel(&insn, &buf[offset]))
  182. break;
  183. if (!insn_is_nop(&insn))
  184. break;
  185. }
  186. return offset;
  187. }
  188. /*
  189. * "noinline" to cause control flow change and thus invalidate I$ and
  190. * cause refetch after modification.
  191. */
  192. static void noinline optimize_nops(const u8 * const instr, u8 *buf, size_t len)
  193. {
  194. for (int next, i = 0; i < len; i = next) {
  195. struct insn insn;
  196. if (insn_decode_kernel(&insn, &buf[i]))
  197. return;
  198. next = i + insn.length;
  199. if (insn_is_nop(&insn)) {
  200. int nop = i;
  201. /* Has the NOP already been optimized? */
  202. if (i + insn.length == len)
  203. return;
  204. next = skip_nops(buf, next, len);
  205. add_nop(buf + nop, next - nop);
  206. DUMP_BYTES(ALT, buf, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, next);
  207. }
  208. }
  209. }
  210. /*
  211. * In this context, "source" is where the instructions are placed in the
  212. * section .altinstr_replacement, for example during kernel build by the
  213. * toolchain.
  214. * "Destination" is where the instructions are being patched in by this
  215. * machinery.
  216. *
  217. * The source offset is:
  218. *
  219. * src_imm = target - src_next_ip (1)
  220. *
  221. * and the target offset is:
  222. *
  223. * dst_imm = target - dst_next_ip (2)
  224. *
  225. * so rework (1) as an expression for target like:
  226. *
  227. * target = src_imm + src_next_ip (1a)
  228. *
  229. * and substitute in (2) to get:
  230. *
  231. * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
  232. *
  233. * Now, since the instruction stream is 'identical' at src and dst (it
  234. * is being copied after all) it can be stated that:
  235. *
  236. * src_next_ip = src + ip_offset
  237. * dst_next_ip = dst + ip_offset (4)
  238. *
  239. * Substitute (4) in (3) and observe ip_offset being cancelled out to
  240. * obtain:
  241. *
  242. * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
  243. * = src_imm + src - dst + ip_offset - ip_offset
  244. * = src_imm + src - dst (5)
  245. *
  246. * IOW, only the relative displacement of the code block matters.
  247. */
  248. #define apply_reloc_n(n_, p_, d_) \
  249. do { \
  250. s32 v = *(s##n_ *)(p_); \
  251. v += (d_); \
  252. BUG_ON((v >> 31) != (v >> (n_-1))); \
  253. *(s##n_ *)(p_) = (s##n_)v; \
  254. } while (0)
  255. static __always_inline
  256. void apply_reloc(int n, void *ptr, uintptr_t diff)
  257. {
  258. switch (n) {
  259. case 1: apply_reloc_n(8, ptr, diff); break;
  260. case 2: apply_reloc_n(16, ptr, diff); break;
  261. case 4: apply_reloc_n(32, ptr, diff); break;
  262. default: BUG();
  263. }
  264. }
  265. static __always_inline
  266. bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
  267. {
  268. u8 *target = src + offset;
  269. /*
  270. * If the target is inside the patched block, it's relative to the
  271. * block itself and does not need relocation.
  272. */
  273. return (target < src || target > src + src_len);
  274. }
  275. static void __apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
  276. {
  277. for (int next, i = 0; i < instrlen; i = next) {
  278. struct insn insn;
  279. if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
  280. return;
  281. next = i + insn.length;
  282. switch (insn.opcode.bytes[0]) {
  283. case 0x0f:
  284. if (insn.opcode.bytes[1] < 0x80 ||
  285. insn.opcode.bytes[1] > 0x8f)
  286. break;
  287. fallthrough; /* Jcc.d32 */
  288. case 0x70 ... 0x7f: /* Jcc.d8 */
  289. case JMP8_INSN_OPCODE:
  290. case JMP32_INSN_OPCODE:
  291. case CALL_INSN_OPCODE:
  292. if (need_reloc(next + insn.immediate.value, repl, repl_len)) {
  293. apply_reloc(insn.immediate.nbytes,
  294. buf + i + insn_offset_immediate(&insn),
  295. repl - instr);
  296. }
  297. /*
  298. * Where possible, convert JMP.d32 into JMP.d8.
  299. */
  300. if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
  301. s32 imm = insn.immediate.value;
  302. imm += repl - instr;
  303. imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
  304. if ((imm >> 31) == (imm >> 7)) {
  305. buf[i+0] = JMP8_INSN_OPCODE;
  306. buf[i+1] = (s8)imm;
  307. memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
  308. }
  309. }
  310. break;
  311. }
  312. if (insn_rip_relative(&insn)) {
  313. if (need_reloc(next + insn.displacement.value, repl, repl_len)) {
  314. apply_reloc(insn.displacement.nbytes,
  315. buf + i + insn_offset_displacement(&insn),
  316. repl - instr);
  317. }
  318. }
  319. }
  320. }
  321. void apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
  322. {
  323. __apply_relocation(buf, instr, instrlen, repl, repl_len);
  324. optimize_nops(instr, buf, instrlen);
  325. }
  326. /* Low-level backend functions usable from alternative code replacements. */
  327. DEFINE_ASM_FUNC(nop_func, "", .entry.text);
  328. EXPORT_SYMBOL_GPL(nop_func);
  329. noinstr void BUG_func(void)
  330. {
  331. BUG();
  332. }
  333. EXPORT_SYMBOL(BUG_func);
  334. #define CALL_RIP_REL_OPCODE 0xff
  335. #define CALL_RIP_REL_MODRM 0x15
  336. /*
  337. * Rewrite the "call BUG_func" replacement to point to the target of the
  338. * indirect pv_ops call "call *disp(%ip)".
  339. */
  340. static int alt_replace_call(u8 *instr, u8 *insn_buff, struct alt_instr *a)
  341. {
  342. void *target, *bug = &BUG_func;
  343. s32 disp;
  344. if (a->replacementlen != 5 || insn_buff[0] != CALL_INSN_OPCODE) {
  345. pr_err("ALT_FLAG_DIRECT_CALL set for a non-call replacement instruction\n");
  346. BUG();
  347. }
  348. if (a->instrlen != 6 ||
  349. instr[0] != CALL_RIP_REL_OPCODE ||
  350. instr[1] != CALL_RIP_REL_MODRM) {
  351. pr_err("ALT_FLAG_DIRECT_CALL set for unrecognized indirect call\n");
  352. BUG();
  353. }
  354. /* Skip CALL_RIP_REL_OPCODE and CALL_RIP_REL_MODRM */
  355. disp = *(s32 *)(instr + 2);
  356. #ifdef CONFIG_X86_64
  357. /* ff 15 00 00 00 00 call *0x0(%rip) */
  358. /* target address is stored at "next instruction + disp". */
  359. target = *(void **)(instr + a->instrlen + disp);
  360. #else
  361. /* ff 15 00 00 00 00 call *0x0 */
  362. /* target address is stored at disp. */
  363. target = *(void **)disp;
  364. #endif
  365. if (!target)
  366. target = bug;
  367. /* (BUG_func - .) + (target - BUG_func) := target - . */
  368. *(s32 *)(insn_buff + 1) += target - bug;
  369. if (target == &nop_func)
  370. return 0;
  371. return 5;
  372. }
  373. static inline u8 * instr_va(struct alt_instr *i)
  374. {
  375. return (u8 *)&i->instr_offset + i->instr_offset;
  376. }
  377. /*
  378. * Replace instructions with better alternatives for this CPU type. This runs
  379. * before SMP is initialized to avoid SMP problems with self modifying code.
  380. * This implies that asymmetric systems where APs have less capabilities than
  381. * the boot processor are not handled. Tough. Make sure you disable such
  382. * features by hand.
  383. *
  384. * Marked "noinline" to cause control flow change and thus insn cache
  385. * to refetch changed I$ lines.
  386. */
  387. void __init_or_module noinline apply_alternatives(struct alt_instr *start,
  388. struct alt_instr *end)
  389. {
  390. u8 insn_buff[MAX_PATCH_LEN];
  391. u8 *instr, *replacement;
  392. struct alt_instr *a, *b;
  393. DPRINTK(ALT, "alt table %px, -> %px", start, end);
  394. /*
  395. * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
  396. * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
  397. * During the process, KASAN becomes confused seeing partial LA57
  398. * conversion and triggers a false-positive out-of-bound report.
  399. *
  400. * Disable KASAN until the patching is complete.
  401. */
  402. kasan_disable_current();
  403. /*
  404. * The scan order should be from start to end. A later scanned
  405. * alternative code can overwrite previously scanned alternative code.
  406. * Some kernel functions (e.g. memcpy, memset, etc) use this order to
  407. * patch code.
  408. *
  409. * So be careful if you want to change the scan order to any other
  410. * order.
  411. */
  412. for (a = start; a < end; a++) {
  413. int insn_buff_sz = 0;
  414. /*
  415. * In case of nested ALTERNATIVE()s the outer alternative might
  416. * add more padding. To ensure consistent patching find the max
  417. * padding for all alt_instr entries for this site (nested
  418. * alternatives result in consecutive entries).
  419. */
  420. for (b = a+1; b < end && instr_va(b) == instr_va(a); b++) {
  421. u8 len = max(a->instrlen, b->instrlen);
  422. a->instrlen = b->instrlen = len;
  423. }
  424. instr = instr_va(a);
  425. replacement = (u8 *)&a->repl_offset + a->repl_offset;
  426. BUG_ON(a->instrlen > sizeof(insn_buff));
  427. BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
  428. /*
  429. * Patch if either:
  430. * - feature is present
  431. * - feature not present but ALT_FLAG_NOT is set to mean,
  432. * patch if feature is *NOT* present.
  433. */
  434. if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) {
  435. memcpy(insn_buff, instr, a->instrlen);
  436. optimize_nops(instr, insn_buff, a->instrlen);
  437. text_poke_early(instr, insn_buff, a->instrlen);
  438. continue;
  439. }
  440. DPRINTK(ALT, "feat: %d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d) flags: 0x%x",
  441. a->cpuid >> 5,
  442. a->cpuid & 0x1f,
  443. instr, instr, a->instrlen,
  444. replacement, a->replacementlen, a->flags);
  445. memcpy(insn_buff, replacement, a->replacementlen);
  446. insn_buff_sz = a->replacementlen;
  447. if (a->flags & ALT_FLAG_DIRECT_CALL) {
  448. insn_buff_sz = alt_replace_call(instr, insn_buff, a);
  449. if (insn_buff_sz < 0)
  450. continue;
  451. }
  452. for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
  453. insn_buff[insn_buff_sz] = 0x90;
  454. apply_relocation(insn_buff, instr, a->instrlen, replacement, a->replacementlen);
  455. DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr);
  456. DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
  457. DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
  458. text_poke_early(instr, insn_buff, insn_buff_sz);
  459. }
  460. kasan_enable_current();
  461. }
  462. static inline bool is_jcc32(struct insn *insn)
  463. {
  464. /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
  465. return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
  466. }
  467. #if defined(CONFIG_MITIGATION_RETPOLINE) && defined(CONFIG_OBJTOOL)
  468. /*
  469. * CALL/JMP *%\reg
  470. */
  471. static int emit_indirect(int op, int reg, u8 *bytes)
  472. {
  473. int i = 0;
  474. u8 modrm;
  475. switch (op) {
  476. case CALL_INSN_OPCODE:
  477. modrm = 0x10; /* Reg = 2; CALL r/m */
  478. break;
  479. case JMP32_INSN_OPCODE:
  480. modrm = 0x20; /* Reg = 4; JMP r/m */
  481. break;
  482. default:
  483. WARN_ON_ONCE(1);
  484. return -1;
  485. }
  486. if (reg >= 8) {
  487. bytes[i++] = 0x41; /* REX.B prefix */
  488. reg -= 8;
  489. }
  490. modrm |= 0xc0; /* Mod = 3 */
  491. modrm += reg;
  492. bytes[i++] = 0xff; /* opcode */
  493. bytes[i++] = modrm;
  494. return i;
  495. }
  496. static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
  497. {
  498. u8 op = insn->opcode.bytes[0];
  499. int i = 0;
  500. /*
  501. * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
  502. * tail-calls. Deal with them.
  503. */
  504. if (is_jcc32(insn)) {
  505. bytes[i++] = op;
  506. op = insn->opcode.bytes[1];
  507. goto clang_jcc;
  508. }
  509. if (insn->length == 6)
  510. bytes[i++] = 0x2e; /* CS-prefix */
  511. switch (op) {
  512. case CALL_INSN_OPCODE:
  513. __text_gen_insn(bytes+i, op, addr+i,
  514. __x86_indirect_call_thunk_array[reg],
  515. CALL_INSN_SIZE);
  516. i += CALL_INSN_SIZE;
  517. break;
  518. case JMP32_INSN_OPCODE:
  519. clang_jcc:
  520. __text_gen_insn(bytes+i, op, addr+i,
  521. __x86_indirect_jump_thunk_array[reg],
  522. JMP32_INSN_SIZE);
  523. i += JMP32_INSN_SIZE;
  524. break;
  525. default:
  526. WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
  527. return -1;
  528. }
  529. WARN_ON_ONCE(i != insn->length);
  530. return i;
  531. }
  532. /*
  533. * Rewrite the compiler generated retpoline thunk calls.
  534. *
  535. * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
  536. * indirect instructions, avoiding the extra indirection.
  537. *
  538. * For example, convert:
  539. *
  540. * CALL __x86_indirect_thunk_\reg
  541. *
  542. * into:
  543. *
  544. * CALL *%\reg
  545. *
  546. * It also tries to inline spectre_v2=retpoline,lfence when size permits.
  547. */
  548. static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
  549. {
  550. retpoline_thunk_t *target;
  551. int reg, ret, i = 0;
  552. u8 op, cc;
  553. target = addr + insn->length + insn->immediate.value;
  554. reg = target - __x86_indirect_thunk_array;
  555. if (WARN_ON_ONCE(reg & ~0xf))
  556. return -1;
  557. /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
  558. BUG_ON(reg == 4);
  559. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
  560. !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
  561. if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
  562. return emit_call_track_retpoline(addr, insn, reg, bytes);
  563. return -1;
  564. }
  565. op = insn->opcode.bytes[0];
  566. /*
  567. * Convert:
  568. *
  569. * Jcc.d32 __x86_indirect_thunk_\reg
  570. *
  571. * into:
  572. *
  573. * Jncc.d8 1f
  574. * [ LFENCE ]
  575. * JMP *%\reg
  576. * [ NOP ]
  577. * 1:
  578. */
  579. if (is_jcc32(insn)) {
  580. cc = insn->opcode.bytes[1] & 0xf;
  581. cc ^= 1; /* invert condition */
  582. bytes[i++] = 0x70 + cc; /* Jcc.d8 */
  583. bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
  584. /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
  585. op = JMP32_INSN_OPCODE;
  586. }
  587. /*
  588. * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
  589. */
  590. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
  591. bytes[i++] = 0x0f;
  592. bytes[i++] = 0xae;
  593. bytes[i++] = 0xe8; /* LFENCE */
  594. }
  595. ret = emit_indirect(op, reg, bytes + i);
  596. if (ret < 0)
  597. return ret;
  598. i += ret;
  599. /*
  600. * The compiler is supposed to EMIT an INT3 after every unconditional
  601. * JMP instruction due to AMD BTC. However, if the compiler is too old
  602. * or MITIGATION_SLS isn't enabled, we still need an INT3 after
  603. * indirect JMPs even on Intel.
  604. */
  605. if (op == JMP32_INSN_OPCODE && i < insn->length)
  606. bytes[i++] = INT3_INSN_OPCODE;
  607. for (; i < insn->length;)
  608. bytes[i++] = BYTES_NOP1;
  609. return i;
  610. }
  611. /*
  612. * Generated by 'objtool --retpoline'.
  613. */
  614. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
  615. {
  616. s32 *s;
  617. for (s = start; s < end; s++) {
  618. void *addr = (void *)s + *s;
  619. struct insn insn;
  620. int len, ret;
  621. u8 bytes[16];
  622. u8 op1, op2;
  623. ret = insn_decode_kernel(&insn, addr);
  624. if (WARN_ON_ONCE(ret < 0))
  625. continue;
  626. op1 = insn.opcode.bytes[0];
  627. op2 = insn.opcode.bytes[1];
  628. switch (op1) {
  629. case CALL_INSN_OPCODE:
  630. case JMP32_INSN_OPCODE:
  631. break;
  632. case 0x0f: /* escape */
  633. if (op2 >= 0x80 && op2 <= 0x8f)
  634. break;
  635. fallthrough;
  636. default:
  637. WARN_ON_ONCE(1);
  638. continue;
  639. }
  640. DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
  641. addr, addr, insn.length,
  642. addr + insn.length + insn.immediate.value);
  643. len = patch_retpoline(addr, &insn, bytes);
  644. if (len == insn.length) {
  645. optimize_nops(addr, bytes, len);
  646. DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr);
  647. DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
  648. text_poke_early(addr, bytes, len);
  649. }
  650. }
  651. }
  652. #ifdef CONFIG_MITIGATION_RETHUNK
  653. /*
  654. * Rewrite the compiler generated return thunk tail-calls.
  655. *
  656. * For example, convert:
  657. *
  658. * JMP __x86_return_thunk
  659. *
  660. * into:
  661. *
  662. * RET
  663. */
  664. static int patch_return(void *addr, struct insn *insn, u8 *bytes)
  665. {
  666. int i = 0;
  667. /* Patch the custom return thunks... */
  668. if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) {
  669. i = JMP32_INSN_SIZE;
  670. __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
  671. } else {
  672. /* ... or patch them out if not needed. */
  673. bytes[i++] = RET_INSN_OPCODE;
  674. }
  675. for (; i < insn->length;)
  676. bytes[i++] = INT3_INSN_OPCODE;
  677. return i;
  678. }
  679. void __init_or_module noinline apply_returns(s32 *start, s32 *end)
  680. {
  681. s32 *s;
  682. if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
  683. static_call_force_reinit();
  684. for (s = start; s < end; s++) {
  685. void *dest = NULL, *addr = (void *)s + *s;
  686. struct insn insn;
  687. int len, ret;
  688. u8 bytes[16];
  689. u8 op;
  690. ret = insn_decode_kernel(&insn, addr);
  691. if (WARN_ON_ONCE(ret < 0))
  692. continue;
  693. op = insn.opcode.bytes[0];
  694. if (op == JMP32_INSN_OPCODE)
  695. dest = addr + insn.length + insn.immediate.value;
  696. if (__static_call_fixup(addr, op, dest) ||
  697. WARN_ONCE(dest != &__x86_return_thunk,
  698. "missing return thunk: %pS-%pS: %*ph",
  699. addr, dest, 5, addr))
  700. continue;
  701. DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
  702. addr, addr, insn.length,
  703. addr + insn.length + insn.immediate.value);
  704. len = patch_return(addr, &insn, bytes);
  705. if (len == insn.length) {
  706. DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr);
  707. DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
  708. text_poke_early(addr, bytes, len);
  709. }
  710. }
  711. }
  712. #else
  713. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  714. #endif /* CONFIG_MITIGATION_RETHUNK */
  715. #else /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
  716. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
  717. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  718. #endif /* CONFIG_MITIGATION_RETPOLINE && CONFIG_OBJTOOL */
  719. #ifdef CONFIG_X86_KERNEL_IBT
  720. static void poison_cfi(void *addr);
  721. static void __init_or_module poison_endbr(void *addr, bool warn)
  722. {
  723. u32 endbr, poison = gen_endbr_poison();
  724. if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr)))
  725. return;
  726. if (!is_endbr(endbr)) {
  727. WARN_ON_ONCE(warn);
  728. return;
  729. }
  730. DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
  731. /*
  732. * When we have IBT, the lack of ENDBR will trigger #CP
  733. */
  734. DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
  735. DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
  736. text_poke_early(addr, &poison, 4);
  737. }
  738. /*
  739. * Generated by: objtool --ibt
  740. *
  741. * Seal the functions for indirect calls by clobbering the ENDBR instructions
  742. * and the kCFI hash value.
  743. */
  744. void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end)
  745. {
  746. s32 *s;
  747. for (s = start; s < end; s++) {
  748. void *addr = (void *)s + *s;
  749. poison_endbr(addr, true);
  750. if (IS_ENABLED(CONFIG_FINEIBT))
  751. poison_cfi(addr - 16);
  752. }
  753. }
  754. #else
  755. void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }
  756. #endif /* CONFIG_X86_KERNEL_IBT */
  757. #ifdef CONFIG_CFI_AUTO_DEFAULT
  758. #define __CFI_DEFAULT CFI_AUTO
  759. #elif defined(CONFIG_CFI_CLANG)
  760. #define __CFI_DEFAULT CFI_KCFI
  761. #else
  762. #define __CFI_DEFAULT CFI_OFF
  763. #endif
  764. enum cfi_mode cfi_mode __ro_after_init = __CFI_DEFAULT;
  765. #ifdef CONFIG_CFI_CLANG
  766. struct bpf_insn;
  767. /* Must match bpf_func_t / DEFINE_BPF_PROG_RUN() */
  768. extern unsigned int __bpf_prog_runX(const void *ctx,
  769. const struct bpf_insn *insn);
  770. /*
  771. * Force a reference to the external symbol so the compiler generates
  772. * __kcfi_typid.
  773. */
  774. __ADDRESSABLE(__bpf_prog_runX);
  775. /* u32 __ro_after_init cfi_bpf_hash = __kcfi_typeid___bpf_prog_runX; */
  776. asm (
  777. " .pushsection .data..ro_after_init,\"aw\",@progbits \n"
  778. " .type cfi_bpf_hash,@object \n"
  779. " .globl cfi_bpf_hash \n"
  780. " .p2align 2, 0x0 \n"
  781. "cfi_bpf_hash: \n"
  782. " .long __kcfi_typeid___bpf_prog_runX \n"
  783. " .size cfi_bpf_hash, 4 \n"
  784. " .popsection \n"
  785. );
  786. /* Must match bpf_callback_t */
  787. extern u64 __bpf_callback_fn(u64, u64, u64, u64, u64);
  788. __ADDRESSABLE(__bpf_callback_fn);
  789. /* u32 __ro_after_init cfi_bpf_subprog_hash = __kcfi_typeid___bpf_callback_fn; */
  790. asm (
  791. " .pushsection .data..ro_after_init,\"aw\",@progbits \n"
  792. " .type cfi_bpf_subprog_hash,@object \n"
  793. " .globl cfi_bpf_subprog_hash \n"
  794. " .p2align 2, 0x0 \n"
  795. "cfi_bpf_subprog_hash: \n"
  796. " .long __kcfi_typeid___bpf_callback_fn \n"
  797. " .size cfi_bpf_subprog_hash, 4 \n"
  798. " .popsection \n"
  799. );
  800. u32 cfi_get_func_hash(void *func)
  801. {
  802. u32 hash;
  803. func -= cfi_get_offset();
  804. switch (cfi_mode) {
  805. case CFI_FINEIBT:
  806. func += 7;
  807. break;
  808. case CFI_KCFI:
  809. func += 1;
  810. break;
  811. default:
  812. return 0;
  813. }
  814. if (get_kernel_nofault(hash, func))
  815. return 0;
  816. return hash;
  817. }
  818. #endif
  819. #ifdef CONFIG_FINEIBT
  820. static bool cfi_rand __ro_after_init = true;
  821. static u32 cfi_seed __ro_after_init;
  822. /*
  823. * Re-hash the CFI hash with a boot-time seed while making sure the result is
  824. * not a valid ENDBR instruction.
  825. */
  826. static u32 cfi_rehash(u32 hash)
  827. {
  828. hash ^= cfi_seed;
  829. while (unlikely(is_endbr(hash) || is_endbr(-hash))) {
  830. bool lsb = hash & 1;
  831. hash >>= 1;
  832. if (lsb)
  833. hash ^= 0x80200003;
  834. }
  835. return hash;
  836. }
  837. static __init int cfi_parse_cmdline(char *str)
  838. {
  839. if (!str)
  840. return -EINVAL;
  841. while (str) {
  842. char *next = strchr(str, ',');
  843. if (next) {
  844. *next = 0;
  845. next++;
  846. }
  847. if (!strcmp(str, "auto")) {
  848. cfi_mode = CFI_AUTO;
  849. } else if (!strcmp(str, "off")) {
  850. cfi_mode = CFI_OFF;
  851. cfi_rand = false;
  852. } else if (!strcmp(str, "kcfi")) {
  853. cfi_mode = CFI_KCFI;
  854. } else if (!strcmp(str, "fineibt")) {
  855. cfi_mode = CFI_FINEIBT;
  856. } else if (!strcmp(str, "norand")) {
  857. cfi_rand = false;
  858. } else {
  859. pr_err("Ignoring unknown cfi option (%s).", str);
  860. }
  861. str = next;
  862. }
  863. return 0;
  864. }
  865. early_param("cfi", cfi_parse_cmdline);
  866. /*
  867. * kCFI FineIBT
  868. *
  869. * __cfi_\func: __cfi_\func:
  870. * movl $0x12345678,%eax // 5 endbr64 // 4
  871. * nop subl $0x12345678,%r10d // 7
  872. * nop jz 1f // 2
  873. * nop ud2 // 2
  874. * nop 1: nop // 1
  875. * nop
  876. * nop
  877. * nop
  878. * nop
  879. * nop
  880. * nop
  881. * nop
  882. *
  883. *
  884. * caller: caller:
  885. * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6
  886. * addl $-15(%r11),%r10d // 4 sub $16,%r11 // 4
  887. * je 1f // 2 nop4 // 4
  888. * ud2 // 2
  889. * 1: call __x86_indirect_thunk_r11 // 5 call *%r11; nop2; // 5
  890. *
  891. */
  892. asm( ".pushsection .rodata \n"
  893. "fineibt_preamble_start: \n"
  894. " endbr64 \n"
  895. " subl $0x12345678, %r10d \n"
  896. " je fineibt_preamble_end \n"
  897. " ud2 \n"
  898. " nop \n"
  899. "fineibt_preamble_end: \n"
  900. ".popsection\n"
  901. );
  902. extern u8 fineibt_preamble_start[];
  903. extern u8 fineibt_preamble_end[];
  904. #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
  905. #define fineibt_preamble_hash 7
  906. asm( ".pushsection .rodata \n"
  907. "fineibt_caller_start: \n"
  908. " movl $0x12345678, %r10d \n"
  909. " sub $16, %r11 \n"
  910. ASM_NOP4
  911. "fineibt_caller_end: \n"
  912. ".popsection \n"
  913. );
  914. extern u8 fineibt_caller_start[];
  915. extern u8 fineibt_caller_end[];
  916. #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
  917. #define fineibt_caller_hash 2
  918. #define fineibt_caller_jmp (fineibt_caller_size - 2)
  919. static u32 decode_preamble_hash(void *addr)
  920. {
  921. u8 *p = addr;
  922. /* b8 78 56 34 12 mov $0x12345678,%eax */
  923. if (p[0] == 0xb8)
  924. return *(u32 *)(addr + 1);
  925. return 0; /* invalid hash value */
  926. }
  927. static u32 decode_caller_hash(void *addr)
  928. {
  929. u8 *p = addr;
  930. /* 41 ba 78 56 34 12 mov $0x12345678,%r10d */
  931. if (p[0] == 0x41 && p[1] == 0xba)
  932. return -*(u32 *)(addr + 2);
  933. /* e8 0c 78 56 34 12 jmp.d8 +12 */
  934. if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
  935. return -*(u32 *)(addr + 2);
  936. return 0; /* invalid hash value */
  937. }
  938. /* .retpoline_sites */
  939. static int cfi_disable_callers(s32 *start, s32 *end)
  940. {
  941. /*
  942. * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
  943. * in tact for later usage. Also see decode_caller_hash() and
  944. * cfi_rewrite_callers().
  945. */
  946. const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
  947. s32 *s;
  948. for (s = start; s < end; s++) {
  949. void *addr = (void *)s + *s;
  950. u32 hash;
  951. addr -= fineibt_caller_size;
  952. hash = decode_caller_hash(addr);
  953. if (!hash) /* nocfi callers */
  954. continue;
  955. text_poke_early(addr, jmp, 2);
  956. }
  957. return 0;
  958. }
  959. static int cfi_enable_callers(s32 *start, s32 *end)
  960. {
  961. /*
  962. * Re-enable kCFI, undo what cfi_disable_callers() did.
  963. */
  964. const u8 mov[] = { 0x41, 0xba };
  965. s32 *s;
  966. for (s = start; s < end; s++) {
  967. void *addr = (void *)s + *s;
  968. u32 hash;
  969. addr -= fineibt_caller_size;
  970. hash = decode_caller_hash(addr);
  971. if (!hash) /* nocfi callers */
  972. continue;
  973. text_poke_early(addr, mov, 2);
  974. }
  975. return 0;
  976. }
  977. /* .cfi_sites */
  978. static int cfi_rand_preamble(s32 *start, s32 *end)
  979. {
  980. s32 *s;
  981. for (s = start; s < end; s++) {
  982. void *addr = (void *)s + *s;
  983. u32 hash;
  984. hash = decode_preamble_hash(addr);
  985. if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
  986. addr, addr, 5, addr))
  987. return -EINVAL;
  988. hash = cfi_rehash(hash);
  989. text_poke_early(addr + 1, &hash, 4);
  990. }
  991. return 0;
  992. }
  993. static int cfi_rewrite_preamble(s32 *start, s32 *end)
  994. {
  995. s32 *s;
  996. for (s = start; s < end; s++) {
  997. void *addr = (void *)s + *s;
  998. u32 hash;
  999. hash = decode_preamble_hash(addr);
  1000. if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
  1001. addr, addr, 5, addr))
  1002. return -EINVAL;
  1003. text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
  1004. WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
  1005. text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
  1006. }
  1007. return 0;
  1008. }
  1009. static void cfi_rewrite_endbr(s32 *start, s32 *end)
  1010. {
  1011. s32 *s;
  1012. for (s = start; s < end; s++) {
  1013. void *addr = (void *)s + *s;
  1014. poison_endbr(addr+16, false);
  1015. }
  1016. }
  1017. /* .retpoline_sites */
  1018. static int cfi_rand_callers(s32 *start, s32 *end)
  1019. {
  1020. s32 *s;
  1021. for (s = start; s < end; s++) {
  1022. void *addr = (void *)s + *s;
  1023. u32 hash;
  1024. addr -= fineibt_caller_size;
  1025. hash = decode_caller_hash(addr);
  1026. if (hash) {
  1027. hash = -cfi_rehash(hash);
  1028. text_poke_early(addr + 2, &hash, 4);
  1029. }
  1030. }
  1031. return 0;
  1032. }
  1033. static int cfi_rewrite_callers(s32 *start, s32 *end)
  1034. {
  1035. s32 *s;
  1036. for (s = start; s < end; s++) {
  1037. void *addr = (void *)s + *s;
  1038. u32 hash;
  1039. addr -= fineibt_caller_size;
  1040. hash = decode_caller_hash(addr);
  1041. if (hash) {
  1042. text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
  1043. WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
  1044. text_poke_early(addr + fineibt_caller_hash, &hash, 4);
  1045. }
  1046. /* rely on apply_retpolines() */
  1047. }
  1048. return 0;
  1049. }
  1050. static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1051. s32 *start_cfi, s32 *end_cfi, bool builtin)
  1052. {
  1053. int ret;
  1054. if (WARN_ONCE(fineibt_preamble_size != 16,
  1055. "FineIBT preamble wrong size: %ld", fineibt_preamble_size))
  1056. return;
  1057. if (cfi_mode == CFI_AUTO) {
  1058. cfi_mode = CFI_KCFI;
  1059. if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
  1060. cfi_mode = CFI_FINEIBT;
  1061. }
  1062. /*
  1063. * Rewrite the callers to not use the __cfi_ stubs, such that we might
  1064. * rewrite them. This disables all CFI. If this succeeds but any of the
  1065. * later stages fails, we're without CFI.
  1066. */
  1067. ret = cfi_disable_callers(start_retpoline, end_retpoline);
  1068. if (ret)
  1069. goto err;
  1070. if (cfi_rand) {
  1071. if (builtin) {
  1072. cfi_seed = get_random_u32();
  1073. cfi_bpf_hash = cfi_rehash(cfi_bpf_hash);
  1074. cfi_bpf_subprog_hash = cfi_rehash(cfi_bpf_subprog_hash);
  1075. }
  1076. ret = cfi_rand_preamble(start_cfi, end_cfi);
  1077. if (ret)
  1078. goto err;
  1079. ret = cfi_rand_callers(start_retpoline, end_retpoline);
  1080. if (ret)
  1081. goto err;
  1082. }
  1083. switch (cfi_mode) {
  1084. case CFI_OFF:
  1085. if (builtin)
  1086. pr_info("Disabling CFI\n");
  1087. return;
  1088. case CFI_KCFI:
  1089. ret = cfi_enable_callers(start_retpoline, end_retpoline);
  1090. if (ret)
  1091. goto err;
  1092. if (builtin)
  1093. pr_info("Using kCFI\n");
  1094. return;
  1095. case CFI_FINEIBT:
  1096. /* place the FineIBT preamble at func()-16 */
  1097. ret = cfi_rewrite_preamble(start_cfi, end_cfi);
  1098. if (ret)
  1099. goto err;
  1100. /* rewrite the callers to target func()-16 */
  1101. ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
  1102. if (ret)
  1103. goto err;
  1104. /* now that nobody targets func()+0, remove ENDBR there */
  1105. cfi_rewrite_endbr(start_cfi, end_cfi);
  1106. if (builtin)
  1107. pr_info("Using FineIBT CFI\n");
  1108. return;
  1109. default:
  1110. break;
  1111. }
  1112. err:
  1113. pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
  1114. }
  1115. static inline void poison_hash(void *addr)
  1116. {
  1117. *(u32 *)addr = 0;
  1118. }
  1119. static void poison_cfi(void *addr)
  1120. {
  1121. switch (cfi_mode) {
  1122. case CFI_FINEIBT:
  1123. /*
  1124. * __cfi_\func:
  1125. * osp nopl (%rax)
  1126. * subl $0, %r10d
  1127. * jz 1f
  1128. * ud2
  1129. * 1: nop
  1130. */
  1131. poison_endbr(addr, false);
  1132. poison_hash(addr + fineibt_preamble_hash);
  1133. break;
  1134. case CFI_KCFI:
  1135. /*
  1136. * __cfi_\func:
  1137. * movl $0, %eax
  1138. * .skip 11, 0x90
  1139. */
  1140. poison_hash(addr + 1);
  1141. break;
  1142. default:
  1143. break;
  1144. }
  1145. }
  1146. #else
  1147. static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1148. s32 *start_cfi, s32 *end_cfi, bool builtin)
  1149. {
  1150. }
  1151. #ifdef CONFIG_X86_KERNEL_IBT
  1152. static void poison_cfi(void *addr) { }
  1153. #endif
  1154. #endif
  1155. void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1156. s32 *start_cfi, s32 *end_cfi)
  1157. {
  1158. return __apply_fineibt(start_retpoline, end_retpoline,
  1159. start_cfi, end_cfi,
  1160. /* .builtin = */ false);
  1161. }
  1162. #ifdef CONFIG_SMP
  1163. static void alternatives_smp_lock(const s32 *start, const s32 *end,
  1164. u8 *text, u8 *text_end)
  1165. {
  1166. const s32 *poff;
  1167. for (poff = start; poff < end; poff++) {
  1168. u8 *ptr = (u8 *)poff + *poff;
  1169. if (!*poff || ptr < text || ptr >= text_end)
  1170. continue;
  1171. /* turn DS segment override prefix into lock prefix */
  1172. if (*ptr == 0x3e)
  1173. text_poke(ptr, ((unsigned char []){0xf0}), 1);
  1174. }
  1175. }
  1176. static void alternatives_smp_unlock(const s32 *start, const s32 *end,
  1177. u8 *text, u8 *text_end)
  1178. {
  1179. const s32 *poff;
  1180. for (poff = start; poff < end; poff++) {
  1181. u8 *ptr = (u8 *)poff + *poff;
  1182. if (!*poff || ptr < text || ptr >= text_end)
  1183. continue;
  1184. /* turn lock prefix into DS segment override prefix */
  1185. if (*ptr == 0xf0)
  1186. text_poke(ptr, ((unsigned char []){0x3E}), 1);
  1187. }
  1188. }
  1189. struct smp_alt_module {
  1190. /* what is this ??? */
  1191. struct module *mod;
  1192. char *name;
  1193. /* ptrs to lock prefixes */
  1194. const s32 *locks;
  1195. const s32 *locks_end;
  1196. /* .text segment, needed to avoid patching init code ;) */
  1197. u8 *text;
  1198. u8 *text_end;
  1199. struct list_head next;
  1200. };
  1201. static LIST_HEAD(smp_alt_modules);
  1202. static bool uniproc_patched = false; /* protected by text_mutex */
  1203. void __init_or_module alternatives_smp_module_add(struct module *mod,
  1204. char *name,
  1205. void *locks, void *locks_end,
  1206. void *text, void *text_end)
  1207. {
  1208. struct smp_alt_module *smp;
  1209. mutex_lock(&text_mutex);
  1210. if (!uniproc_patched)
  1211. goto unlock;
  1212. if (num_possible_cpus() == 1)
  1213. /* Don't bother remembering, we'll never have to undo it. */
  1214. goto smp_unlock;
  1215. smp = kzalloc(sizeof(*smp), GFP_KERNEL);
  1216. if (NULL == smp)
  1217. /* we'll run the (safe but slow) SMP code then ... */
  1218. goto unlock;
  1219. smp->mod = mod;
  1220. smp->name = name;
  1221. smp->locks = locks;
  1222. smp->locks_end = locks_end;
  1223. smp->text = text;
  1224. smp->text_end = text_end;
  1225. DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
  1226. smp->locks, smp->locks_end,
  1227. smp->text, smp->text_end, smp->name);
  1228. list_add_tail(&smp->next, &smp_alt_modules);
  1229. smp_unlock:
  1230. alternatives_smp_unlock(locks, locks_end, text, text_end);
  1231. unlock:
  1232. mutex_unlock(&text_mutex);
  1233. }
  1234. void __init_or_module alternatives_smp_module_del(struct module *mod)
  1235. {
  1236. struct smp_alt_module *item;
  1237. mutex_lock(&text_mutex);
  1238. list_for_each_entry(item, &smp_alt_modules, next) {
  1239. if (mod != item->mod)
  1240. continue;
  1241. list_del(&item->next);
  1242. kfree(item);
  1243. break;
  1244. }
  1245. mutex_unlock(&text_mutex);
  1246. }
  1247. void alternatives_enable_smp(void)
  1248. {
  1249. struct smp_alt_module *mod;
  1250. /* Why bother if there are no other CPUs? */
  1251. BUG_ON(num_possible_cpus() == 1);
  1252. mutex_lock(&text_mutex);
  1253. if (uniproc_patched) {
  1254. pr_info("switching to SMP code\n");
  1255. BUG_ON(num_online_cpus() != 1);
  1256. clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
  1257. clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
  1258. list_for_each_entry(mod, &smp_alt_modules, next)
  1259. alternatives_smp_lock(mod->locks, mod->locks_end,
  1260. mod->text, mod->text_end);
  1261. uniproc_patched = false;
  1262. }
  1263. mutex_unlock(&text_mutex);
  1264. }
  1265. /*
  1266. * Return 1 if the address range is reserved for SMP-alternatives.
  1267. * Must hold text_mutex.
  1268. */
  1269. int alternatives_text_reserved(void *start, void *end)
  1270. {
  1271. struct smp_alt_module *mod;
  1272. const s32 *poff;
  1273. u8 *text_start = start;
  1274. u8 *text_end = end;
  1275. lockdep_assert_held(&text_mutex);
  1276. list_for_each_entry(mod, &smp_alt_modules, next) {
  1277. if (mod->text > text_end || mod->text_end < text_start)
  1278. continue;
  1279. for (poff = mod->locks; poff < mod->locks_end; poff++) {
  1280. const u8 *ptr = (const u8 *)poff + *poff;
  1281. if (text_start <= ptr && text_end > ptr)
  1282. return 1;
  1283. }
  1284. }
  1285. return 0;
  1286. }
  1287. #endif /* CONFIG_SMP */
  1288. /*
  1289. * Self-test for the INT3 based CALL emulation code.
  1290. *
  1291. * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
  1292. * properly and that there is a stack gap between the INT3 frame and the
  1293. * previous context. Without this gap doing a virtual PUSH on the interrupted
  1294. * stack would corrupt the INT3 IRET frame.
  1295. *
  1296. * See entry_{32,64}.S for more details.
  1297. */
  1298. /*
  1299. * We define the int3_magic() function in assembly to control the calling
  1300. * convention such that we can 'call' it from assembly.
  1301. */
  1302. extern void int3_magic(unsigned int *ptr); /* defined in asm */
  1303. asm (
  1304. " .pushsection .init.text, \"ax\", @progbits\n"
  1305. " .type int3_magic, @function\n"
  1306. "int3_magic:\n"
  1307. ANNOTATE_NOENDBR
  1308. " movl $1, (%" _ASM_ARG1 ")\n"
  1309. ASM_RET
  1310. " .size int3_magic, .-int3_magic\n"
  1311. " .popsection\n"
  1312. );
  1313. extern void int3_selftest_ip(void); /* defined in asm below */
  1314. static int __init
  1315. int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
  1316. {
  1317. unsigned long selftest = (unsigned long)&int3_selftest_ip;
  1318. struct die_args *args = data;
  1319. struct pt_regs *regs = args->regs;
  1320. OPTIMIZER_HIDE_VAR(selftest);
  1321. if (!regs || user_mode(regs))
  1322. return NOTIFY_DONE;
  1323. if (val != DIE_INT3)
  1324. return NOTIFY_DONE;
  1325. if (regs->ip - INT3_INSN_SIZE != selftest)
  1326. return NOTIFY_DONE;
  1327. int3_emulate_call(regs, (unsigned long)&int3_magic);
  1328. return NOTIFY_STOP;
  1329. }
  1330. /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
  1331. static noinline void __init int3_selftest(void)
  1332. {
  1333. static __initdata struct notifier_block int3_exception_nb = {
  1334. .notifier_call = int3_exception_notify,
  1335. .priority = INT_MAX-1, /* last */
  1336. };
  1337. unsigned int val = 0;
  1338. BUG_ON(register_die_notifier(&int3_exception_nb));
  1339. /*
  1340. * Basically: int3_magic(&val); but really complicated :-)
  1341. *
  1342. * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
  1343. * notifier above will emulate CALL for us.
  1344. */
  1345. asm volatile ("int3_selftest_ip:\n\t"
  1346. ANNOTATE_NOENDBR
  1347. " int3; nop; nop; nop; nop\n\t"
  1348. : ASM_CALL_CONSTRAINT
  1349. : __ASM_SEL_RAW(a, D) (&val)
  1350. : "memory");
  1351. BUG_ON(val != 1);
  1352. unregister_die_notifier(&int3_exception_nb);
  1353. }
  1354. static __initdata int __alt_reloc_selftest_addr;
  1355. extern void __init __alt_reloc_selftest(void *arg);
  1356. __visible noinline void __init __alt_reloc_selftest(void *arg)
  1357. {
  1358. WARN_ON(arg != &__alt_reloc_selftest_addr);
  1359. }
  1360. static noinline void __init alt_reloc_selftest(void)
  1361. {
  1362. /*
  1363. * Tests apply_relocation().
  1364. *
  1365. * This has a relative immediate (CALL) in a place other than the first
  1366. * instruction and additionally on x86_64 we get a RIP-relative LEA:
  1367. *
  1368. * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c
  1369. * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4
  1370. *
  1371. * Getting this wrong will either crash and burn or tickle the WARN
  1372. * above.
  1373. */
  1374. asm_inline volatile (
  1375. ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
  1376. : ASM_CALL_CONSTRAINT
  1377. : [mem] "m" (__alt_reloc_selftest_addr)
  1378. : _ASM_ARG1
  1379. );
  1380. }
  1381. void __init alternative_instructions(void)
  1382. {
  1383. int3_selftest();
  1384. /*
  1385. * The patching is not fully atomic, so try to avoid local
  1386. * interruptions that might execute the to be patched code.
  1387. * Other CPUs are not running.
  1388. */
  1389. stop_nmi();
  1390. /*
  1391. * Don't stop machine check exceptions while patching.
  1392. * MCEs only happen when something got corrupted and in this
  1393. * case we must do something about the corruption.
  1394. * Ignoring it is worse than an unlikely patching race.
  1395. * Also machine checks tend to be broadcast and if one CPU
  1396. * goes into machine check the others follow quickly, so we don't
  1397. * expect a machine check to cause undue problems during to code
  1398. * patching.
  1399. */
  1400. /*
  1401. * Make sure to set (artificial) features depending on used paravirt
  1402. * functions which can later influence alternative patching.
  1403. */
  1404. paravirt_set_cap();
  1405. __apply_fineibt(__retpoline_sites, __retpoline_sites_end,
  1406. __cfi_sites, __cfi_sites_end, true);
  1407. /*
  1408. * Rewrite the retpolines, must be done before alternatives since
  1409. * those can rewrite the retpoline thunks.
  1410. */
  1411. apply_retpolines(__retpoline_sites, __retpoline_sites_end);
  1412. apply_returns(__return_sites, __return_sites_end);
  1413. apply_alternatives(__alt_instructions, __alt_instructions_end);
  1414. /*
  1415. * Now all calls are established. Apply the call thunks if
  1416. * required.
  1417. */
  1418. callthunks_patch_builtin_calls();
  1419. /*
  1420. * Seal all functions that do not have their address taken.
  1421. */
  1422. apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
  1423. #ifdef CONFIG_SMP
  1424. /* Patch to UP if other cpus not imminent. */
  1425. if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
  1426. uniproc_patched = true;
  1427. alternatives_smp_module_add(NULL, "core kernel",
  1428. __smp_locks, __smp_locks_end,
  1429. _text, _etext);
  1430. }
  1431. if (!uniproc_patched || num_possible_cpus() == 1) {
  1432. free_init_pages("SMP alternatives",
  1433. (unsigned long)__smp_locks,
  1434. (unsigned long)__smp_locks_end);
  1435. }
  1436. #endif
  1437. restart_nmi();
  1438. alternatives_patched = 1;
  1439. alt_reloc_selftest();
  1440. }
  1441. /**
  1442. * text_poke_early - Update instructions on a live kernel at boot time
  1443. * @addr: address to modify
  1444. * @opcode: source of the copy
  1445. * @len: length to copy
  1446. *
  1447. * When you use this code to patch more than one byte of an instruction
  1448. * you need to make sure that other CPUs cannot execute this code in parallel.
  1449. * Also no thread must be currently preempted in the middle of these
  1450. * instructions. And on the local CPU you need to be protected against NMI or
  1451. * MCE handlers seeing an inconsistent instruction while you patch.
  1452. */
  1453. void __init_or_module text_poke_early(void *addr, const void *opcode,
  1454. size_t len)
  1455. {
  1456. unsigned long flags;
  1457. if (boot_cpu_has(X86_FEATURE_NX) &&
  1458. is_module_text_address((unsigned long)addr)) {
  1459. /*
  1460. * Modules text is marked initially as non-executable, so the
  1461. * code cannot be running and speculative code-fetches are
  1462. * prevented. Just change the code.
  1463. */
  1464. memcpy(addr, opcode, len);
  1465. } else {
  1466. local_irq_save(flags);
  1467. memcpy(addr, opcode, len);
  1468. sync_core();
  1469. local_irq_restore(flags);
  1470. /*
  1471. * Could also do a CLFLUSH here to speed up CPU recovery; but
  1472. * that causes hangs on some VIA CPUs.
  1473. */
  1474. }
  1475. }
  1476. typedef struct {
  1477. struct mm_struct *mm;
  1478. } temp_mm_state_t;
  1479. /*
  1480. * Using a temporary mm allows to set temporary mappings that are not accessible
  1481. * by other CPUs. Such mappings are needed to perform sensitive memory writes
  1482. * that override the kernel memory protections (e.g., W^X), without exposing the
  1483. * temporary page-table mappings that are required for these write operations to
  1484. * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
  1485. * mapping is torn down.
  1486. *
  1487. * Context: The temporary mm needs to be used exclusively by a single core. To
  1488. * harden security IRQs must be disabled while the temporary mm is
  1489. * loaded, thereby preventing interrupt handler bugs from overriding
  1490. * the kernel memory protection.
  1491. */
  1492. static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
  1493. {
  1494. temp_mm_state_t temp_state;
  1495. lockdep_assert_irqs_disabled();
  1496. /*
  1497. * Make sure not to be in TLB lazy mode, as otherwise we'll end up
  1498. * with a stale address space WITHOUT being in lazy mode after
  1499. * restoring the previous mm.
  1500. */
  1501. if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
  1502. leave_mm();
  1503. temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
  1504. switch_mm_irqs_off(NULL, mm, current);
  1505. /*
  1506. * If breakpoints are enabled, disable them while the temporary mm is
  1507. * used. Userspace might set up watchpoints on addresses that are used
  1508. * in the temporary mm, which would lead to wrong signals being sent or
  1509. * crashes.
  1510. *
  1511. * Note that breakpoints are not disabled selectively, which also causes
  1512. * kernel breakpoints (e.g., perf's) to be disabled. This might be
  1513. * undesirable, but still seems reasonable as the code that runs in the
  1514. * temporary mm should be short.
  1515. */
  1516. if (hw_breakpoint_active())
  1517. hw_breakpoint_disable();
  1518. return temp_state;
  1519. }
  1520. static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
  1521. {
  1522. lockdep_assert_irqs_disabled();
  1523. switch_mm_irqs_off(NULL, prev_state.mm, current);
  1524. /*
  1525. * Restore the breakpoints if they were disabled before the temporary mm
  1526. * was loaded.
  1527. */
  1528. if (hw_breakpoint_active())
  1529. hw_breakpoint_restore();
  1530. }
  1531. __ro_after_init struct mm_struct *poking_mm;
  1532. __ro_after_init unsigned long poking_addr;
  1533. static void text_poke_memcpy(void *dst, const void *src, size_t len)
  1534. {
  1535. memcpy(dst, src, len);
  1536. }
  1537. static void text_poke_memset(void *dst, const void *src, size_t len)
  1538. {
  1539. int c = *(const int *)src;
  1540. memset(dst, c, len);
  1541. }
  1542. typedef void text_poke_f(void *dst, const void *src, size_t len);
  1543. static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
  1544. {
  1545. bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
  1546. struct page *pages[2] = {NULL};
  1547. temp_mm_state_t prev;
  1548. unsigned long flags;
  1549. pte_t pte, *ptep;
  1550. spinlock_t *ptl;
  1551. pgprot_t pgprot;
  1552. /*
  1553. * While boot memory allocator is running we cannot use struct pages as
  1554. * they are not yet initialized. There is no way to recover.
  1555. */
  1556. BUG_ON(!after_bootmem);
  1557. if (!core_kernel_text((unsigned long)addr)) {
  1558. pages[0] = vmalloc_to_page(addr);
  1559. if (cross_page_boundary)
  1560. pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
  1561. } else {
  1562. pages[0] = virt_to_page(addr);
  1563. WARN_ON(!PageReserved(pages[0]));
  1564. if (cross_page_boundary)
  1565. pages[1] = virt_to_page(addr + PAGE_SIZE);
  1566. }
  1567. /*
  1568. * If something went wrong, crash and burn since recovery paths are not
  1569. * implemented.
  1570. */
  1571. BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
  1572. /*
  1573. * Map the page without the global bit, as TLB flushing is done with
  1574. * flush_tlb_mm_range(), which is intended for non-global PTEs.
  1575. */
  1576. pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
  1577. /*
  1578. * The lock is not really needed, but this allows to avoid open-coding.
  1579. */
  1580. ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
  1581. /*
  1582. * This must not fail; preallocated in poking_init().
  1583. */
  1584. VM_BUG_ON(!ptep);
  1585. local_irq_save(flags);
  1586. pte = mk_pte(pages[0], pgprot);
  1587. set_pte_at(poking_mm, poking_addr, ptep, pte);
  1588. if (cross_page_boundary) {
  1589. pte = mk_pte(pages[1], pgprot);
  1590. set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
  1591. }
  1592. /*
  1593. * Loading the temporary mm behaves as a compiler barrier, which
  1594. * guarantees that the PTE will be set at the time memcpy() is done.
  1595. */
  1596. prev = use_temporary_mm(poking_mm);
  1597. kasan_disable_current();
  1598. func((u8 *)poking_addr + offset_in_page(addr), src, len);
  1599. kasan_enable_current();
  1600. /*
  1601. * Ensure that the PTE is only cleared after the instructions of memcpy
  1602. * were issued by using a compiler barrier.
  1603. */
  1604. barrier();
  1605. pte_clear(poking_mm, poking_addr, ptep);
  1606. if (cross_page_boundary)
  1607. pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
  1608. /*
  1609. * Loading the previous page-table hierarchy requires a serializing
  1610. * instruction that already allows the core to see the updated version.
  1611. * Xen-PV is assumed to serialize execution in a similar manner.
  1612. */
  1613. unuse_temporary_mm(prev);
  1614. /*
  1615. * Flushing the TLB might involve IPIs, which would require enabled
  1616. * IRQs, but not if the mm is not used, as it is in this point.
  1617. */
  1618. flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
  1619. (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
  1620. PAGE_SHIFT, false);
  1621. if (func == text_poke_memcpy) {
  1622. /*
  1623. * If the text does not match what we just wrote then something is
  1624. * fundamentally screwy; there's nothing we can really do about that.
  1625. */
  1626. BUG_ON(memcmp(addr, src, len));
  1627. }
  1628. local_irq_restore(flags);
  1629. pte_unmap_unlock(ptep, ptl);
  1630. return addr;
  1631. }
  1632. /**
  1633. * text_poke - Update instructions on a live kernel
  1634. * @addr: address to modify
  1635. * @opcode: source of the copy
  1636. * @len: length to copy
  1637. *
  1638. * Only atomic text poke/set should be allowed when not doing early patching.
  1639. * It means the size must be writable atomically and the address must be aligned
  1640. * in a way that permits an atomic write. It also makes sure we fit on a single
  1641. * page.
  1642. *
  1643. * Note that the caller must ensure that if the modified code is part of a
  1644. * module, the module would not be removed during poking. This can be achieved
  1645. * by registering a module notifier, and ordering module removal and patching
  1646. * through a mutex.
  1647. */
  1648. void *text_poke(void *addr, const void *opcode, size_t len)
  1649. {
  1650. lockdep_assert_held(&text_mutex);
  1651. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1652. }
  1653. /**
  1654. * text_poke_kgdb - Update instructions on a live kernel by kgdb
  1655. * @addr: address to modify
  1656. * @opcode: source of the copy
  1657. * @len: length to copy
  1658. *
  1659. * Only atomic text poke/set should be allowed when not doing early patching.
  1660. * It means the size must be writable atomically and the address must be aligned
  1661. * in a way that permits an atomic write. It also makes sure we fit on a single
  1662. * page.
  1663. *
  1664. * Context: should only be used by kgdb, which ensures no other core is running,
  1665. * despite the fact it does not hold the text_mutex.
  1666. */
  1667. void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
  1668. {
  1669. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1670. }
  1671. void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
  1672. bool core_ok)
  1673. {
  1674. unsigned long start = (unsigned long)addr;
  1675. size_t patched = 0;
  1676. if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
  1677. return NULL;
  1678. while (patched < len) {
  1679. unsigned long ptr = start + patched;
  1680. size_t s;
  1681. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1682. __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
  1683. patched += s;
  1684. }
  1685. return addr;
  1686. }
  1687. /**
  1688. * text_poke_copy - Copy instructions into (an unused part of) RX memory
  1689. * @addr: address to modify
  1690. * @opcode: source of the copy
  1691. * @len: length to copy, could be more than 2x PAGE_SIZE
  1692. *
  1693. * Not safe against concurrent execution; useful for JITs to dump
  1694. * new code blocks into unused regions of RX memory. Can be used in
  1695. * conjunction with synchronize_rcu_tasks() to wait for existing
  1696. * execution to quiesce after having made sure no existing functions
  1697. * pointers are live.
  1698. */
  1699. void *text_poke_copy(void *addr, const void *opcode, size_t len)
  1700. {
  1701. mutex_lock(&text_mutex);
  1702. addr = text_poke_copy_locked(addr, opcode, len, false);
  1703. mutex_unlock(&text_mutex);
  1704. return addr;
  1705. }
  1706. /**
  1707. * text_poke_set - memset into (an unused part of) RX memory
  1708. * @addr: address to modify
  1709. * @c: the byte to fill the area with
  1710. * @len: length to copy, could be more than 2x PAGE_SIZE
  1711. *
  1712. * This is useful to overwrite unused regions of RX memory with illegal
  1713. * instructions.
  1714. */
  1715. void *text_poke_set(void *addr, int c, size_t len)
  1716. {
  1717. unsigned long start = (unsigned long)addr;
  1718. size_t patched = 0;
  1719. if (WARN_ON_ONCE(core_kernel_text(start)))
  1720. return NULL;
  1721. mutex_lock(&text_mutex);
  1722. while (patched < len) {
  1723. unsigned long ptr = start + patched;
  1724. size_t s;
  1725. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1726. __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
  1727. patched += s;
  1728. }
  1729. mutex_unlock(&text_mutex);
  1730. return addr;
  1731. }
  1732. static void do_sync_core(void *info)
  1733. {
  1734. sync_core();
  1735. }
  1736. void text_poke_sync(void)
  1737. {
  1738. on_each_cpu(do_sync_core, NULL, 1);
  1739. }
  1740. /*
  1741. * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
  1742. * this thing. When len == 6 everything is prefixed with 0x0f and we map
  1743. * opcode to Jcc.d8, using len to distinguish.
  1744. */
  1745. struct text_poke_loc {
  1746. /* addr := _stext + rel_addr */
  1747. s32 rel_addr;
  1748. s32 disp;
  1749. u8 len;
  1750. u8 opcode;
  1751. const u8 text[POKE_MAX_OPCODE_SIZE];
  1752. /* see text_poke_bp_batch() */
  1753. u8 old;
  1754. };
  1755. struct bp_patching_desc {
  1756. struct text_poke_loc *vec;
  1757. int nr_entries;
  1758. atomic_t refs;
  1759. };
  1760. static struct bp_patching_desc bp_desc;
  1761. static __always_inline
  1762. struct bp_patching_desc *try_get_desc(void)
  1763. {
  1764. struct bp_patching_desc *desc = &bp_desc;
  1765. if (!raw_atomic_inc_not_zero(&desc->refs))
  1766. return NULL;
  1767. return desc;
  1768. }
  1769. static __always_inline void put_desc(void)
  1770. {
  1771. struct bp_patching_desc *desc = &bp_desc;
  1772. smp_mb__before_atomic();
  1773. raw_atomic_dec(&desc->refs);
  1774. }
  1775. static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
  1776. {
  1777. return _stext + tp->rel_addr;
  1778. }
  1779. static __always_inline int patch_cmp(const void *key, const void *elt)
  1780. {
  1781. struct text_poke_loc *tp = (struct text_poke_loc *) elt;
  1782. if (key < text_poke_addr(tp))
  1783. return -1;
  1784. if (key > text_poke_addr(tp))
  1785. return 1;
  1786. return 0;
  1787. }
  1788. noinstr int poke_int3_handler(struct pt_regs *regs)
  1789. {
  1790. struct bp_patching_desc *desc;
  1791. struct text_poke_loc *tp;
  1792. int ret = 0;
  1793. void *ip;
  1794. if (user_mode(regs))
  1795. return 0;
  1796. /*
  1797. * Having observed our INT3 instruction, we now must observe
  1798. * bp_desc with non-zero refcount:
  1799. *
  1800. * bp_desc.refs = 1 INT3
  1801. * WMB RMB
  1802. * write INT3 if (bp_desc.refs != 0)
  1803. */
  1804. smp_rmb();
  1805. desc = try_get_desc();
  1806. if (!desc)
  1807. return 0;
  1808. /*
  1809. * Discount the INT3. See text_poke_bp_batch().
  1810. */
  1811. ip = (void *) regs->ip - INT3_INSN_SIZE;
  1812. /*
  1813. * Skip the binary search if there is a single member in the vector.
  1814. */
  1815. if (unlikely(desc->nr_entries > 1)) {
  1816. tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
  1817. sizeof(struct text_poke_loc),
  1818. patch_cmp);
  1819. if (!tp)
  1820. goto out_put;
  1821. } else {
  1822. tp = desc->vec;
  1823. if (text_poke_addr(tp) != ip)
  1824. goto out_put;
  1825. }
  1826. ip += tp->len;
  1827. switch (tp->opcode) {
  1828. case INT3_INSN_OPCODE:
  1829. /*
  1830. * Someone poked an explicit INT3, they'll want to handle it,
  1831. * do not consume.
  1832. */
  1833. goto out_put;
  1834. case RET_INSN_OPCODE:
  1835. int3_emulate_ret(regs);
  1836. break;
  1837. case CALL_INSN_OPCODE:
  1838. int3_emulate_call(regs, (long)ip + tp->disp);
  1839. break;
  1840. case JMP32_INSN_OPCODE:
  1841. case JMP8_INSN_OPCODE:
  1842. int3_emulate_jmp(regs, (long)ip + tp->disp);
  1843. break;
  1844. case 0x70 ... 0x7f: /* Jcc */
  1845. int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp);
  1846. break;
  1847. default:
  1848. BUG();
  1849. }
  1850. ret = 1;
  1851. out_put:
  1852. put_desc();
  1853. return ret;
  1854. }
  1855. #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
  1856. static struct text_poke_loc tp_vec[TP_VEC_MAX];
  1857. static int tp_vec_nr;
  1858. /**
  1859. * text_poke_bp_batch() -- update instructions on live kernel on SMP
  1860. * @tp: vector of instructions to patch
  1861. * @nr_entries: number of entries in the vector
  1862. *
  1863. * Modify multi-byte instruction by using int3 breakpoint on SMP.
  1864. * We completely avoid stop_machine() here, and achieve the
  1865. * synchronization using int3 breakpoint.
  1866. *
  1867. * The way it is done:
  1868. * - For each entry in the vector:
  1869. * - add a int3 trap to the address that will be patched
  1870. * - sync cores
  1871. * - For each entry in the vector:
  1872. * - update all but the first byte of the patched range
  1873. * - sync cores
  1874. * - For each entry in the vector:
  1875. * - replace the first byte (int3) by the first byte of
  1876. * replacing opcode
  1877. * - sync cores
  1878. */
  1879. static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
  1880. {
  1881. unsigned char int3 = INT3_INSN_OPCODE;
  1882. unsigned int i;
  1883. int do_sync;
  1884. lockdep_assert_held(&text_mutex);
  1885. bp_desc.vec = tp;
  1886. bp_desc.nr_entries = nr_entries;
  1887. /*
  1888. * Corresponds to the implicit memory barrier in try_get_desc() to
  1889. * ensure reading a non-zero refcount provides up to date bp_desc data.
  1890. */
  1891. atomic_set_release(&bp_desc.refs, 1);
  1892. /*
  1893. * Function tracing can enable thousands of places that need to be
  1894. * updated. This can take quite some time, and with full kernel debugging
  1895. * enabled, this could cause the softlockup watchdog to trigger.
  1896. * This function gets called every 256 entries added to be patched.
  1897. * Call cond_resched() here to make sure that other tasks can get scheduled
  1898. * while processing all the functions being patched.
  1899. */
  1900. cond_resched();
  1901. /*
  1902. * Corresponding read barrier in int3 notifier for making sure the
  1903. * nr_entries and handler are correctly ordered wrt. patching.
  1904. */
  1905. smp_wmb();
  1906. /*
  1907. * First step: add a int3 trap to the address that will be patched.
  1908. */
  1909. for (i = 0; i < nr_entries; i++) {
  1910. tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
  1911. text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
  1912. }
  1913. text_poke_sync();
  1914. /*
  1915. * Second step: update all but the first byte of the patched range.
  1916. */
  1917. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  1918. u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, };
  1919. u8 _new[POKE_MAX_OPCODE_SIZE+1];
  1920. const u8 *new = tp[i].text;
  1921. int len = tp[i].len;
  1922. if (len - INT3_INSN_SIZE > 0) {
  1923. memcpy(old + INT3_INSN_SIZE,
  1924. text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  1925. len - INT3_INSN_SIZE);
  1926. if (len == 6) {
  1927. _new[0] = 0x0f;
  1928. memcpy(_new + 1, new, 5);
  1929. new = _new;
  1930. }
  1931. text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  1932. new + INT3_INSN_SIZE,
  1933. len - INT3_INSN_SIZE);
  1934. do_sync++;
  1935. }
  1936. /*
  1937. * Emit a perf event to record the text poke, primarily to
  1938. * support Intel PT decoding which must walk the executable code
  1939. * to reconstruct the trace. The flow up to here is:
  1940. * - write INT3 byte
  1941. * - IPI-SYNC
  1942. * - write instruction tail
  1943. * At this point the actual control flow will be through the
  1944. * INT3 and handler and not hit the old or new instruction.
  1945. * Intel PT outputs FUP/TIP packets for the INT3, so the flow
  1946. * can still be decoded. Subsequently:
  1947. * - emit RECORD_TEXT_POKE with the new instruction
  1948. * - IPI-SYNC
  1949. * - write first byte
  1950. * - IPI-SYNC
  1951. * So before the text poke event timestamp, the decoder will see
  1952. * either the old instruction flow or FUP/TIP of INT3. After the
  1953. * text poke event timestamp, the decoder will see either the
  1954. * new instruction flow or FUP/TIP of INT3. Thus decoders can
  1955. * use the timestamp as the point at which to modify the
  1956. * executable code.
  1957. * The old instruction is recorded so that the event can be
  1958. * processed forwards or backwards.
  1959. */
  1960. perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len);
  1961. }
  1962. if (do_sync) {
  1963. /*
  1964. * According to Intel, this core syncing is very likely
  1965. * not necessary and we'd be safe even without it. But
  1966. * better safe than sorry (plus there's not only Intel).
  1967. */
  1968. text_poke_sync();
  1969. }
  1970. /*
  1971. * Third step: replace the first byte (int3) by the first byte of
  1972. * replacing opcode.
  1973. */
  1974. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  1975. u8 byte = tp[i].text[0];
  1976. if (tp[i].len == 6)
  1977. byte = 0x0f;
  1978. if (byte == INT3_INSN_OPCODE)
  1979. continue;
  1980. text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE);
  1981. do_sync++;
  1982. }
  1983. if (do_sync)
  1984. text_poke_sync();
  1985. /*
  1986. * Remove and wait for refs to be zero.
  1987. */
  1988. if (!atomic_dec_and_test(&bp_desc.refs))
  1989. atomic_cond_read_acquire(&bp_desc.refs, !VAL);
  1990. }
  1991. static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
  1992. const void *opcode, size_t len, const void *emulate)
  1993. {
  1994. struct insn insn;
  1995. int ret, i = 0;
  1996. if (len == 6)
  1997. i = 1;
  1998. memcpy((void *)tp->text, opcode+i, len-i);
  1999. if (!emulate)
  2000. emulate = opcode;
  2001. ret = insn_decode_kernel(&insn, emulate);
  2002. BUG_ON(ret < 0);
  2003. tp->rel_addr = addr - (void *)_stext;
  2004. tp->len = len;
  2005. tp->opcode = insn.opcode.bytes[0];
  2006. if (is_jcc32(&insn)) {
  2007. /*
  2008. * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
  2009. */
  2010. tp->opcode = insn.opcode.bytes[1] - 0x10;
  2011. }
  2012. switch (tp->opcode) {
  2013. case RET_INSN_OPCODE:
  2014. case JMP32_INSN_OPCODE:
  2015. case JMP8_INSN_OPCODE:
  2016. /*
  2017. * Control flow instructions without implied execution of the
  2018. * next instruction can be padded with INT3.
  2019. */
  2020. for (i = insn.length; i < len; i++)
  2021. BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
  2022. break;
  2023. default:
  2024. BUG_ON(len != insn.length);
  2025. }
  2026. switch (tp->opcode) {
  2027. case INT3_INSN_OPCODE:
  2028. case RET_INSN_OPCODE:
  2029. break;
  2030. case CALL_INSN_OPCODE:
  2031. case JMP32_INSN_OPCODE:
  2032. case JMP8_INSN_OPCODE:
  2033. case 0x70 ... 0x7f: /* Jcc */
  2034. tp->disp = insn.immediate.value;
  2035. break;
  2036. default: /* assume NOP */
  2037. switch (len) {
  2038. case 2: /* NOP2 -- emulate as JMP8+0 */
  2039. BUG_ON(memcmp(emulate, x86_nops[len], len));
  2040. tp->opcode = JMP8_INSN_OPCODE;
  2041. tp->disp = 0;
  2042. break;
  2043. case 5: /* NOP5 -- emulate as JMP32+0 */
  2044. BUG_ON(memcmp(emulate, x86_nops[len], len));
  2045. tp->opcode = JMP32_INSN_OPCODE;
  2046. tp->disp = 0;
  2047. break;
  2048. default: /* unknown instruction */
  2049. BUG();
  2050. }
  2051. break;
  2052. }
  2053. }
  2054. /*
  2055. * We hard rely on the tp_vec being ordered; ensure this is so by flushing
  2056. * early if needed.
  2057. */
  2058. static bool tp_order_fail(void *addr)
  2059. {
  2060. struct text_poke_loc *tp;
  2061. if (!tp_vec_nr)
  2062. return false;
  2063. if (!addr) /* force */
  2064. return true;
  2065. tp = &tp_vec[tp_vec_nr - 1];
  2066. if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
  2067. return true;
  2068. return false;
  2069. }
  2070. static void text_poke_flush(void *addr)
  2071. {
  2072. if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
  2073. text_poke_bp_batch(tp_vec, tp_vec_nr);
  2074. tp_vec_nr = 0;
  2075. }
  2076. }
  2077. void text_poke_finish(void)
  2078. {
  2079. text_poke_flush(NULL);
  2080. }
  2081. void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
  2082. {
  2083. struct text_poke_loc *tp;
  2084. text_poke_flush(addr);
  2085. tp = &tp_vec[tp_vec_nr++];
  2086. text_poke_loc_init(tp, addr, opcode, len, emulate);
  2087. }
  2088. /**
  2089. * text_poke_bp() -- update instructions on live kernel on SMP
  2090. * @addr: address to patch
  2091. * @opcode: opcode of new instruction
  2092. * @len: length to copy
  2093. * @emulate: instruction to be emulated
  2094. *
  2095. * Update a single instruction with the vector in the stack, avoiding
  2096. * dynamically allocated memory. This function should be used when it is
  2097. * not possible to allocate memory.
  2098. */
  2099. void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
  2100. {
  2101. struct text_poke_loc tp;
  2102. text_poke_loc_init(&tp, addr, opcode, len, emulate);
  2103. text_poke_bp_batch(&tp, 1);
  2104. }