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