x86/alternatives: Make JMPs more robust
[pandora-kernel.git] / arch / x86 / kernel / alternative.c
1 #include <linux/module.h>
2 #include <linux/sched.h>
3 #include <linux/mutex.h>
4 #include <linux/list.h>
5 #include <linux/stringify.h>
6 #include <linux/kprobes.h>
7 #include <linux/mm.h>
8 #include <linux/vmalloc.h>
9 #include <linux/memory.h>
10 #include <linux/stop_machine.h>
11 #include <linux/slab.h>
12 #include <asm/alternative.h>
13 #include <asm/sections.h>
14 #include <asm/pgtable.h>
15 #include <asm/mce.h>
16 #include <asm/nmi.h>
17 #include <asm/cacheflush.h>
18 #include <asm/tlbflush.h>
19 #include <asm/io.h>
20 #include <asm/fixmap.h>
21
22 #define MAX_PATCH_LEN (255-1)
23
24 #ifdef CONFIG_HOTPLUG_CPU
25 static int smp_alt_once;
26
27 static int __init bootonly(char *str)
28 {
29         smp_alt_once = 1;
30         return 1;
31 }
32 __setup("smp-alt-boot", bootonly);
33 #else
34 #define smp_alt_once 1
35 #endif
36
37 static int __initdata_or_module debug_alternative;
38
39 static int __init debug_alt(char *str)
40 {
41         debug_alternative = 1;
42         return 1;
43 }
44 __setup("debug-alternative", debug_alt);
45
46 static int noreplace_smp;
47
48 static int __init setup_noreplace_smp(char *str)
49 {
50         noreplace_smp = 1;
51         return 1;
52 }
53 __setup("noreplace-smp", setup_noreplace_smp);
54
55 #ifdef CONFIG_PARAVIRT
56 static int __initdata_or_module noreplace_paravirt = 0;
57
58 static int __init setup_noreplace_paravirt(char *str)
59 {
60         noreplace_paravirt = 1;
61         return 1;
62 }
63 __setup("noreplace-paravirt", setup_noreplace_paravirt);
64 #endif
65
66 #define DPRINTK(fmt, args...)                                           \
67 do {                                                                    \
68         if (debug_alternative)                                          \
69                 printk(KERN_DEBUG "%s: " fmt "\n", __func__, ##args);   \
70 } while (0)
71
72 #define DUMP_BYTES(buf, len, fmt, args...)                              \
73 do {                                                                    \
74         if (unlikely(debug_alternative)) {                              \
75                 int j;                                                  \
76                                                                         \
77                 if (!(len))                                             \
78                         break;                                          \
79                                                                         \
80                 printk(KERN_DEBUG fmt, ##args);                         \
81                 for (j = 0; j < (len) - 1; j++)                         \
82                         printk(KERN_CONT "%02hhx ", buf[j]);            \
83                 printk(KERN_CONT "%02hhx\n", buf[j]);                   \
84         }                                                               \
85 } while (0)
86
87 /*
88  * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
89  * that correspond to that nop. Getting from one nop to the next, we
90  * add to the array the offset that is equal to the sum of all sizes of
91  * nops preceding the one we are after.
92  *
93  * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
94  * nice symmetry of sizes of the previous nops.
95  */
96 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
97 static const unsigned char intelnops[] =
98 {
99         GENERIC_NOP1,
100         GENERIC_NOP2,
101         GENERIC_NOP3,
102         GENERIC_NOP4,
103         GENERIC_NOP5,
104         GENERIC_NOP6,
105         GENERIC_NOP7,
106         GENERIC_NOP8,
107         GENERIC_NOP5_ATOMIC
108 };
109 static const unsigned char * const intel_nops[ASM_NOP_MAX+2] =
110 {
111         NULL,
112         intelnops,
113         intelnops + 1,
114         intelnops + 1 + 2,
115         intelnops + 1 + 2 + 3,
116         intelnops + 1 + 2 + 3 + 4,
117         intelnops + 1 + 2 + 3 + 4 + 5,
118         intelnops + 1 + 2 + 3 + 4 + 5 + 6,
119         intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
120         intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
121 };
122 #endif
123
124 #ifdef K8_NOP1
125 static const unsigned char k8nops[] =
126 {
127         K8_NOP1,
128         K8_NOP2,
129         K8_NOP3,
130         K8_NOP4,
131         K8_NOP5,
132         K8_NOP6,
133         K8_NOP7,
134         K8_NOP8,
135         K8_NOP5_ATOMIC
136 };
137 static const unsigned char * const k8_nops[ASM_NOP_MAX+2] =
138 {
139         NULL,
140         k8nops,
141         k8nops + 1,
142         k8nops + 1 + 2,
143         k8nops + 1 + 2 + 3,
144         k8nops + 1 + 2 + 3 + 4,
145         k8nops + 1 + 2 + 3 + 4 + 5,
146         k8nops + 1 + 2 + 3 + 4 + 5 + 6,
147         k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
148         k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
149 };
150 #endif
151
152 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
153 static const unsigned char k7nops[] =
154 {
155         K7_NOP1,
156         K7_NOP2,
157         K7_NOP3,
158         K7_NOP4,
159         K7_NOP5,
160         K7_NOP6,
161         K7_NOP7,
162         K7_NOP8,
163         K7_NOP5_ATOMIC
164 };
165 static const unsigned char * const k7_nops[ASM_NOP_MAX+2] =
166 {
167         NULL,
168         k7nops,
169         k7nops + 1,
170         k7nops + 1 + 2,
171         k7nops + 1 + 2 + 3,
172         k7nops + 1 + 2 + 3 + 4,
173         k7nops + 1 + 2 + 3 + 4 + 5,
174         k7nops + 1 + 2 + 3 + 4 + 5 + 6,
175         k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
176         k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
177 };
178 #endif
179
180 #ifdef P6_NOP1
181 static const unsigned char p6nops[] =
182 {
183         P6_NOP1,
184         P6_NOP2,
185         P6_NOP3,
186         P6_NOP4,
187         P6_NOP5,
188         P6_NOP6,
189         P6_NOP7,
190         P6_NOP8,
191         P6_NOP5_ATOMIC
192 };
193 static const unsigned char * const p6_nops[ASM_NOP_MAX+2] =
194 {
195         NULL,
196         p6nops,
197         p6nops + 1,
198         p6nops + 1 + 2,
199         p6nops + 1 + 2 + 3,
200         p6nops + 1 + 2 + 3 + 4,
201         p6nops + 1 + 2 + 3 + 4 + 5,
202         p6nops + 1 + 2 + 3 + 4 + 5 + 6,
203         p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
204         p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
205 };
206 #endif
207
208 /* Initialize these to a safe default */
209 #ifdef CONFIG_X86_64
210 const unsigned char * const *ideal_nops = p6_nops;
211 #else
212 const unsigned char * const *ideal_nops = intel_nops;
213 #endif
214
215 void __init arch_init_ideal_nops(void)
216 {
217         switch (boot_cpu_data.x86_vendor) {
218         case X86_VENDOR_INTEL:
219                 /*
220                  * Due to a decoder implementation quirk, some
221                  * specific Intel CPUs actually perform better with
222                  * the "k8_nops" than with the SDM-recommended NOPs.
223                  */
224                 if (boot_cpu_data.x86 == 6 &&
225                     boot_cpu_data.x86_model >= 0x0f &&
226                     boot_cpu_data.x86_model != 0x1c &&
227                     boot_cpu_data.x86_model != 0x26 &&
228                     boot_cpu_data.x86_model != 0x27 &&
229                     boot_cpu_data.x86_model < 0x30) {
230                         ideal_nops = k8_nops;
231                 } else if (boot_cpu_has(X86_FEATURE_NOPL)) {
232                            ideal_nops = p6_nops;
233                 } else {
234 #ifdef CONFIG_X86_64
235                         ideal_nops = k8_nops;
236 #else
237                         ideal_nops = intel_nops;
238 #endif
239                 }
240                 break;
241         default:
242 #ifdef CONFIG_X86_64
243                 ideal_nops = k8_nops;
244 #else
245                 if (boot_cpu_has(X86_FEATURE_K8))
246                         ideal_nops = k8_nops;
247                 else if (boot_cpu_has(X86_FEATURE_K7))
248                         ideal_nops = k7_nops;
249                 else
250                         ideal_nops = intel_nops;
251 #endif
252         }
253 }
254
255 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
256 static void __init_or_module add_nops(void *insns, unsigned int len)
257 {
258         while (len > 0) {
259                 unsigned int noplen = len;
260                 if (noplen > ASM_NOP_MAX)
261                         noplen = ASM_NOP_MAX;
262                 memcpy(insns, ideal_nops[noplen], noplen);
263                 insns += noplen;
264                 len -= noplen;
265         }
266 }
267
268 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
269 extern s32 __smp_locks[], __smp_locks_end[];
270 void *text_poke_early(void *addr, const void *opcode, size_t len);
271
272 /*
273  * Are we looking at a near JMP with a 1 or 4-byte displacement.
274  */
275 static inline bool is_jmp(const u8 opcode)
276 {
277         return opcode == 0xeb || opcode == 0xe9;
278 }
279
280 static void __init_or_module
281 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insnbuf)
282 {
283         u8 *next_rip, *tgt_rip;
284         s32 n_dspl, o_dspl;
285         int repl_len;
286
287         if (a->replacementlen != 5)
288                 return;
289
290         o_dspl = *(s32 *)(insnbuf + 1);
291
292         /* next_rip of the replacement JMP */
293         next_rip = repl_insn + a->replacementlen;
294         /* target rip of the replacement JMP */
295         tgt_rip  = next_rip + o_dspl;
296         n_dspl = tgt_rip - orig_insn;
297
298         DPRINTK("target RIP: %p, new_displ: 0x%x", tgt_rip, n_dspl);
299
300         if (tgt_rip - orig_insn >= 0) {
301                 if (n_dspl - 2 <= 127)
302                         goto two_byte_jmp;
303                 else
304                         goto five_byte_jmp;
305         /* negative offset */
306         } else {
307                 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
308                         goto two_byte_jmp;
309                 else
310                         goto five_byte_jmp;
311         }
312
313 two_byte_jmp:
314         n_dspl -= 2;
315
316         insnbuf[0] = 0xeb;
317         insnbuf[1] = (s8)n_dspl;
318         add_nops(insnbuf + 2, 3);
319
320         repl_len = 2;
321         goto done;
322
323 five_byte_jmp:
324         n_dspl -= 5;
325
326         insnbuf[0] = 0xe9;
327         *(s32 *)&insnbuf[1] = n_dspl;
328
329         repl_len = 5;
330
331 done:
332
333         DPRINTK("final displ: 0x%08x, JMP 0x%lx",
334                 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
335 }
336
337 /*
338  * Replace instructions with better alternatives for this CPU type. This runs
339  * before SMP is initialized to avoid SMP problems with self modifying code.
340  * This implies that asymmetric systems where APs have less capabilities than
341  * the boot processor are not handled. Tough. Make sure you disable such
342  * features by hand.
343  */
344 void __init_or_module apply_alternatives(struct alt_instr *start,
345                                          struct alt_instr *end)
346 {
347         struct alt_instr *a;
348         u8 *instr, *replacement;
349         u8 insnbuf[MAX_PATCH_LEN];
350
351         DPRINTK("alt table %p -> %p", start, end);
352         /*
353          * The scan order should be from start to end. A later scanned
354          * alternative code can overwrite previously scanned alternative code.
355          * Some kernel functions (e.g. memcpy, memset, etc) use this order to
356          * patch code.
357          *
358          * So be careful if you want to change the scan order to any other
359          * order.
360          */
361         for (a = start; a < end; a++) {
362                 int insnbuf_sz = 0;
363
364                 instr = (u8 *)&a->instr_offset + a->instr_offset;
365                 replacement = (u8 *)&a->repl_offset + a->repl_offset;
366                 BUG_ON(a->instrlen > sizeof(insnbuf));
367                 BUG_ON(a->cpuid >= NCAPINTS*32);
368                 if (!boot_cpu_has(a->cpuid))
369                         continue;
370
371                 DPRINTK("feat: %d*32+%d, old: (%p, len: %d), repl: (%p, len: %d)",
372                         a->cpuid >> 5,
373                         a->cpuid & 0x1f,
374                         instr, a->instrlen,
375                         replacement, a->replacementlen);
376
377                 DUMP_BYTES(instr, a->instrlen, "%p: old_insn: ", instr);
378                 DUMP_BYTES(replacement, a->replacementlen, "%p: rpl_insn: ", replacement);
379
380                 memcpy(insnbuf, replacement, a->replacementlen);
381                 insnbuf_sz = a->replacementlen;
382
383                 /* 0xe8 is a relative jump; fix the offset. */
384                 if (*insnbuf == 0xe8 && a->replacementlen == 5) {
385                         *(s32 *)(insnbuf + 1) += replacement - instr;
386                         DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
387                                 *(s32 *)(insnbuf + 1),
388                                 (unsigned long)instr + *(s32 *)(insnbuf + 1) + 5);
389                 }
390
391                 if (a->replacementlen && is_jmp(replacement[0]))
392                         recompute_jump(a, instr, replacement, insnbuf);
393
394                 if (a->instrlen > a->replacementlen) {
395                         add_nops(insnbuf + a->replacementlen,
396                                  a->instrlen - a->replacementlen);
397                         insnbuf_sz += a->instrlen - a->replacementlen;
398                 }
399                 DUMP_BYTES(insnbuf, insnbuf_sz, "%p: final_insn: ", instr);
400
401                 text_poke_early(instr, insnbuf, insnbuf_sz);
402         }
403 }
404
405 #ifdef CONFIG_SMP
406 static void alternatives_smp_lock(const s32 *start, const s32 *end,
407                                   u8 *text, u8 *text_end)
408 {
409         const s32 *poff;
410
411         mutex_lock(&text_mutex);
412         for (poff = start; poff < end; poff++) {
413                 u8 *ptr = (u8 *)poff + *poff;
414
415                 if (!*poff || ptr < text || ptr >= text_end)
416                         continue;
417                 /* turn DS segment override prefix into lock prefix */
418                 if (*ptr == 0x3e)
419                         text_poke(ptr, ((unsigned char []){0xf0}), 1);
420         };
421         mutex_unlock(&text_mutex);
422 }
423
424 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
425                                     u8 *text, u8 *text_end)
426 {
427         const s32 *poff;
428
429         if (noreplace_smp)
430                 return;
431
432         mutex_lock(&text_mutex);
433         for (poff = start; poff < end; poff++) {
434                 u8 *ptr = (u8 *)poff + *poff;
435
436                 if (!*poff || ptr < text || ptr >= text_end)
437                         continue;
438                 /* turn lock prefix into DS segment override prefix */
439                 if (*ptr == 0xf0)
440                         text_poke(ptr, ((unsigned char []){0x3E}), 1);
441         };
442         mutex_unlock(&text_mutex);
443 }
444
445 struct smp_alt_module {
446         /* what is this ??? */
447         struct module   *mod;
448         char            *name;
449
450         /* ptrs to lock prefixes */
451         const s32       *locks;
452         const s32       *locks_end;
453
454         /* .text segment, needed to avoid patching init code ;) */
455         u8              *text;
456         u8              *text_end;
457
458         struct list_head next;
459 };
460 static LIST_HEAD(smp_alt_modules);
461 static DEFINE_MUTEX(smp_alt);
462 static int smp_mode = 1;        /* protected by smp_alt */
463
464 void __init_or_module alternatives_smp_module_add(struct module *mod,
465                                                   char *name,
466                                                   void *locks, void *locks_end,
467                                                   void *text,  void *text_end)
468 {
469         struct smp_alt_module *smp;
470
471         if (noreplace_smp)
472                 return;
473
474         if (smp_alt_once) {
475                 if (boot_cpu_has(X86_FEATURE_UP))
476                         alternatives_smp_unlock(locks, locks_end,
477                                                 text, text_end);
478                 return;
479         }
480
481         smp = kzalloc(sizeof(*smp), GFP_KERNEL);
482         if (NULL == smp)
483                 return; /* we'll run the (safe but slow) SMP code then ... */
484
485         smp->mod        = mod;
486         smp->name       = name;
487         smp->locks      = locks;
488         smp->locks_end  = locks_end;
489         smp->text       = text;
490         smp->text_end   = text_end;
491         DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
492                 smp->locks, smp->locks_end,
493                 smp->text, smp->text_end, smp->name);
494
495         mutex_lock(&smp_alt);
496         list_add_tail(&smp->next, &smp_alt_modules);
497         if (boot_cpu_has(X86_FEATURE_UP))
498                 alternatives_smp_unlock(smp->locks, smp->locks_end,
499                                         smp->text, smp->text_end);
500         mutex_unlock(&smp_alt);
501 }
502
503 void __init_or_module alternatives_smp_module_del(struct module *mod)
504 {
505         struct smp_alt_module *item;
506
507         if (smp_alt_once || noreplace_smp)
508                 return;
509
510         mutex_lock(&smp_alt);
511         list_for_each_entry(item, &smp_alt_modules, next) {
512                 if (mod != item->mod)
513                         continue;
514                 list_del(&item->next);
515                 mutex_unlock(&smp_alt);
516                 DPRINTK("%s\n", item->name);
517                 kfree(item);
518                 return;
519         }
520         mutex_unlock(&smp_alt);
521 }
522
523 bool skip_smp_alternatives;
524 void alternatives_smp_switch(int smp)
525 {
526         struct smp_alt_module *mod;
527
528 #ifdef CONFIG_LOCKDEP
529         /*
530          * Older binutils section handling bug prevented
531          * alternatives-replacement from working reliably.
532          *
533          * If this still occurs then you should see a hang
534          * or crash shortly after this line:
535          */
536         printk("lockdep: fixing up alternatives.\n");
537 #endif
538
539         if (noreplace_smp || smp_alt_once || skip_smp_alternatives)
540                 return;
541         BUG_ON(!smp && (num_online_cpus() > 1));
542
543         mutex_lock(&smp_alt);
544
545         /*
546          * Avoid unnecessary switches because it forces JIT based VMs to
547          * throw away all cached translations, which can be quite costly.
548          */
549         if (smp == smp_mode) {
550                 /* nothing */
551         } else if (smp) {
552                 printk(KERN_INFO "SMP alternatives: switching to SMP code\n");
553                 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
554                 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
555                 list_for_each_entry(mod, &smp_alt_modules, next)
556                         alternatives_smp_lock(mod->locks, mod->locks_end,
557                                               mod->text, mod->text_end);
558         } else {
559                 printk(KERN_INFO "SMP alternatives: switching to UP code\n");
560                 set_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
561                 set_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
562                 list_for_each_entry(mod, &smp_alt_modules, next)
563                         alternatives_smp_unlock(mod->locks, mod->locks_end,
564                                                 mod->text, mod->text_end);
565         }
566         smp_mode = smp;
567         mutex_unlock(&smp_alt);
568 }
569
570 /* Return 1 if the address range is reserved for smp-alternatives */
571 int alternatives_text_reserved(void *start, void *end)
572 {
573         struct smp_alt_module *mod;
574         const s32 *poff;
575         u8 *text_start = start;
576         u8 *text_end = end;
577
578         list_for_each_entry(mod, &smp_alt_modules, next) {
579                 if (mod->text > text_end || mod->text_end < text_start)
580                         continue;
581                 for (poff = mod->locks; poff < mod->locks_end; poff++) {
582                         const u8 *ptr = (const u8 *)poff + *poff;
583
584                         if (text_start <= ptr && text_end > ptr)
585                                 return 1;
586                 }
587         }
588
589         return 0;
590 }
591 #endif /* CONFIG_SMP */
592
593 #ifdef CONFIG_PARAVIRT
594 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
595                                      struct paravirt_patch_site *end)
596 {
597         struct paravirt_patch_site *p;
598         char insnbuf[MAX_PATCH_LEN];
599
600         if (noreplace_paravirt)
601                 return;
602
603         for (p = start; p < end; p++) {
604                 unsigned int used;
605
606                 BUG_ON(p->len > MAX_PATCH_LEN);
607                 /* prep the buffer with the original instructions */
608                 memcpy(insnbuf, p->instr, p->len);
609                 used = pv_init_ops.patch(p->instrtype, p->clobbers, insnbuf,
610                                          (unsigned long)p->instr, p->len);
611
612                 BUG_ON(used > p->len);
613
614                 /* Pad the rest with nops */
615                 add_nops(insnbuf + used, p->len - used);
616                 text_poke_early(p->instr, insnbuf, p->len);
617         }
618 }
619 extern struct paravirt_patch_site __start_parainstructions[],
620         __stop_parainstructions[];
621 #endif  /* CONFIG_PARAVIRT */
622
623 void __init alternative_instructions(void)
624 {
625         /* The patching is not fully atomic, so try to avoid local interruptions
626            that might execute the to be patched code.
627            Other CPUs are not running. */
628         stop_nmi();
629
630         /*
631          * Don't stop machine check exceptions while patching.
632          * MCEs only happen when something got corrupted and in this
633          * case we must do something about the corruption.
634          * Ignoring it is worse than a unlikely patching race.
635          * Also machine checks tend to be broadcast and if one CPU
636          * goes into machine check the others follow quickly, so we don't
637          * expect a machine check to cause undue problems during to code
638          * patching.
639          */
640
641         apply_alternatives(__alt_instructions, __alt_instructions_end);
642
643         /* switch to patch-once-at-boottime-only mode and free the
644          * tables in case we know the number of CPUs will never ever
645          * change */
646 #ifdef CONFIG_HOTPLUG_CPU
647         if (num_possible_cpus() < 2)
648                 smp_alt_once = 1;
649 #endif
650
651 #ifdef CONFIG_SMP
652         if (smp_alt_once) {
653                 if (1 == num_possible_cpus()) {
654                         printk(KERN_INFO "SMP alternatives: switching to UP code\n");
655                         set_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
656                         set_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
657
658                         alternatives_smp_unlock(__smp_locks, __smp_locks_end,
659                                                 _text, _etext);
660                 }
661         } else {
662                 alternatives_smp_module_add(NULL, "core kernel",
663                                             __smp_locks, __smp_locks_end,
664                                             _text, _etext);
665
666                 /* Only switch to UP mode if we don't immediately boot others */
667                 if (num_present_cpus() == 1 || setup_max_cpus <= 1)
668                         alternatives_smp_switch(0);
669         }
670 #endif
671         apply_paravirt(__parainstructions, __parainstructions_end);
672
673         if (smp_alt_once)
674                 free_init_pages("SMP alternatives",
675                                 (unsigned long)__smp_locks,
676                                 (unsigned long)__smp_locks_end);
677
678         restart_nmi();
679 }
680
681 /**
682  * text_poke_early - Update instructions on a live kernel at boot time
683  * @addr: address to modify
684  * @opcode: source of the copy
685  * @len: length to copy
686  *
687  * When you use this code to patch more than one byte of an instruction
688  * you need to make sure that other CPUs cannot execute this code in parallel.
689  * Also no thread must be currently preempted in the middle of these
690  * instructions. And on the local CPU you need to be protected again NMI or MCE
691  * handlers seeing an inconsistent instruction while you patch.
692  */
693 void *__init_or_module text_poke_early(void *addr, const void *opcode,
694                                               size_t len)
695 {
696         unsigned long flags;
697         local_irq_save(flags);
698         memcpy(addr, opcode, len);
699         sync_core();
700         local_irq_restore(flags);
701         /* Could also do a CLFLUSH here to speed up CPU recovery; but
702            that causes hangs on some VIA CPUs. */
703         return addr;
704 }
705
706 /**
707  * text_poke - Update instructions on a live kernel
708  * @addr: address to modify
709  * @opcode: source of the copy
710  * @len: length to copy
711  *
712  * Only atomic text poke/set should be allowed when not doing early patching.
713  * It means the size must be writable atomically and the address must be aligned
714  * in a way that permits an atomic write. It also makes sure we fit on a single
715  * page.
716  *
717  * Note: Must be called under text_mutex.
718  */
719 void *__kprobes text_poke(void *addr, const void *opcode, size_t len)
720 {
721         unsigned long flags;
722         char *vaddr;
723         struct page *pages[2];
724         int i;
725
726         if (!core_kernel_text((unsigned long)addr)) {
727                 pages[0] = vmalloc_to_page(addr);
728                 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
729         } else {
730                 pages[0] = virt_to_page(addr);
731                 WARN_ON(!PageReserved(pages[0]));
732                 pages[1] = virt_to_page(addr + PAGE_SIZE);
733         }
734         BUG_ON(!pages[0]);
735         local_irq_save(flags);
736         set_fixmap(FIX_TEXT_POKE0, page_to_phys(pages[0]));
737         if (pages[1])
738                 set_fixmap(FIX_TEXT_POKE1, page_to_phys(pages[1]));
739         vaddr = (char *)fix_to_virt(FIX_TEXT_POKE0);
740         memcpy(&vaddr[(unsigned long)addr & ~PAGE_MASK], opcode, len);
741         clear_fixmap(FIX_TEXT_POKE0);
742         if (pages[1])
743                 clear_fixmap(FIX_TEXT_POKE1);
744         local_flush_tlb();
745         sync_core();
746         /* Could also do a CLFLUSH here to speed up CPU recovery; but
747            that causes hangs on some VIA CPUs. */
748         for (i = 0; i < len; i++)
749                 BUG_ON(((char *)addr)[i] != ((char *)opcode)[i]);
750         local_irq_restore(flags);
751         return addr;
752 }
753
754 /*
755  * Cross-modifying kernel text with stop_machine().
756  * This code originally comes from immediate value.
757  */
758 static atomic_t stop_machine_first;
759 static int wrote_text;
760
761 struct text_poke_params {
762         struct text_poke_param *params;
763         int nparams;
764 };
765
766 static int __kprobes stop_machine_text_poke(void *data)
767 {
768         struct text_poke_params *tpp = data;
769         struct text_poke_param *p;
770         int i;
771
772         if (atomic_dec_and_test(&stop_machine_first)) {
773                 for (i = 0; i < tpp->nparams; i++) {
774                         p = &tpp->params[i];
775                         text_poke(p->addr, p->opcode, p->len);
776                 }
777                 smp_wmb();      /* Make sure other cpus see that this has run */
778                 wrote_text = 1;
779         } else {
780                 while (!wrote_text)
781                         cpu_relax();
782                 smp_mb();       /* Load wrote_text before following execution */
783         }
784
785         for (i = 0; i < tpp->nparams; i++) {
786                 p = &tpp->params[i];
787                 flush_icache_range((unsigned long)p->addr,
788                                    (unsigned long)p->addr + p->len);
789         }
790         /*
791          * Intel Archiecture Software Developer's Manual section 7.1.3 specifies
792          * that a core serializing instruction such as "cpuid" should be
793          * executed on _each_ core before the new instruction is made visible.
794          */
795         sync_core();
796         return 0;
797 }
798
799 /**
800  * text_poke_smp - Update instructions on a live kernel on SMP
801  * @addr: address to modify
802  * @opcode: source of the copy
803  * @len: length to copy
804  *
805  * Modify multi-byte instruction by using stop_machine() on SMP. This allows
806  * user to poke/set multi-byte text on SMP. Only non-NMI/MCE code modifying
807  * should be allowed, since stop_machine() does _not_ protect code against
808  * NMI and MCE.
809  *
810  * Note: Must be called under get_online_cpus() and text_mutex.
811  */
812 void *__kprobes text_poke_smp(void *addr, const void *opcode, size_t len)
813 {
814         struct text_poke_params tpp;
815         struct text_poke_param p;
816
817         p.addr = addr;
818         p.opcode = opcode;
819         p.len = len;
820         tpp.params = &p;
821         tpp.nparams = 1;
822         atomic_set(&stop_machine_first, 1);
823         wrote_text = 0;
824         /* Use __stop_machine() because the caller already got online_cpus. */
825         __stop_machine(stop_machine_text_poke, (void *)&tpp, cpu_online_mask);
826         return addr;
827 }
828
829 /**
830  * text_poke_smp_batch - Update instructions on a live kernel on SMP
831  * @params: an array of text_poke parameters
832  * @n: the number of elements in params.
833  *
834  * Modify multi-byte instruction by using stop_machine() on SMP. Since the
835  * stop_machine() is heavy task, it is better to aggregate text_poke requests
836  * and do it once if possible.
837  *
838  * Note: Must be called under get_online_cpus() and text_mutex.
839  */
840 void __kprobes text_poke_smp_batch(struct text_poke_param *params, int n)
841 {
842         struct text_poke_params tpp = {.params = params, .nparams = n};
843
844         atomic_set(&stop_machine_first, 1);
845         wrote_text = 0;
846         __stop_machine(stop_machine_text_poke, (void *)&tpp, cpu_online_mask);
847 }