GNU Linux-libre 5.15.72-gnu
[releases.git] / arch / powerpc / kernel / rtas.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  * Procedures for interfacing to the RTAS on CHRP machines.
5  *
6  * Peter Bergner, IBM   March 2001.
7  * Copyright (C) 2001 IBM.
8  */
9
10 #include <linux/stdarg.h>
11 #include <linux/kernel.h>
12 #include <linux/types.h>
13 #include <linux/spinlock.h>
14 #include <linux/export.h>
15 #include <linux/init.h>
16 #include <linux/capability.h>
17 #include <linux/delay.h>
18 #include <linux/cpu.h>
19 #include <linux/sched.h>
20 #include <linux/smp.h>
21 #include <linux/completion.h>
22 #include <linux/cpumask.h>
23 #include <linux/memblock.h>
24 #include <linux/slab.h>
25 #include <linux/reboot.h>
26 #include <linux/syscalls.h>
27
28 #include <asm/interrupt.h>
29 #include <asm/prom.h>
30 #include <asm/rtas.h>
31 #include <asm/hvcall.h>
32 #include <asm/machdep.h>
33 #include <asm/firmware.h>
34 #include <asm/page.h>
35 #include <asm/param.h>
36 #include <asm/delay.h>
37 #include <linux/uaccess.h>
38 #include <asm/udbg.h>
39 #include <asm/syscalls.h>
40 #include <asm/smp.h>
41 #include <linux/atomic.h>
42 #include <asm/time.h>
43 #include <asm/mmu.h>
44 #include <asm/topology.h>
45 #include <asm/paca.h>
46
47 /* This is here deliberately so it's only used in this file */
48 void enter_rtas(unsigned long);
49
50 static inline void do_enter_rtas(unsigned long args)
51 {
52         unsigned long msr;
53
54         /*
55          * Make sure MSR[RI] is currently enabled as it will be forced later
56          * in enter_rtas.
57          */
58         msr = mfmsr();
59         BUG_ON(!(msr & MSR_RI));
60
61         enter_rtas(args);
62
63         srr_regs_clobbered(); /* rtas uses SRRs, invalidate */
64 }
65
66 struct rtas_t rtas = {
67         .lock = __ARCH_SPIN_LOCK_UNLOCKED
68 };
69 EXPORT_SYMBOL(rtas);
70
71 DEFINE_SPINLOCK(rtas_data_buf_lock);
72 EXPORT_SYMBOL(rtas_data_buf_lock);
73
74 char rtas_data_buf[RTAS_DATA_BUF_SIZE] __cacheline_aligned;
75 EXPORT_SYMBOL(rtas_data_buf);
76
77 unsigned long rtas_rmo_buf;
78
79 /*
80  * If non-NULL, this gets called when the kernel terminates.
81  * This is done like this so rtas_flash can be a module.
82  */
83 void (*rtas_flash_term_hook)(int);
84 EXPORT_SYMBOL(rtas_flash_term_hook);
85
86 /* RTAS use home made raw locking instead of spin_lock_irqsave
87  * because those can be called from within really nasty contexts
88  * such as having the timebase stopped which would lockup with
89  * normal locks and spinlock debugging enabled
90  */
91 static unsigned long lock_rtas(void)
92 {
93         unsigned long flags;
94
95         local_irq_save(flags);
96         preempt_disable();
97         arch_spin_lock(&rtas.lock);
98         return flags;
99 }
100
101 static void unlock_rtas(unsigned long flags)
102 {
103         arch_spin_unlock(&rtas.lock);
104         local_irq_restore(flags);
105         preempt_enable();
106 }
107
108 /*
109  * call_rtas_display_status and call_rtas_display_status_delay
110  * are designed only for very early low-level debugging, which
111  * is why the token is hard-coded to 10.
112  */
113 static void call_rtas_display_status(unsigned char c)
114 {
115         unsigned long s;
116
117         if (!rtas.base)
118                 return;
119
120         s = lock_rtas();
121         rtas_call_unlocked(&rtas.args, 10, 1, 1, NULL, c);
122         unlock_rtas(s);
123 }
124
125 static void call_rtas_display_status_delay(char c)
126 {
127         static int pending_newline = 0;  /* did last write end with unprinted newline? */
128         static int width = 16;
129
130         if (c == '\n') {        
131                 while (width-- > 0)
132                         call_rtas_display_status(' ');
133                 width = 16;
134                 mdelay(500);
135                 pending_newline = 1;
136         } else {
137                 if (pending_newline) {
138                         call_rtas_display_status('\r');
139                         call_rtas_display_status('\n');
140                 } 
141                 pending_newline = 0;
142                 if (width--) {
143                         call_rtas_display_status(c);
144                         udelay(10000);
145                 }
146         }
147 }
148
149 void __init udbg_init_rtas_panel(void)
150 {
151         udbg_putc = call_rtas_display_status_delay;
152 }
153
154 #ifdef CONFIG_UDBG_RTAS_CONSOLE
155
156 /* If you think you're dying before early_init_dt_scan_rtas() does its
157  * work, you can hard code the token values for your firmware here and
158  * hardcode rtas.base/entry etc.
159  */
160 static unsigned int rtas_putchar_token = RTAS_UNKNOWN_SERVICE;
161 static unsigned int rtas_getchar_token = RTAS_UNKNOWN_SERVICE;
162
163 static void udbg_rtascon_putc(char c)
164 {
165         int tries;
166
167         if (!rtas.base)
168                 return;
169
170         /* Add CRs before LFs */
171         if (c == '\n')
172                 udbg_rtascon_putc('\r');
173
174         /* if there is more than one character to be displayed, wait a bit */
175         for (tries = 0; tries < 16; tries++) {
176                 if (rtas_call(rtas_putchar_token, 1, 1, NULL, c) == 0)
177                         break;
178                 udelay(1000);
179         }
180 }
181
182 static int udbg_rtascon_getc_poll(void)
183 {
184         int c;
185
186         if (!rtas.base)
187                 return -1;
188
189         if (rtas_call(rtas_getchar_token, 0, 2, &c))
190                 return -1;
191
192         return c;
193 }
194
195 static int udbg_rtascon_getc(void)
196 {
197         int c;
198
199         while ((c = udbg_rtascon_getc_poll()) == -1)
200                 ;
201
202         return c;
203 }
204
205
206 void __init udbg_init_rtas_console(void)
207 {
208         udbg_putc = udbg_rtascon_putc;
209         udbg_getc = udbg_rtascon_getc;
210         udbg_getc_poll = udbg_rtascon_getc_poll;
211 }
212 #endif /* CONFIG_UDBG_RTAS_CONSOLE */
213
214 void rtas_progress(char *s, unsigned short hex)
215 {
216         struct device_node *root;
217         int width;
218         const __be32 *p;
219         char *os;
220         static int display_character, set_indicator;
221         static int display_width, display_lines, form_feed;
222         static const int *row_width;
223         static DEFINE_SPINLOCK(progress_lock);
224         static int current_line;
225         static int pending_newline = 0;  /* did last write end with unprinted newline? */
226
227         if (!rtas.base)
228                 return;
229
230         if (display_width == 0) {
231                 display_width = 0x10;
232                 if ((root = of_find_node_by_path("/rtas"))) {
233                         if ((p = of_get_property(root,
234                                         "ibm,display-line-length", NULL)))
235                                 display_width = be32_to_cpu(*p);
236                         if ((p = of_get_property(root,
237                                         "ibm,form-feed", NULL)))
238                                 form_feed = be32_to_cpu(*p);
239                         if ((p = of_get_property(root,
240                                         "ibm,display-number-of-lines", NULL)))
241                                 display_lines = be32_to_cpu(*p);
242                         row_width = of_get_property(root,
243                                         "ibm,display-truncation-length", NULL);
244                         of_node_put(root);
245                 }
246                 display_character = rtas_token("display-character");
247                 set_indicator = rtas_token("set-indicator");
248         }
249
250         if (display_character == RTAS_UNKNOWN_SERVICE) {
251                 /* use hex display if available */
252                 if (set_indicator != RTAS_UNKNOWN_SERVICE)
253                         rtas_call(set_indicator, 3, 1, NULL, 6, 0, hex);
254                 return;
255         }
256
257         spin_lock(&progress_lock);
258
259         /*
260          * Last write ended with newline, but we didn't print it since
261          * it would just clear the bottom line of output. Print it now
262          * instead.
263          *
264          * If no newline is pending and form feed is supported, clear the
265          * display with a form feed; otherwise, print a CR to start output
266          * at the beginning of the line.
267          */
268         if (pending_newline) {
269                 rtas_call(display_character, 1, 1, NULL, '\r');
270                 rtas_call(display_character, 1, 1, NULL, '\n');
271                 pending_newline = 0;
272         } else {
273                 current_line = 0;
274                 if (form_feed)
275                         rtas_call(display_character, 1, 1, NULL,
276                                   (char)form_feed);
277                 else
278                         rtas_call(display_character, 1, 1, NULL, '\r');
279         }
280  
281         if (row_width)
282                 width = row_width[current_line];
283         else
284                 width = display_width;
285         os = s;
286         while (*os) {
287                 if (*os == '\n' || *os == '\r') {
288                         /* If newline is the last character, save it
289                          * until next call to avoid bumping up the
290                          * display output.
291                          */
292                         if (*os == '\n' && !os[1]) {
293                                 pending_newline = 1;
294                                 current_line++;
295                                 if (current_line > display_lines-1)
296                                         current_line = display_lines-1;
297                                 spin_unlock(&progress_lock);
298                                 return;
299                         }
300  
301                         /* RTAS wants CR-LF, not just LF */
302  
303                         if (*os == '\n') {
304                                 rtas_call(display_character, 1, 1, NULL, '\r');
305                                 rtas_call(display_character, 1, 1, NULL, '\n');
306                         } else {
307                                 /* CR might be used to re-draw a line, so we'll
308                                  * leave it alone and not add LF.
309                                  */
310                                 rtas_call(display_character, 1, 1, NULL, *os);
311                         }
312  
313                         if (row_width)
314                                 width = row_width[current_line];
315                         else
316                                 width = display_width;
317                 } else {
318                         width--;
319                         rtas_call(display_character, 1, 1, NULL, *os);
320                 }
321  
322                 os++;
323  
324                 /* if we overwrite the screen length */
325                 if (width <= 0)
326                         while ((*os != 0) && (*os != '\n') && (*os != '\r'))
327                                 os++;
328         }
329  
330         spin_unlock(&progress_lock);
331 }
332 EXPORT_SYMBOL(rtas_progress);           /* needed by rtas_flash module */
333
334 int rtas_token(const char *service)
335 {
336         const __be32 *tokp;
337         if (rtas.dev == NULL)
338                 return RTAS_UNKNOWN_SERVICE;
339         tokp = of_get_property(rtas.dev, service, NULL);
340         return tokp ? be32_to_cpu(*tokp) : RTAS_UNKNOWN_SERVICE;
341 }
342 EXPORT_SYMBOL(rtas_token);
343
344 int rtas_service_present(const char *service)
345 {
346         return rtas_token(service) != RTAS_UNKNOWN_SERVICE;
347 }
348 EXPORT_SYMBOL(rtas_service_present);
349
350 #ifdef CONFIG_RTAS_ERROR_LOGGING
351 /*
352  * Return the firmware-specified size of the error log buffer
353  *  for all rtas calls that require an error buffer argument.
354  *  This includes 'check-exception' and 'rtas-last-error'.
355  */
356 int rtas_get_error_log_max(void)
357 {
358         static int rtas_error_log_max;
359         if (rtas_error_log_max)
360                 return rtas_error_log_max;
361
362         rtas_error_log_max = rtas_token ("rtas-error-log-max");
363         if ((rtas_error_log_max == RTAS_UNKNOWN_SERVICE) ||
364             (rtas_error_log_max > RTAS_ERROR_LOG_MAX)) {
365                 printk (KERN_WARNING "RTAS: bad log buffer size %d\n",
366                         rtas_error_log_max);
367                 rtas_error_log_max = RTAS_ERROR_LOG_MAX;
368         }
369         return rtas_error_log_max;
370 }
371 EXPORT_SYMBOL(rtas_get_error_log_max);
372
373
374 static char rtas_err_buf[RTAS_ERROR_LOG_MAX];
375 static int rtas_last_error_token;
376
377 /** Return a copy of the detailed error text associated with the
378  *  most recent failed call to rtas.  Because the error text
379  *  might go stale if there are any other intervening rtas calls,
380  *  this routine must be called atomically with whatever produced
381  *  the error (i.e. with rtas.lock still held from the previous call).
382  */
383 static char *__fetch_rtas_last_error(char *altbuf)
384 {
385         struct rtas_args err_args, save_args;
386         u32 bufsz;
387         char *buf = NULL;
388
389         if (rtas_last_error_token == -1)
390                 return NULL;
391
392         bufsz = rtas_get_error_log_max();
393
394         err_args.token = cpu_to_be32(rtas_last_error_token);
395         err_args.nargs = cpu_to_be32(2);
396         err_args.nret = cpu_to_be32(1);
397         err_args.args[0] = cpu_to_be32(__pa(rtas_err_buf));
398         err_args.args[1] = cpu_to_be32(bufsz);
399         err_args.args[2] = 0;
400
401         save_args = rtas.args;
402         rtas.args = err_args;
403
404         do_enter_rtas(__pa(&rtas.args));
405
406         err_args = rtas.args;
407         rtas.args = save_args;
408
409         /* Log the error in the unlikely case that there was one. */
410         if (unlikely(err_args.args[2] == 0)) {
411                 if (altbuf) {
412                         buf = altbuf;
413                 } else {
414                         buf = rtas_err_buf;
415                         if (slab_is_available())
416                                 buf = kmalloc(RTAS_ERROR_LOG_MAX, GFP_ATOMIC);
417                 }
418                 if (buf)
419                         memcpy(buf, rtas_err_buf, RTAS_ERROR_LOG_MAX);
420         }
421
422         return buf;
423 }
424
425 #define get_errorlog_buffer()   kmalloc(RTAS_ERROR_LOG_MAX, GFP_KERNEL)
426
427 #else /* CONFIG_RTAS_ERROR_LOGGING */
428 #define __fetch_rtas_last_error(x)      NULL
429 #define get_errorlog_buffer()           NULL
430 #endif
431
432
433 static void
434 va_rtas_call_unlocked(struct rtas_args *args, int token, int nargs, int nret,
435                       va_list list)
436 {
437         int i;
438
439         args->token = cpu_to_be32(token);
440         args->nargs = cpu_to_be32(nargs);
441         args->nret  = cpu_to_be32(nret);
442         args->rets  = &(args->args[nargs]);
443
444         for (i = 0; i < nargs; ++i)
445                 args->args[i] = cpu_to_be32(va_arg(list, __u32));
446
447         for (i = 0; i < nret; ++i)
448                 args->rets[i] = 0;
449
450         do_enter_rtas(__pa(args));
451 }
452
453 void rtas_call_unlocked(struct rtas_args *args, int token, int nargs, int nret, ...)
454 {
455         va_list list;
456
457         va_start(list, nret);
458         va_rtas_call_unlocked(args, token, nargs, nret, list);
459         va_end(list);
460 }
461
462 int rtas_call(int token, int nargs, int nret, int *outputs, ...)
463 {
464         va_list list;
465         int i;
466         unsigned long s;
467         struct rtas_args *rtas_args;
468         char *buff_copy = NULL;
469         int ret;
470
471         if (!rtas.entry || token == RTAS_UNKNOWN_SERVICE)
472                 return -1;
473
474         s = lock_rtas();
475
476         /* We use the global rtas args buffer */
477         rtas_args = &rtas.args;
478
479         va_start(list, outputs);
480         va_rtas_call_unlocked(rtas_args, token, nargs, nret, list);
481         va_end(list);
482
483         /* A -1 return code indicates that the last command couldn't
484            be completed due to a hardware error. */
485         if (be32_to_cpu(rtas_args->rets[0]) == -1)
486                 buff_copy = __fetch_rtas_last_error(NULL);
487
488         if (nret > 1 && outputs != NULL)
489                 for (i = 0; i < nret-1; ++i)
490                         outputs[i] = be32_to_cpu(rtas_args->rets[i+1]);
491         ret = (nret > 0)? be32_to_cpu(rtas_args->rets[0]): 0;
492
493         unlock_rtas(s);
494
495         if (buff_copy) {
496                 log_error(buff_copy, ERR_TYPE_RTAS_LOG, 0);
497                 if (slab_is_available())
498                         kfree(buff_copy);
499         }
500         return ret;
501 }
502 EXPORT_SYMBOL(rtas_call);
503
504 /* For RTAS_BUSY (-2), delay for 1 millisecond.  For an extended busy status
505  * code of 990n, perform the hinted delay of 10^n (last digit) milliseconds.
506  */
507 unsigned int rtas_busy_delay_time(int status)
508 {
509         int order;
510         unsigned int ms = 0;
511
512         if (status == RTAS_BUSY) {
513                 ms = 1;
514         } else if (status >= RTAS_EXTENDED_DELAY_MIN &&
515                    status <= RTAS_EXTENDED_DELAY_MAX) {
516                 order = status - RTAS_EXTENDED_DELAY_MIN;
517                 for (ms = 1; order > 0; order--)
518                         ms *= 10;
519         }
520
521         return ms;
522 }
523 EXPORT_SYMBOL(rtas_busy_delay_time);
524
525 /* For an RTAS busy status code, perform the hinted delay. */
526 unsigned int rtas_busy_delay(int status)
527 {
528         unsigned int ms;
529
530         might_sleep();
531         ms = rtas_busy_delay_time(status);
532         if (ms && need_resched())
533                 msleep(ms);
534
535         return ms;
536 }
537 EXPORT_SYMBOL(rtas_busy_delay);
538
539 static int rtas_error_rc(int rtas_rc)
540 {
541         int rc;
542
543         switch (rtas_rc) {
544                 case -1:                /* Hardware Error */
545                         rc = -EIO;
546                         break;
547                 case -3:                /* Bad indicator/domain/etc */
548                         rc = -EINVAL;
549                         break;
550                 case -9000:             /* Isolation error */
551                         rc = -EFAULT;
552                         break;
553                 case -9001:             /* Outstanding TCE/PTE */
554                         rc = -EEXIST;
555                         break;
556                 case -9002:             /* No usable slot */
557                         rc = -ENODEV;
558                         break;
559                 default:
560                         printk(KERN_ERR "%s: unexpected RTAS error %d\n",
561                                         __func__, rtas_rc);
562                         rc = -ERANGE;
563                         break;
564         }
565         return rc;
566 }
567
568 int rtas_get_power_level(int powerdomain, int *level)
569 {
570         int token = rtas_token("get-power-level");
571         int rc;
572
573         if (token == RTAS_UNKNOWN_SERVICE)
574                 return -ENOENT;
575
576         while ((rc = rtas_call(token, 1, 2, level, powerdomain)) == RTAS_BUSY)
577                 udelay(1);
578
579         if (rc < 0)
580                 return rtas_error_rc(rc);
581         return rc;
582 }
583 EXPORT_SYMBOL(rtas_get_power_level);
584
585 int rtas_set_power_level(int powerdomain, int level, int *setlevel)
586 {
587         int token = rtas_token("set-power-level");
588         int rc;
589
590         if (token == RTAS_UNKNOWN_SERVICE)
591                 return -ENOENT;
592
593         do {
594                 rc = rtas_call(token, 2, 2, setlevel, powerdomain, level);
595         } while (rtas_busy_delay(rc));
596
597         if (rc < 0)
598                 return rtas_error_rc(rc);
599         return rc;
600 }
601 EXPORT_SYMBOL(rtas_set_power_level);
602
603 int rtas_get_sensor(int sensor, int index, int *state)
604 {
605         int token = rtas_token("get-sensor-state");
606         int rc;
607
608         if (token == RTAS_UNKNOWN_SERVICE)
609                 return -ENOENT;
610
611         do {
612                 rc = rtas_call(token, 2, 2, state, sensor, index);
613         } while (rtas_busy_delay(rc));
614
615         if (rc < 0)
616                 return rtas_error_rc(rc);
617         return rc;
618 }
619 EXPORT_SYMBOL(rtas_get_sensor);
620
621 int rtas_get_sensor_fast(int sensor, int index, int *state)
622 {
623         int token = rtas_token("get-sensor-state");
624         int rc;
625
626         if (token == RTAS_UNKNOWN_SERVICE)
627                 return -ENOENT;
628
629         rc = rtas_call(token, 2, 2, state, sensor, index);
630         WARN_ON(rc == RTAS_BUSY || (rc >= RTAS_EXTENDED_DELAY_MIN &&
631                                     rc <= RTAS_EXTENDED_DELAY_MAX));
632
633         if (rc < 0)
634                 return rtas_error_rc(rc);
635         return rc;
636 }
637
638 bool rtas_indicator_present(int token, int *maxindex)
639 {
640         int proplen, count, i;
641         const struct indicator_elem {
642                 __be32 token;
643                 __be32 maxindex;
644         } *indicators;
645
646         indicators = of_get_property(rtas.dev, "rtas-indicators", &proplen);
647         if (!indicators)
648                 return false;
649
650         count = proplen / sizeof(struct indicator_elem);
651
652         for (i = 0; i < count; i++) {
653                 if (__be32_to_cpu(indicators[i].token) != token)
654                         continue;
655                 if (maxindex)
656                         *maxindex = __be32_to_cpu(indicators[i].maxindex);
657                 return true;
658         }
659
660         return false;
661 }
662 EXPORT_SYMBOL(rtas_indicator_present);
663
664 int rtas_set_indicator(int indicator, int index, int new_value)
665 {
666         int token = rtas_token("set-indicator");
667         int rc;
668
669         if (token == RTAS_UNKNOWN_SERVICE)
670                 return -ENOENT;
671
672         do {
673                 rc = rtas_call(token, 3, 1, NULL, indicator, index, new_value);
674         } while (rtas_busy_delay(rc));
675
676         if (rc < 0)
677                 return rtas_error_rc(rc);
678         return rc;
679 }
680 EXPORT_SYMBOL(rtas_set_indicator);
681
682 /*
683  * Ignoring RTAS extended delay
684  */
685 int rtas_set_indicator_fast(int indicator, int index, int new_value)
686 {
687         int rc;
688         int token = rtas_token("set-indicator");
689
690         if (token == RTAS_UNKNOWN_SERVICE)
691                 return -ENOENT;
692
693         rc = rtas_call(token, 3, 1, NULL, indicator, index, new_value);
694
695         WARN_ON(rc == RTAS_BUSY || (rc >= RTAS_EXTENDED_DELAY_MIN &&
696                                     rc <= RTAS_EXTENDED_DELAY_MAX));
697
698         if (rc < 0)
699                 return rtas_error_rc(rc);
700
701         return rc;
702 }
703
704 /**
705  * rtas_ibm_suspend_me() - Call ibm,suspend-me to suspend the LPAR.
706  *
707  * @fw_status: RTAS call status will be placed here if not NULL.
708  *
709  * rtas_ibm_suspend_me() should be called only on a CPU which has
710  * received H_CONTINUE from the H_JOIN hcall. All other active CPUs
711  * should be waiting to return from H_JOIN.
712  *
713  * rtas_ibm_suspend_me() may suspend execution of the OS
714  * indefinitely. Callers should take appropriate measures upon return, such as
715  * resetting watchdog facilities.
716  *
717  * Callers may choose to retry this call if @fw_status is
718  * %RTAS_THREADS_ACTIVE.
719  *
720  * Return:
721  * 0          - The partition has resumed from suspend, possibly after
722  *              migration to a different host.
723  * -ECANCELED - The operation was aborted.
724  * -EAGAIN    - There were other CPUs not in H_JOIN at the time of the call.
725  * -EBUSY     - Some other condition prevented the suspend from succeeding.
726  * -EIO       - Hardware/platform error.
727  */
728 int rtas_ibm_suspend_me(int *fw_status)
729 {
730         int fwrc;
731         int ret;
732
733         fwrc = rtas_call(rtas_token("ibm,suspend-me"), 0, 1, NULL);
734
735         switch (fwrc) {
736         case 0:
737                 ret = 0;
738                 break;
739         case RTAS_SUSPEND_ABORTED:
740                 ret = -ECANCELED;
741                 break;
742         case RTAS_THREADS_ACTIVE:
743                 ret = -EAGAIN;
744                 break;
745         case RTAS_NOT_SUSPENDABLE:
746         case RTAS_OUTSTANDING_COPROC:
747                 ret = -EBUSY;
748                 break;
749         case -1:
750         default:
751                 ret = -EIO;
752                 break;
753         }
754
755         if (fw_status)
756                 *fw_status = fwrc;
757
758         return ret;
759 }
760
761 void __noreturn rtas_restart(char *cmd)
762 {
763         if (rtas_flash_term_hook)
764                 rtas_flash_term_hook(SYS_RESTART);
765         printk("RTAS system-reboot returned %d\n",
766                rtas_call(rtas_token("system-reboot"), 0, 1, NULL));
767         for (;;);
768 }
769
770 void rtas_power_off(void)
771 {
772         if (rtas_flash_term_hook)
773                 rtas_flash_term_hook(SYS_POWER_OFF);
774         /* allow power on only with power button press */
775         printk("RTAS power-off returned %d\n",
776                rtas_call(rtas_token("power-off"), 2, 1, NULL, -1, -1));
777         for (;;);
778 }
779
780 void __noreturn rtas_halt(void)
781 {
782         if (rtas_flash_term_hook)
783                 rtas_flash_term_hook(SYS_HALT);
784         /* allow power on only with power button press */
785         printk("RTAS power-off returned %d\n",
786                rtas_call(rtas_token("power-off"), 2, 1, NULL, -1, -1));
787         for (;;);
788 }
789
790 /* Must be in the RMO region, so we place it here */
791 static char rtas_os_term_buf[2048];
792
793 void rtas_os_term(char *str)
794 {
795         int status;
796
797         /*
798          * Firmware with the ibm,extended-os-term property is guaranteed
799          * to always return from an ibm,os-term call. Earlier versions without
800          * this property may terminate the partition which we want to avoid
801          * since it interferes with panic_timeout.
802          */
803         if (RTAS_UNKNOWN_SERVICE == rtas_token("ibm,os-term") ||
804             RTAS_UNKNOWN_SERVICE == rtas_token("ibm,extended-os-term"))
805                 return;
806
807         snprintf(rtas_os_term_buf, 2048, "OS panic: %s", str);
808
809         do {
810                 status = rtas_call(rtas_token("ibm,os-term"), 1, 1, NULL,
811                                    __pa(rtas_os_term_buf));
812         } while (rtas_busy_delay(status));
813
814         if (status != 0)
815                 printk(KERN_EMERG "ibm,os-term call failed %d\n", status);
816 }
817
818 /**
819  * rtas_activate_firmware() - Activate a new version of firmware.
820  *
821  * Activate a new version of partition firmware. The OS must call this
822  * after resuming from a partition hibernation or migration in order
823  * to maintain the ability to perform live firmware updates. It's not
824  * catastrophic for this method to be absent or to fail; just log the
825  * condition in that case.
826  *
827  * Context: This function may sleep.
828  */
829 void rtas_activate_firmware(void)
830 {
831         int token;
832         int fwrc;
833
834         token = rtas_token("ibm,activate-firmware");
835         if (token == RTAS_UNKNOWN_SERVICE) {
836                 pr_notice("ibm,activate-firmware method unavailable\n");
837                 return;
838         }
839
840         do {
841                 fwrc = rtas_call(token, 0, 1, NULL);
842         } while (rtas_busy_delay(fwrc));
843
844         if (fwrc)
845                 pr_err("ibm,activate-firmware failed (%i)\n", fwrc);
846 }
847
848 #ifdef CONFIG_PPC_PSERIES
849 /**
850  * rtas_call_reentrant() - Used for reentrant rtas calls
851  * @token:      Token for desired reentrant RTAS call
852  * @nargs:      Number of Input Parameters
853  * @nret:       Number of Output Parameters
854  * @outputs:    Array of outputs
855  * @...:        Inputs for desired RTAS call
856  *
857  * According to LoPAR documentation, only "ibm,int-on", "ibm,int-off",
858  * "ibm,get-xive" and "ibm,set-xive" are currently reentrant.
859  * Reentrant calls need their own rtas_args buffer, so not using rtas.args, but
860  * PACA one instead.
861  *
862  * Return:      -1 on error,
863  *              First output value of RTAS call if (nret > 0),
864  *              0 otherwise,
865  */
866 int rtas_call_reentrant(int token, int nargs, int nret, int *outputs, ...)
867 {
868         va_list list;
869         struct rtas_args *args;
870         unsigned long flags;
871         int i, ret = 0;
872
873         if (!rtas.entry || token == RTAS_UNKNOWN_SERVICE)
874                 return -1;
875
876         local_irq_save(flags);
877         preempt_disable();
878
879         /* We use the per-cpu (PACA) rtas args buffer */
880         args = local_paca->rtas_args_reentrant;
881
882         va_start(list, outputs);
883         va_rtas_call_unlocked(args, token, nargs, nret, list);
884         va_end(list);
885
886         if (nret > 1 && outputs)
887                 for (i = 0; i < nret - 1; ++i)
888                         outputs[i] = be32_to_cpu(args->rets[i + 1]);
889
890         if (nret > 0)
891                 ret = be32_to_cpu(args->rets[0]);
892
893         local_irq_restore(flags);
894         preempt_enable();
895
896         return ret;
897 }
898
899 #endif /* CONFIG_PPC_PSERIES */
900
901 /**
902  * Find a specific pseries error log in an RTAS extended event log.
903  * @log: RTAS error/event log
904  * @section_id: two character section identifier
905  *
906  * Returns a pointer to the specified errorlog or NULL if not found.
907  */
908 struct pseries_errorlog *get_pseries_errorlog(struct rtas_error_log *log,
909                                               uint16_t section_id)
910 {
911         struct rtas_ext_event_log_v6 *ext_log =
912                 (struct rtas_ext_event_log_v6 *)log->buffer;
913         struct pseries_errorlog *sect;
914         unsigned char *p, *log_end;
915         uint32_t ext_log_length = rtas_error_extended_log_length(log);
916         uint8_t log_format = rtas_ext_event_log_format(ext_log);
917         uint32_t company_id = rtas_ext_event_company_id(ext_log);
918
919         /* Check that we understand the format */
920         if (ext_log_length < sizeof(struct rtas_ext_event_log_v6) ||
921             log_format != RTAS_V6EXT_LOG_FORMAT_EVENT_LOG ||
922             company_id != RTAS_V6EXT_COMPANY_ID_IBM)
923                 return NULL;
924
925         log_end = log->buffer + ext_log_length;
926         p = ext_log->vendor_log;
927
928         while (p < log_end) {
929                 sect = (struct pseries_errorlog *)p;
930                 if (pseries_errorlog_id(sect) == section_id)
931                         return sect;
932                 p += pseries_errorlog_length(sect);
933         }
934
935         return NULL;
936 }
937
938 #ifdef CONFIG_PPC_RTAS_FILTER
939
940 /*
941  * The sys_rtas syscall, as originally designed, allows root to pass
942  * arbitrary physical addresses to RTAS calls. A number of RTAS calls
943  * can be abused to write to arbitrary memory and do other things that
944  * are potentially harmful to system integrity, and thus should only
945  * be used inside the kernel and not exposed to userspace.
946  *
947  * All known legitimate users of the sys_rtas syscall will only ever
948  * pass addresses that fall within the RMO buffer, and use a known
949  * subset of RTAS calls.
950  *
951  * Accordingly, we filter RTAS requests to check that the call is
952  * permitted, and that provided pointers fall within the RMO buffer.
953  * The rtas_filters list contains an entry for each permitted call,
954  * with the indexes of the parameters which are expected to contain
955  * addresses and sizes of buffers allocated inside the RMO buffer.
956  */
957 struct rtas_filter {
958         const char *name;
959         int token;
960         /* Indexes into the args buffer, -1 if not used */
961         int buf_idx1;
962         int size_idx1;
963         int buf_idx2;
964         int size_idx2;
965
966         int fixed_size;
967 };
968
969 static struct rtas_filter rtas_filters[] __ro_after_init = {
970         { "ibm,activate-firmware", -1, -1, -1, -1, -1 },
971         { "ibm,configure-connector", -1, 0, -1, 1, -1, 4096 },  /* Special cased */
972         { "display-character", -1, -1, -1, -1, -1 },
973         { "ibm,display-message", -1, 0, -1, -1, -1 },
974         { "ibm,errinjct", -1, 2, -1, -1, -1, 1024 },
975         { "ibm,close-errinjct", -1, -1, -1, -1, -1 },
976         { "ibm,open-errinjct", -1, -1, -1, -1, -1 },
977         { "ibm,get-config-addr-info2", -1, -1, -1, -1, -1 },
978         { "ibm,get-dynamic-sensor-state", -1, 1, -1, -1, -1 },
979         { "ibm,get-indices", -1, 2, 3, -1, -1 },
980         { "get-power-level", -1, -1, -1, -1, -1 },
981         { "get-sensor-state", -1, -1, -1, -1, -1 },
982         { "ibm,get-system-parameter", -1, 1, 2, -1, -1 },
983         { "get-time-of-day", -1, -1, -1, -1, -1 },
984         { "ibm,get-vpd", -1, 0, -1, 1, 2 },
985         { "ibm,lpar-perftools", -1, 2, 3, -1, -1 },
986         { "ibm,platform-dump", -1, 4, 5, -1, -1 },              /* Special cased */
987         { "ibm,read-slot-reset-state", -1, -1, -1, -1, -1 },
988         { "ibm,scan-log-dump", -1, 0, 1, -1, -1 },
989         { "ibm,set-dynamic-indicator", -1, 2, -1, -1, -1 },
990         { "ibm,set-eeh-option", -1, -1, -1, -1, -1 },
991         { "set-indicator", -1, -1, -1, -1, -1 },
992         { "set-power-level", -1, -1, -1, -1, -1 },
993         { "set-time-for-power-on", -1, -1, -1, -1, -1 },
994         { "ibm,set-system-parameter", -1, 1, -1, -1, -1 },
995         { "set-time-of-day", -1, -1, -1, -1, -1 },
996 #ifdef CONFIG_CPU_BIG_ENDIAN
997         { "ibm,suspend-me", -1, -1, -1, -1, -1 },
998         { "ibm,update-nodes", -1, 0, -1, -1, -1, 4096 },
999         { "ibm,update-properties", -1, 0, -1, -1, -1, 4096 },
1000 #endif
1001         { "ibm,physical-attestation", -1, 0, 1, -1, -1 },
1002 };
1003
1004 static bool in_rmo_buf(u32 base, u32 end)
1005 {
1006         return base >= rtas_rmo_buf &&
1007                 base < (rtas_rmo_buf + RTAS_USER_REGION_SIZE) &&
1008                 base <= end &&
1009                 end >= rtas_rmo_buf &&
1010                 end < (rtas_rmo_buf + RTAS_USER_REGION_SIZE);
1011 }
1012
1013 static bool block_rtas_call(int token, int nargs,
1014                             struct rtas_args *args)
1015 {
1016         int i;
1017
1018         for (i = 0; i < ARRAY_SIZE(rtas_filters); i++) {
1019                 struct rtas_filter *f = &rtas_filters[i];
1020                 u32 base, size, end;
1021
1022                 if (token != f->token)
1023                         continue;
1024
1025                 if (f->buf_idx1 != -1) {
1026                         base = be32_to_cpu(args->args[f->buf_idx1]);
1027                         if (f->size_idx1 != -1)
1028                                 size = be32_to_cpu(args->args[f->size_idx1]);
1029                         else if (f->fixed_size)
1030                                 size = f->fixed_size;
1031                         else
1032                                 size = 1;
1033
1034                         end = base + size - 1;
1035
1036                         /*
1037                          * Special case for ibm,platform-dump - NULL buffer
1038                          * address is used to indicate end of dump processing
1039                          */
1040                         if (!strcmp(f->name, "ibm,platform-dump") &&
1041                             base == 0)
1042                                 return false;
1043
1044                         if (!in_rmo_buf(base, end))
1045                                 goto err;
1046                 }
1047
1048                 if (f->buf_idx2 != -1) {
1049                         base = be32_to_cpu(args->args[f->buf_idx2]);
1050                         if (f->size_idx2 != -1)
1051                                 size = be32_to_cpu(args->args[f->size_idx2]);
1052                         else if (f->fixed_size)
1053                                 size = f->fixed_size;
1054                         else
1055                                 size = 1;
1056                         end = base + size - 1;
1057
1058                         /*
1059                          * Special case for ibm,configure-connector where the
1060                          * address can be 0
1061                          */
1062                         if (!strcmp(f->name, "ibm,configure-connector") &&
1063                             base == 0)
1064                                 return false;
1065
1066                         if (!in_rmo_buf(base, end))
1067                                 goto err;
1068                 }
1069
1070                 return false;
1071         }
1072
1073 err:
1074         pr_err_ratelimited("sys_rtas: RTAS call blocked - exploit attempt?\n");
1075         pr_err_ratelimited("sys_rtas: token=0x%x, nargs=%d (called by %s)\n",
1076                            token, nargs, current->comm);
1077         return true;
1078 }
1079
1080 static void __init rtas_syscall_filter_init(void)
1081 {
1082         unsigned int i;
1083
1084         for (i = 0; i < ARRAY_SIZE(rtas_filters); i++)
1085                 rtas_filters[i].token = rtas_token(rtas_filters[i].name);
1086 }
1087
1088 #else
1089
1090 static bool block_rtas_call(int token, int nargs,
1091                             struct rtas_args *args)
1092 {
1093         return false;
1094 }
1095
1096 static void __init rtas_syscall_filter_init(void)
1097 {
1098 }
1099
1100 #endif /* CONFIG_PPC_RTAS_FILTER */
1101
1102 /* We assume to be passed big endian arguments */
1103 SYSCALL_DEFINE1(rtas, struct rtas_args __user *, uargs)
1104 {
1105         struct rtas_args args;
1106         unsigned long flags;
1107         char *buff_copy, *errbuf = NULL;
1108         int nargs, nret, token;
1109
1110         if (!capable(CAP_SYS_ADMIN))
1111                 return -EPERM;
1112
1113         if (!rtas.entry)
1114                 return -EINVAL;
1115
1116         if (copy_from_user(&args, uargs, 3 * sizeof(u32)) != 0)
1117                 return -EFAULT;
1118
1119         nargs = be32_to_cpu(args.nargs);
1120         nret  = be32_to_cpu(args.nret);
1121         token = be32_to_cpu(args.token);
1122
1123         if (nargs >= ARRAY_SIZE(args.args)
1124             || nret > ARRAY_SIZE(args.args)
1125             || nargs + nret > ARRAY_SIZE(args.args))
1126                 return -EINVAL;
1127
1128         /* Copy in args. */
1129         if (copy_from_user(args.args, uargs->args,
1130                            nargs * sizeof(rtas_arg_t)) != 0)
1131                 return -EFAULT;
1132
1133         if (token == RTAS_UNKNOWN_SERVICE)
1134                 return -EINVAL;
1135
1136         args.rets = &args.args[nargs];
1137         memset(args.rets, 0, nret * sizeof(rtas_arg_t));
1138
1139         if (block_rtas_call(token, nargs, &args))
1140                 return -EINVAL;
1141
1142         /* Need to handle ibm,suspend_me call specially */
1143         if (token == rtas_token("ibm,suspend-me")) {
1144
1145                 /*
1146                  * rtas_ibm_suspend_me assumes the streamid handle is in cpu
1147                  * endian, or at least the hcall within it requires it.
1148                  */
1149                 int rc = 0;
1150                 u64 handle = ((u64)be32_to_cpu(args.args[0]) << 32)
1151                               | be32_to_cpu(args.args[1]);
1152                 rc = rtas_syscall_dispatch_ibm_suspend_me(handle);
1153                 if (rc == -EAGAIN)
1154                         args.rets[0] = cpu_to_be32(RTAS_NOT_SUSPENDABLE);
1155                 else if (rc == -EIO)
1156                         args.rets[0] = cpu_to_be32(-1);
1157                 else if (rc)
1158                         return rc;
1159                 goto copy_return;
1160         }
1161
1162         buff_copy = get_errorlog_buffer();
1163
1164         flags = lock_rtas();
1165
1166         rtas.args = args;
1167         do_enter_rtas(__pa(&rtas.args));
1168         args = rtas.args;
1169
1170         /* A -1 return code indicates that the last command couldn't
1171            be completed due to a hardware error. */
1172         if (be32_to_cpu(args.rets[0]) == -1)
1173                 errbuf = __fetch_rtas_last_error(buff_copy);
1174
1175         unlock_rtas(flags);
1176
1177         if (buff_copy) {
1178                 if (errbuf)
1179                         log_error(errbuf, ERR_TYPE_RTAS_LOG, 0);
1180                 kfree(buff_copy);
1181         }
1182
1183  copy_return:
1184         /* Copy out args. */
1185         if (copy_to_user(uargs->args + nargs,
1186                          args.args + nargs,
1187                          nret * sizeof(rtas_arg_t)) != 0)
1188                 return -EFAULT;
1189
1190         return 0;
1191 }
1192
1193 /*
1194  * Call early during boot, before mem init, to retrieve the RTAS
1195  * information from the device-tree and allocate the RMO buffer for userland
1196  * accesses.
1197  */
1198 void __init rtas_initialize(void)
1199 {
1200         unsigned long rtas_region = RTAS_INSTANTIATE_MAX;
1201         u32 base, size, entry;
1202         int no_base, no_size, no_entry;
1203
1204         /* Get RTAS dev node and fill up our "rtas" structure with infos
1205          * about it.
1206          */
1207         rtas.dev = of_find_node_by_name(NULL, "rtas");
1208         if (!rtas.dev)
1209                 return;
1210
1211         no_base = of_property_read_u32(rtas.dev, "linux,rtas-base", &base);
1212         no_size = of_property_read_u32(rtas.dev, "rtas-size", &size);
1213         if (no_base || no_size) {
1214                 of_node_put(rtas.dev);
1215                 rtas.dev = NULL;
1216                 return;
1217         }
1218
1219         rtas.base = base;
1220         rtas.size = size;
1221         no_entry = of_property_read_u32(rtas.dev, "linux,rtas-entry", &entry);
1222         rtas.entry = no_entry ? rtas.base : entry;
1223
1224         /* If RTAS was found, allocate the RMO buffer for it and look for
1225          * the stop-self token if any
1226          */
1227 #ifdef CONFIG_PPC64
1228         if (firmware_has_feature(FW_FEATURE_LPAR))
1229                 rtas_region = min(ppc64_rma_size, RTAS_INSTANTIATE_MAX);
1230 #endif
1231         rtas_rmo_buf = memblock_phys_alloc_range(RTAS_USER_REGION_SIZE, PAGE_SIZE,
1232                                                  0, rtas_region);
1233         if (!rtas_rmo_buf)
1234                 panic("ERROR: RTAS: Failed to allocate %lx bytes below %pa\n",
1235                       PAGE_SIZE, &rtas_region);
1236
1237 #ifdef CONFIG_RTAS_ERROR_LOGGING
1238         rtas_last_error_token = rtas_token("rtas-last-error");
1239 #endif
1240
1241         rtas_syscall_filter_init();
1242 }
1243
1244 int __init early_init_dt_scan_rtas(unsigned long node,
1245                 const char *uname, int depth, void *data)
1246 {
1247         const u32 *basep, *entryp, *sizep;
1248
1249         if (depth != 1 || strcmp(uname, "rtas") != 0)
1250                 return 0;
1251
1252         basep  = of_get_flat_dt_prop(node, "linux,rtas-base", NULL);
1253         entryp = of_get_flat_dt_prop(node, "linux,rtas-entry", NULL);
1254         sizep  = of_get_flat_dt_prop(node, "rtas-size", NULL);
1255
1256 #ifdef CONFIG_PPC64
1257         /* need this feature to decide the crashkernel offset */
1258         if (of_get_flat_dt_prop(node, "ibm,hypertas-functions", NULL))
1259                 powerpc_firmware_features |= FW_FEATURE_LPAR;
1260 #endif
1261
1262         if (basep && entryp && sizep) {
1263                 rtas.base = *basep;
1264                 rtas.entry = *entryp;
1265                 rtas.size = *sizep;
1266         }
1267
1268 #ifdef CONFIG_UDBG_RTAS_CONSOLE
1269         basep = of_get_flat_dt_prop(node, "put-term-char", NULL);
1270         if (basep)
1271                 rtas_putchar_token = *basep;
1272
1273         basep = of_get_flat_dt_prop(node, "get-term-char", NULL);
1274         if (basep)
1275                 rtas_getchar_token = *basep;
1276
1277         if (rtas_putchar_token != RTAS_UNKNOWN_SERVICE &&
1278             rtas_getchar_token != RTAS_UNKNOWN_SERVICE)
1279                 udbg_init_rtas_console();
1280
1281 #endif
1282
1283         /* break now */
1284         return 1;
1285 }
1286
1287 static arch_spinlock_t timebase_lock;
1288 static u64 timebase = 0;
1289
1290 void rtas_give_timebase(void)
1291 {
1292         unsigned long flags;
1293
1294         local_irq_save(flags);
1295         hard_irq_disable();
1296         arch_spin_lock(&timebase_lock);
1297         rtas_call(rtas_token("freeze-time-base"), 0, 1, NULL);
1298         timebase = get_tb();
1299         arch_spin_unlock(&timebase_lock);
1300
1301         while (timebase)
1302                 barrier();
1303         rtas_call(rtas_token("thaw-time-base"), 0, 1, NULL);
1304         local_irq_restore(flags);
1305 }
1306
1307 void rtas_take_timebase(void)
1308 {
1309         while (!timebase)
1310                 barrier();
1311         arch_spin_lock(&timebase_lock);
1312         set_tb(timebase >> 32, timebase & 0xffffffff);
1313         timebase = 0;
1314         arch_spin_unlock(&timebase_lock);
1315 }