xref: /openbmc/linux/arch/powerpc/kernel/rtas.c (revision d88e2a2b)
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 #define pr_fmt(fmt)	"rtas: " fmt
11 
12 #include <linux/bsearch.h>
13 #include <linux/capability.h>
14 #include <linux/delay.h>
15 #include <linux/export.h>
16 #include <linux/init.h>
17 #include <linux/kconfig.h>
18 #include <linux/kernel.h>
19 #include <linux/memblock.h>
20 #include <linux/of.h>
21 #include <linux/of_fdt.h>
22 #include <linux/reboot.h>
23 #include <linux/sched.h>
24 #include <linux/security.h>
25 #include <linux/slab.h>
26 #include <linux/spinlock.h>
27 #include <linux/stdarg.h>
28 #include <linux/syscalls.h>
29 #include <linux/types.h>
30 #include <linux/uaccess.h>
31 #include <linux/xarray.h>
32 
33 #include <asm/delay.h>
34 #include <asm/firmware.h>
35 #include <asm/interrupt.h>
36 #include <asm/machdep.h>
37 #include <asm/mmu.h>
38 #include <asm/page.h>
39 #include <asm/rtas-work-area.h>
40 #include <asm/rtas.h>
41 #include <asm/time.h>
42 #include <asm/trace.h>
43 #include <asm/udbg.h>
44 
45 struct rtas_filter {
46 	/* Indexes into the args buffer, -1 if not used */
47 	const int buf_idx1;
48 	const int size_idx1;
49 	const int buf_idx2;
50 	const int size_idx2;
51 	/*
52 	 * Assumed buffer size per the spec if the function does not
53 	 * have a size parameter, e.g. ibm,errinjct. 0 if unused.
54 	 */
55 	const int fixed_size;
56 };
57 
58 /**
59  * struct rtas_function - Descriptor for RTAS functions.
60  *
61  * @token: Value of @name if it exists under the /rtas node.
62  * @name: Function name.
63  * @filter: If non-NULL, invoking this function via the rtas syscall is
64  *          generally allowed, and @filter describes constraints on the
65  *          arguments. See also @banned_for_syscall_on_le.
66  * @banned_for_syscall_on_le: Set when call via sys_rtas is generally allowed
67  *                            but specifically restricted on ppc64le. Such
68  *                            functions are believed to have no users on
69  *                            ppc64le, and we want to keep it that way. It does
70  *                            not make sense for this to be set when @filter
71  *                            is false.
72  */
73 struct rtas_function {
74 	s32 token;
75 	const bool banned_for_syscall_on_le:1;
76 	const char * const name;
77 	const struct rtas_filter *filter;
78 };
79 
80 static struct rtas_function rtas_function_table[] __ro_after_init = {
81 	[RTAS_FNIDX__CHECK_EXCEPTION] = {
82 		.name = "check-exception",
83 	},
84 	[RTAS_FNIDX__DISPLAY_CHARACTER] = {
85 		.name = "display-character",
86 		.filter = &(const struct rtas_filter) {
87 			.buf_idx1 = -1, .size_idx1 = -1,
88 			.buf_idx2 = -1, .size_idx2 = -1,
89 		},
90 	},
91 	[RTAS_FNIDX__EVENT_SCAN] = {
92 		.name = "event-scan",
93 	},
94 	[RTAS_FNIDX__FREEZE_TIME_BASE] = {
95 		.name = "freeze-time-base",
96 	},
97 	[RTAS_FNIDX__GET_POWER_LEVEL] = {
98 		.name = "get-power-level",
99 		.filter = &(const struct rtas_filter) {
100 			.buf_idx1 = -1, .size_idx1 = -1,
101 			.buf_idx2 = -1, .size_idx2 = -1,
102 		},
103 	},
104 	[RTAS_FNIDX__GET_SENSOR_STATE] = {
105 		.name = "get-sensor-state",
106 		.filter = &(const struct rtas_filter) {
107 			.buf_idx1 = -1, .size_idx1 = -1,
108 			.buf_idx2 = -1, .size_idx2 = -1,
109 		},
110 	},
111 	[RTAS_FNIDX__GET_TERM_CHAR] = {
112 		.name = "get-term-char",
113 	},
114 	[RTAS_FNIDX__GET_TIME_OF_DAY] = {
115 		.name = "get-time-of-day",
116 		.filter = &(const struct rtas_filter) {
117 			.buf_idx1 = -1, .size_idx1 = -1,
118 			.buf_idx2 = -1, .size_idx2 = -1,
119 		},
120 	},
121 	[RTAS_FNIDX__IBM_ACTIVATE_FIRMWARE] = {
122 		.name = "ibm,activate-firmware",
123 		.filter = &(const struct rtas_filter) {
124 			.buf_idx1 = -1, .size_idx1 = -1,
125 			.buf_idx2 = -1, .size_idx2 = -1,
126 		},
127 	},
128 	[RTAS_FNIDX__IBM_CBE_START_PTCAL] = {
129 		.name = "ibm,cbe-start-ptcal",
130 	},
131 	[RTAS_FNIDX__IBM_CBE_STOP_PTCAL] = {
132 		.name = "ibm,cbe-stop-ptcal",
133 	},
134 	[RTAS_FNIDX__IBM_CHANGE_MSI] = {
135 		.name = "ibm,change-msi",
136 	},
137 	[RTAS_FNIDX__IBM_CLOSE_ERRINJCT] = {
138 		.name = "ibm,close-errinjct",
139 		.filter = &(const struct rtas_filter) {
140 			.buf_idx1 = -1, .size_idx1 = -1,
141 			.buf_idx2 = -1, .size_idx2 = -1,
142 		},
143 	},
144 	[RTAS_FNIDX__IBM_CONFIGURE_BRIDGE] = {
145 		.name = "ibm,configure-bridge",
146 	},
147 	[RTAS_FNIDX__IBM_CONFIGURE_CONNECTOR] = {
148 		.name = "ibm,configure-connector",
149 		.filter = &(const struct rtas_filter) {
150 			.buf_idx1 = 0, .size_idx1 = -1,
151 			.buf_idx2 = 1, .size_idx2 = -1,
152 			.fixed_size = 4096,
153 		},
154 	},
155 	[RTAS_FNIDX__IBM_CONFIGURE_KERNEL_DUMP] = {
156 		.name = "ibm,configure-kernel-dump",
157 	},
158 	[RTAS_FNIDX__IBM_CONFIGURE_PE] = {
159 		.name = "ibm,configure-pe",
160 	},
161 	[RTAS_FNIDX__IBM_CREATE_PE_DMA_WINDOW] = {
162 		.name = "ibm,create-pe-dma-window",
163 	},
164 	[RTAS_FNIDX__IBM_DISPLAY_MESSAGE] = {
165 		.name = "ibm,display-message",
166 		.filter = &(const struct rtas_filter) {
167 			.buf_idx1 = 0, .size_idx1 = -1,
168 			.buf_idx2 = -1, .size_idx2 = -1,
169 		},
170 	},
171 	[RTAS_FNIDX__IBM_ERRINJCT] = {
172 		.name = "ibm,errinjct",
173 		.filter = &(const struct rtas_filter) {
174 			.buf_idx1 = 2, .size_idx1 = -1,
175 			.buf_idx2 = -1, .size_idx2 = -1,
176 			.fixed_size = 1024,
177 		},
178 	},
179 	[RTAS_FNIDX__IBM_EXTI2C] = {
180 		.name = "ibm,exti2c",
181 	},
182 	[RTAS_FNIDX__IBM_GET_CONFIG_ADDR_INFO] = {
183 		.name = "ibm,get-config-addr-info",
184 	},
185 	[RTAS_FNIDX__IBM_GET_CONFIG_ADDR_INFO2] = {
186 		.name = "ibm,get-config-addr-info2",
187 		.filter = &(const struct rtas_filter) {
188 			.buf_idx1 = -1, .size_idx1 = -1,
189 			.buf_idx2 = -1, .size_idx2 = -1,
190 		},
191 	},
192 	[RTAS_FNIDX__IBM_GET_DYNAMIC_SENSOR_STATE] = {
193 		.name = "ibm,get-dynamic-sensor-state",
194 		.filter = &(const struct rtas_filter) {
195 			.buf_idx1 = 1, .size_idx1 = -1,
196 			.buf_idx2 = -1, .size_idx2 = -1,
197 		},
198 	},
199 	[RTAS_FNIDX__IBM_GET_INDICES] = {
200 		.name = "ibm,get-indices",
201 		.filter = &(const struct rtas_filter) {
202 			.buf_idx1 = 2, .size_idx1 = 3,
203 			.buf_idx2 = -1, .size_idx2 = -1,
204 		},
205 	},
206 	[RTAS_FNIDX__IBM_GET_RIO_TOPOLOGY] = {
207 		.name = "ibm,get-rio-topology",
208 	},
209 	[RTAS_FNIDX__IBM_GET_SYSTEM_PARAMETER] = {
210 		.name = "ibm,get-system-parameter",
211 		.filter = &(const struct rtas_filter) {
212 			.buf_idx1 = 1, .size_idx1 = 2,
213 			.buf_idx2 = -1, .size_idx2 = -1,
214 		},
215 	},
216 	[RTAS_FNIDX__IBM_GET_VPD] = {
217 		.name = "ibm,get-vpd",
218 		.filter = &(const struct rtas_filter) {
219 			.buf_idx1 = 0, .size_idx1 = -1,
220 			.buf_idx2 = 1, .size_idx2 = 2,
221 		},
222 	},
223 	[RTAS_FNIDX__IBM_GET_XIVE] = {
224 		.name = "ibm,get-xive",
225 	},
226 	[RTAS_FNIDX__IBM_INT_OFF] = {
227 		.name = "ibm,int-off",
228 	},
229 	[RTAS_FNIDX__IBM_INT_ON] = {
230 		.name = "ibm,int-on",
231 	},
232 	[RTAS_FNIDX__IBM_IO_QUIESCE_ACK] = {
233 		.name = "ibm,io-quiesce-ack",
234 	},
235 	[RTAS_FNIDX__IBM_LPAR_PERFTOOLS] = {
236 		.name = "ibm,lpar-perftools",
237 		.filter = &(const struct rtas_filter) {
238 			.buf_idx1 = 2, .size_idx1 = 3,
239 			.buf_idx2 = -1, .size_idx2 = -1,
240 		},
241 	},
242 	[RTAS_FNIDX__IBM_MANAGE_FLASH_IMAGE] = {
243 		.name = "ibm,manage-flash-image",
244 	},
245 	[RTAS_FNIDX__IBM_MANAGE_STORAGE_PRESERVATION] = {
246 		.name = "ibm,manage-storage-preservation",
247 	},
248 	[RTAS_FNIDX__IBM_NMI_INTERLOCK] = {
249 		.name = "ibm,nmi-interlock",
250 	},
251 	[RTAS_FNIDX__IBM_NMI_REGISTER] = {
252 		.name = "ibm,nmi-register",
253 	},
254 	[RTAS_FNIDX__IBM_OPEN_ERRINJCT] = {
255 		.name = "ibm,open-errinjct",
256 		.filter = &(const struct rtas_filter) {
257 			.buf_idx1 = -1, .size_idx1 = -1,
258 			.buf_idx2 = -1, .size_idx2 = -1,
259 		},
260 	},
261 	[RTAS_FNIDX__IBM_OPEN_SRIOV_ALLOW_UNFREEZE] = {
262 		.name = "ibm,open-sriov-allow-unfreeze",
263 	},
264 	[RTAS_FNIDX__IBM_OPEN_SRIOV_MAP_PE_NUMBER] = {
265 		.name = "ibm,open-sriov-map-pe-number",
266 	},
267 	[RTAS_FNIDX__IBM_OS_TERM] = {
268 		.name = "ibm,os-term",
269 	},
270 	[RTAS_FNIDX__IBM_PARTNER_CONTROL] = {
271 		.name = "ibm,partner-control",
272 	},
273 	[RTAS_FNIDX__IBM_PHYSICAL_ATTESTATION] = {
274 		.name = "ibm,physical-attestation",
275 		.filter = &(const struct rtas_filter) {
276 			.buf_idx1 = 0, .size_idx1 = 1,
277 			.buf_idx2 = -1, .size_idx2 = -1,
278 		},
279 	},
280 	[RTAS_FNIDX__IBM_PLATFORM_DUMP] = {
281 		.name = "ibm,platform-dump",
282 		.filter = &(const struct rtas_filter) {
283 			.buf_idx1 = 4, .size_idx1 = 5,
284 			.buf_idx2 = -1, .size_idx2 = -1,
285 		},
286 	},
287 	[RTAS_FNIDX__IBM_POWER_OFF_UPS] = {
288 		.name = "ibm,power-off-ups",
289 	},
290 	[RTAS_FNIDX__IBM_QUERY_INTERRUPT_SOURCE_NUMBER] = {
291 		.name = "ibm,query-interrupt-source-number",
292 	},
293 	[RTAS_FNIDX__IBM_QUERY_PE_DMA_WINDOW] = {
294 		.name = "ibm,query-pe-dma-window",
295 	},
296 	[RTAS_FNIDX__IBM_READ_PCI_CONFIG] = {
297 		.name = "ibm,read-pci-config",
298 	},
299 	[RTAS_FNIDX__IBM_READ_SLOT_RESET_STATE] = {
300 		.name = "ibm,read-slot-reset-state",
301 		.filter = &(const struct rtas_filter) {
302 			.buf_idx1 = -1, .size_idx1 = -1,
303 			.buf_idx2 = -1, .size_idx2 = -1,
304 		},
305 	},
306 	[RTAS_FNIDX__IBM_READ_SLOT_RESET_STATE2] = {
307 		.name = "ibm,read-slot-reset-state2",
308 	},
309 	[RTAS_FNIDX__IBM_REMOVE_PE_DMA_WINDOW] = {
310 		.name = "ibm,remove-pe-dma-window",
311 	},
312 	[RTAS_FNIDX__IBM_RESET_PE_DMA_WINDOWS] = {
313 		.name = "ibm,reset-pe-dma-windows",
314 	},
315 	[RTAS_FNIDX__IBM_SCAN_LOG_DUMP] = {
316 		.name = "ibm,scan-log-dump",
317 		.filter = &(const struct rtas_filter) {
318 			.buf_idx1 = 0, .size_idx1 = 1,
319 			.buf_idx2 = -1, .size_idx2 = -1,
320 		},
321 	},
322 	[RTAS_FNIDX__IBM_SET_DYNAMIC_INDICATOR] = {
323 		.name = "ibm,set-dynamic-indicator",
324 		.filter = &(const struct rtas_filter) {
325 			.buf_idx1 = 2, .size_idx1 = -1,
326 			.buf_idx2 = -1, .size_idx2 = -1,
327 		},
328 	},
329 	[RTAS_FNIDX__IBM_SET_EEH_OPTION] = {
330 		.name = "ibm,set-eeh-option",
331 		.filter = &(const struct rtas_filter) {
332 			.buf_idx1 = -1, .size_idx1 = -1,
333 			.buf_idx2 = -1, .size_idx2 = -1,
334 		},
335 	},
336 	[RTAS_FNIDX__IBM_SET_SLOT_RESET] = {
337 		.name = "ibm,set-slot-reset",
338 	},
339 	[RTAS_FNIDX__IBM_SET_SYSTEM_PARAMETER] = {
340 		.name = "ibm,set-system-parameter",
341 		.filter = &(const struct rtas_filter) {
342 			.buf_idx1 = 1, .size_idx1 = -1,
343 			.buf_idx2 = -1, .size_idx2 = -1,
344 		},
345 	},
346 	[RTAS_FNIDX__IBM_SET_XIVE] = {
347 		.name = "ibm,set-xive",
348 	},
349 	[RTAS_FNIDX__IBM_SLOT_ERROR_DETAIL] = {
350 		.name = "ibm,slot-error-detail",
351 	},
352 	[RTAS_FNIDX__IBM_SUSPEND_ME] = {
353 		.name = "ibm,suspend-me",
354 		.banned_for_syscall_on_le = true,
355 		.filter = &(const struct rtas_filter) {
356 			.buf_idx1 = -1, .size_idx1 = -1,
357 			.buf_idx2 = -1, .size_idx2 = -1,
358 		},
359 	},
360 	[RTAS_FNIDX__IBM_TUNE_DMA_PARMS] = {
361 		.name = "ibm,tune-dma-parms",
362 	},
363 	[RTAS_FNIDX__IBM_UPDATE_FLASH_64_AND_REBOOT] = {
364 		.name = "ibm,update-flash-64-and-reboot",
365 	},
366 	[RTAS_FNIDX__IBM_UPDATE_NODES] = {
367 		.name = "ibm,update-nodes",
368 		.banned_for_syscall_on_le = true,
369 		.filter = &(const struct rtas_filter) {
370 			.buf_idx1 = 0, .size_idx1 = -1,
371 			.buf_idx2 = -1, .size_idx2 = -1,
372 			.fixed_size = 4096,
373 		},
374 	},
375 	[RTAS_FNIDX__IBM_UPDATE_PROPERTIES] = {
376 		.name = "ibm,update-properties",
377 		.banned_for_syscall_on_le = true,
378 		.filter = &(const struct rtas_filter) {
379 			.buf_idx1 = 0, .size_idx1 = -1,
380 			.buf_idx2 = -1, .size_idx2 = -1,
381 			.fixed_size = 4096,
382 		},
383 	},
384 	[RTAS_FNIDX__IBM_VALIDATE_FLASH_IMAGE] = {
385 		.name = "ibm,validate-flash-image",
386 	},
387 	[RTAS_FNIDX__IBM_WRITE_PCI_CONFIG] = {
388 		.name = "ibm,write-pci-config",
389 	},
390 	[RTAS_FNIDX__NVRAM_FETCH] = {
391 		.name = "nvram-fetch",
392 	},
393 	[RTAS_FNIDX__NVRAM_STORE] = {
394 		.name = "nvram-store",
395 	},
396 	[RTAS_FNIDX__POWER_OFF] = {
397 		.name = "power-off",
398 	},
399 	[RTAS_FNIDX__PUT_TERM_CHAR] = {
400 		.name = "put-term-char",
401 	},
402 	[RTAS_FNIDX__QUERY_CPU_STOPPED_STATE] = {
403 		.name = "query-cpu-stopped-state",
404 	},
405 	[RTAS_FNIDX__READ_PCI_CONFIG] = {
406 		.name = "read-pci-config",
407 	},
408 	[RTAS_FNIDX__RTAS_LAST_ERROR] = {
409 		.name = "rtas-last-error",
410 	},
411 	[RTAS_FNIDX__SET_INDICATOR] = {
412 		.name = "set-indicator",
413 		.filter = &(const struct rtas_filter) {
414 			.buf_idx1 = -1, .size_idx1 = -1,
415 			.buf_idx2 = -1, .size_idx2 = -1,
416 		},
417 	},
418 	[RTAS_FNIDX__SET_POWER_LEVEL] = {
419 		.name = "set-power-level",
420 		.filter = &(const struct rtas_filter) {
421 			.buf_idx1 = -1, .size_idx1 = -1,
422 			.buf_idx2 = -1, .size_idx2 = -1,
423 		},
424 	},
425 	[RTAS_FNIDX__SET_TIME_FOR_POWER_ON] = {
426 		.name = "set-time-for-power-on",
427 		.filter = &(const struct rtas_filter) {
428 			.buf_idx1 = -1, .size_idx1 = -1,
429 			.buf_idx2 = -1, .size_idx2 = -1,
430 		},
431 	},
432 	[RTAS_FNIDX__SET_TIME_OF_DAY] = {
433 		.name = "set-time-of-day",
434 		.filter = &(const struct rtas_filter) {
435 			.buf_idx1 = -1, .size_idx1 = -1,
436 			.buf_idx2 = -1, .size_idx2 = -1,
437 		},
438 	},
439 	[RTAS_FNIDX__START_CPU] = {
440 		.name = "start-cpu",
441 	},
442 	[RTAS_FNIDX__STOP_SELF] = {
443 		.name = "stop-self",
444 	},
445 	[RTAS_FNIDX__SYSTEM_REBOOT] = {
446 		.name = "system-reboot",
447 	},
448 	[RTAS_FNIDX__THAW_TIME_BASE] = {
449 		.name = "thaw-time-base",
450 	},
451 	[RTAS_FNIDX__WRITE_PCI_CONFIG] = {
452 		.name = "write-pci-config",
453 	},
454 };
455 
456 /**
457  * rtas_function_token() - RTAS function token lookup.
458  * @handle: Function handle, e.g. RTAS_FN_EVENT_SCAN.
459  *
460  * Context: Any context.
461  * Return: the token value for the function if implemented by this platform,
462  *         otherwise RTAS_UNKNOWN_SERVICE.
463  */
464 s32 rtas_function_token(const rtas_fn_handle_t handle)
465 {
466 	const size_t index = handle.index;
467 	const bool out_of_bounds = index >= ARRAY_SIZE(rtas_function_table);
468 
469 	if (WARN_ONCE(out_of_bounds, "invalid function index %zu", index))
470 		return RTAS_UNKNOWN_SERVICE;
471 	/*
472 	 * Various drivers attempt token lookups on non-RTAS
473 	 * platforms.
474 	 */
475 	if (!rtas.dev)
476 		return RTAS_UNKNOWN_SERVICE;
477 
478 	return rtas_function_table[index].token;
479 }
480 EXPORT_SYMBOL_GPL(rtas_function_token);
481 
482 static int rtas_function_cmp(const void *a, const void *b)
483 {
484 	const struct rtas_function *f1 = a;
485 	const struct rtas_function *f2 = b;
486 
487 	return strcmp(f1->name, f2->name);
488 }
489 
490 /*
491  * Boot-time initialization of the function table needs the lookup to
492  * return a non-const-qualified object. Use rtas_name_to_function()
493  * in all other contexts.
494  */
495 static struct rtas_function *__rtas_name_to_function(const char *name)
496 {
497 	const struct rtas_function key = {
498 		.name = name,
499 	};
500 	struct rtas_function *found;
501 
502 	found = bsearch(&key, rtas_function_table, ARRAY_SIZE(rtas_function_table),
503 			sizeof(rtas_function_table[0]), rtas_function_cmp);
504 
505 	return found;
506 }
507 
508 static const struct rtas_function *rtas_name_to_function(const char *name)
509 {
510 	return __rtas_name_to_function(name);
511 }
512 
513 static DEFINE_XARRAY(rtas_token_to_function_xarray);
514 
515 static int __init rtas_token_to_function_xarray_init(void)
516 {
517 	int err = 0;
518 
519 	for (size_t i = 0; i < ARRAY_SIZE(rtas_function_table); ++i) {
520 		const struct rtas_function *func = &rtas_function_table[i];
521 		const s32 token = func->token;
522 
523 		if (token == RTAS_UNKNOWN_SERVICE)
524 			continue;
525 
526 		err = xa_err(xa_store(&rtas_token_to_function_xarray,
527 				      token, (void *)func, GFP_KERNEL));
528 		if (err)
529 			break;
530 	}
531 
532 	return err;
533 }
534 arch_initcall(rtas_token_to_function_xarray_init);
535 
536 static const struct rtas_function *rtas_token_to_function(s32 token)
537 {
538 	const struct rtas_function *func;
539 
540 	if (WARN_ONCE(token < 0, "invalid token %d", token))
541 		return NULL;
542 
543 	func = xa_load(&rtas_token_to_function_xarray, token);
544 
545 	if (WARN_ONCE(!func, "unexpected failed lookup for token %d", token))
546 		return NULL;
547 
548 	return func;
549 }
550 
551 /* This is here deliberately so it's only used in this file */
552 void enter_rtas(unsigned long);
553 
554 static void __do_enter_rtas(struct rtas_args *args)
555 {
556 	enter_rtas(__pa(args));
557 	srr_regs_clobbered(); /* rtas uses SRRs, invalidate */
558 }
559 
560 static void __do_enter_rtas_trace(struct rtas_args *args)
561 {
562 	const char *name = NULL;
563 	/*
564 	 * If the tracepoints that consume the function name aren't
565 	 * active, avoid the lookup.
566 	 */
567 	if ((trace_rtas_input_enabled() || trace_rtas_output_enabled())) {
568 		const s32 token = be32_to_cpu(args->token);
569 		const struct rtas_function *func = rtas_token_to_function(token);
570 
571 		name = func->name;
572 	}
573 
574 	trace_rtas_input(args, name);
575 	trace_rtas_ll_entry(args);
576 
577 	__do_enter_rtas(args);
578 
579 	trace_rtas_ll_exit(args);
580 	trace_rtas_output(args, name);
581 }
582 
583 static void do_enter_rtas(struct rtas_args *args)
584 {
585 	const unsigned long msr = mfmsr();
586 	/*
587 	 * Situations where we want to skip any active tracepoints for
588 	 * safety reasons:
589 	 *
590 	 * 1. The last code executed on an offline CPU as it stops,
591 	 *    i.e. we're about to call stop-self. The tracepoints'
592 	 *    function name lookup uses xarray, which uses RCU, which
593 	 *    isn't valid to call on an offline CPU.  Any events
594 	 *    emitted on an offline CPU will be discarded anyway.
595 	 *
596 	 * 2. In real mode, as when invoking ibm,nmi-interlock from
597 	 *    the pseries MCE handler. We cannot count on trace
598 	 *    buffers or the entries in rtas_token_to_function_xarray
599 	 *    to be contained in the RMO.
600 	 */
601 	const unsigned long mask = MSR_IR | MSR_DR;
602 	const bool can_trace = likely(cpu_online(raw_smp_processor_id()) &&
603 				      (msr & mask) == mask);
604 	/*
605 	 * Make sure MSR[RI] is currently enabled as it will be forced later
606 	 * in enter_rtas.
607 	 */
608 	BUG_ON(!(msr & MSR_RI));
609 
610 	BUG_ON(!irqs_disabled());
611 
612 	hard_irq_disable(); /* Ensure MSR[EE] is disabled on PPC64 */
613 
614 	if (can_trace)
615 		__do_enter_rtas_trace(args);
616 	else
617 		__do_enter_rtas(args);
618 }
619 
620 struct rtas_t rtas;
621 
622 /*
623  * Nearly all RTAS calls need to be serialized. All uses of the
624  * default rtas_args block must hold rtas_lock.
625  *
626  * Exceptions to the RTAS serialization requirement (e.g. stop-self)
627  * must use a separate rtas_args structure.
628  */
629 static DEFINE_RAW_SPINLOCK(rtas_lock);
630 static struct rtas_args rtas_args;
631 
632 DEFINE_SPINLOCK(rtas_data_buf_lock);
633 EXPORT_SYMBOL_GPL(rtas_data_buf_lock);
634 
635 char rtas_data_buf[RTAS_DATA_BUF_SIZE] __aligned(SZ_4K);
636 EXPORT_SYMBOL_GPL(rtas_data_buf);
637 
638 unsigned long rtas_rmo_buf;
639 
640 /*
641  * If non-NULL, this gets called when the kernel terminates.
642  * This is done like this so rtas_flash can be a module.
643  */
644 void (*rtas_flash_term_hook)(int);
645 EXPORT_SYMBOL_GPL(rtas_flash_term_hook);
646 
647 /*
648  * call_rtas_display_status and call_rtas_display_status_delay
649  * are designed only for very early low-level debugging, which
650  * is why the token is hard-coded to 10.
651  */
652 static void call_rtas_display_status(unsigned char c)
653 {
654 	unsigned long flags;
655 
656 	if (!rtas.base)
657 		return;
658 
659 	raw_spin_lock_irqsave(&rtas_lock, flags);
660 	rtas_call_unlocked(&rtas_args, 10, 1, 1, NULL, c);
661 	raw_spin_unlock_irqrestore(&rtas_lock, flags);
662 }
663 
664 static void call_rtas_display_status_delay(char c)
665 {
666 	static int pending_newline = 0;  /* did last write end with unprinted newline? */
667 	static int width = 16;
668 
669 	if (c == '\n') {
670 		while (width-- > 0)
671 			call_rtas_display_status(' ');
672 		width = 16;
673 		mdelay(500);
674 		pending_newline = 1;
675 	} else {
676 		if (pending_newline) {
677 			call_rtas_display_status('\r');
678 			call_rtas_display_status('\n');
679 		}
680 		pending_newline = 0;
681 		if (width--) {
682 			call_rtas_display_status(c);
683 			udelay(10000);
684 		}
685 	}
686 }
687 
688 void __init udbg_init_rtas_panel(void)
689 {
690 	udbg_putc = call_rtas_display_status_delay;
691 }
692 
693 #ifdef CONFIG_UDBG_RTAS_CONSOLE
694 
695 /* If you think you're dying before early_init_dt_scan_rtas() does its
696  * work, you can hard code the token values for your firmware here and
697  * hardcode rtas.base/entry etc.
698  */
699 static unsigned int rtas_putchar_token = RTAS_UNKNOWN_SERVICE;
700 static unsigned int rtas_getchar_token = RTAS_UNKNOWN_SERVICE;
701 
702 static void udbg_rtascon_putc(char c)
703 {
704 	int tries;
705 
706 	if (!rtas.base)
707 		return;
708 
709 	/* Add CRs before LFs */
710 	if (c == '\n')
711 		udbg_rtascon_putc('\r');
712 
713 	/* if there is more than one character to be displayed, wait a bit */
714 	for (tries = 0; tries < 16; tries++) {
715 		if (rtas_call(rtas_putchar_token, 1, 1, NULL, c) == 0)
716 			break;
717 		udelay(1000);
718 	}
719 }
720 
721 static int udbg_rtascon_getc_poll(void)
722 {
723 	int c;
724 
725 	if (!rtas.base)
726 		return -1;
727 
728 	if (rtas_call(rtas_getchar_token, 0, 2, &c))
729 		return -1;
730 
731 	return c;
732 }
733 
734 static int udbg_rtascon_getc(void)
735 {
736 	int c;
737 
738 	while ((c = udbg_rtascon_getc_poll()) == -1)
739 		;
740 
741 	return c;
742 }
743 
744 
745 void __init udbg_init_rtas_console(void)
746 {
747 	udbg_putc = udbg_rtascon_putc;
748 	udbg_getc = udbg_rtascon_getc;
749 	udbg_getc_poll = udbg_rtascon_getc_poll;
750 }
751 #endif /* CONFIG_UDBG_RTAS_CONSOLE */
752 
753 void rtas_progress(char *s, unsigned short hex)
754 {
755 	struct device_node *root;
756 	int width;
757 	const __be32 *p;
758 	char *os;
759 	static int display_character, set_indicator;
760 	static int display_width, display_lines, form_feed;
761 	static const int *row_width;
762 	static DEFINE_SPINLOCK(progress_lock);
763 	static int current_line;
764 	static int pending_newline = 0;  /* did last write end with unprinted newline? */
765 
766 	if (!rtas.base)
767 		return;
768 
769 	if (display_width == 0) {
770 		display_width = 0x10;
771 		if ((root = of_find_node_by_path("/rtas"))) {
772 			if ((p = of_get_property(root,
773 					"ibm,display-line-length", NULL)))
774 				display_width = be32_to_cpu(*p);
775 			if ((p = of_get_property(root,
776 					"ibm,form-feed", NULL)))
777 				form_feed = be32_to_cpu(*p);
778 			if ((p = of_get_property(root,
779 					"ibm,display-number-of-lines", NULL)))
780 				display_lines = be32_to_cpu(*p);
781 			row_width = of_get_property(root,
782 					"ibm,display-truncation-length", NULL);
783 			of_node_put(root);
784 		}
785 		display_character = rtas_function_token(RTAS_FN_DISPLAY_CHARACTER);
786 		set_indicator = rtas_function_token(RTAS_FN_SET_INDICATOR);
787 	}
788 
789 	if (display_character == RTAS_UNKNOWN_SERVICE) {
790 		/* use hex display if available */
791 		if (set_indicator != RTAS_UNKNOWN_SERVICE)
792 			rtas_call(set_indicator, 3, 1, NULL, 6, 0, hex);
793 		return;
794 	}
795 
796 	spin_lock(&progress_lock);
797 
798 	/*
799 	 * Last write ended with newline, but we didn't print it since
800 	 * it would just clear the bottom line of output. Print it now
801 	 * instead.
802 	 *
803 	 * If no newline is pending and form feed is supported, clear the
804 	 * display with a form feed; otherwise, print a CR to start output
805 	 * at the beginning of the line.
806 	 */
807 	if (pending_newline) {
808 		rtas_call(display_character, 1, 1, NULL, '\r');
809 		rtas_call(display_character, 1, 1, NULL, '\n');
810 		pending_newline = 0;
811 	} else {
812 		current_line = 0;
813 		if (form_feed)
814 			rtas_call(display_character, 1, 1, NULL,
815 				  (char)form_feed);
816 		else
817 			rtas_call(display_character, 1, 1, NULL, '\r');
818 	}
819 
820 	if (row_width)
821 		width = row_width[current_line];
822 	else
823 		width = display_width;
824 	os = s;
825 	while (*os) {
826 		if (*os == '\n' || *os == '\r') {
827 			/* If newline is the last character, save it
828 			 * until next call to avoid bumping up the
829 			 * display output.
830 			 */
831 			if (*os == '\n' && !os[1]) {
832 				pending_newline = 1;
833 				current_line++;
834 				if (current_line > display_lines-1)
835 					current_line = display_lines-1;
836 				spin_unlock(&progress_lock);
837 				return;
838 			}
839 
840 			/* RTAS wants CR-LF, not just LF */
841 
842 			if (*os == '\n') {
843 				rtas_call(display_character, 1, 1, NULL, '\r');
844 				rtas_call(display_character, 1, 1, NULL, '\n');
845 			} else {
846 				/* CR might be used to re-draw a line, so we'll
847 				 * leave it alone and not add LF.
848 				 */
849 				rtas_call(display_character, 1, 1, NULL, *os);
850 			}
851 
852 			if (row_width)
853 				width = row_width[current_line];
854 			else
855 				width = display_width;
856 		} else {
857 			width--;
858 			rtas_call(display_character, 1, 1, NULL, *os);
859 		}
860 
861 		os++;
862 
863 		/* if we overwrite the screen length */
864 		if (width <= 0)
865 			while ((*os != 0) && (*os != '\n') && (*os != '\r'))
866 				os++;
867 	}
868 
869 	spin_unlock(&progress_lock);
870 }
871 EXPORT_SYMBOL_GPL(rtas_progress);		/* needed by rtas_flash module */
872 
873 int rtas_token(const char *service)
874 {
875 	const struct rtas_function *func;
876 	const __be32 *tokp;
877 
878 	if (rtas.dev == NULL)
879 		return RTAS_UNKNOWN_SERVICE;
880 
881 	func = rtas_name_to_function(service);
882 	if (func)
883 		return func->token;
884 	/*
885 	 * The caller is looking up a name that is not known to be an
886 	 * RTAS function. Either it's a function that needs to be
887 	 * added to the table, or they're misusing rtas_token() to
888 	 * access non-function properties of the /rtas node. Warn and
889 	 * fall back to the legacy behavior.
890 	 */
891 	WARN_ONCE(1, "unknown function `%s`, should it be added to rtas_function_table?\n",
892 		  service);
893 
894 	tokp = of_get_property(rtas.dev, service, NULL);
895 	return tokp ? be32_to_cpu(*tokp) : RTAS_UNKNOWN_SERVICE;
896 }
897 EXPORT_SYMBOL_GPL(rtas_token);
898 
899 int rtas_service_present(const char *service)
900 {
901 	return rtas_token(service) != RTAS_UNKNOWN_SERVICE;
902 }
903 
904 #ifdef CONFIG_RTAS_ERROR_LOGGING
905 
906 static u32 rtas_error_log_max __ro_after_init = RTAS_ERROR_LOG_MAX;
907 
908 /*
909  * Return the firmware-specified size of the error log buffer
910  *  for all rtas calls that require an error buffer argument.
911  *  This includes 'check-exception' and 'rtas-last-error'.
912  */
913 int rtas_get_error_log_max(void)
914 {
915 	return rtas_error_log_max;
916 }
917 
918 static void __init init_error_log_max(void)
919 {
920 	static const char propname[] __initconst = "rtas-error-log-max";
921 	u32 max;
922 
923 	if (of_property_read_u32(rtas.dev, propname, &max)) {
924 		pr_warn("%s not found, using default of %u\n",
925 			propname, RTAS_ERROR_LOG_MAX);
926 		max = RTAS_ERROR_LOG_MAX;
927 	}
928 
929 	if (max > RTAS_ERROR_LOG_MAX) {
930 		pr_warn("%s = %u, clamping max error log size to %u\n",
931 			propname, max, RTAS_ERROR_LOG_MAX);
932 		max = RTAS_ERROR_LOG_MAX;
933 	}
934 
935 	rtas_error_log_max = max;
936 }
937 
938 
939 static char rtas_err_buf[RTAS_ERROR_LOG_MAX];
940 
941 /** Return a copy of the detailed error text associated with the
942  *  most recent failed call to rtas.  Because the error text
943  *  might go stale if there are any other intervening rtas calls,
944  *  this routine must be called atomically with whatever produced
945  *  the error (i.e. with rtas_lock still held from the previous call).
946  */
947 static char *__fetch_rtas_last_error(char *altbuf)
948 {
949 	const s32 token = rtas_function_token(RTAS_FN_RTAS_LAST_ERROR);
950 	struct rtas_args err_args, save_args;
951 	u32 bufsz;
952 	char *buf = NULL;
953 
954 	if (token == -1)
955 		return NULL;
956 
957 	bufsz = rtas_get_error_log_max();
958 
959 	err_args.token = cpu_to_be32(token);
960 	err_args.nargs = cpu_to_be32(2);
961 	err_args.nret = cpu_to_be32(1);
962 	err_args.args[0] = cpu_to_be32(__pa(rtas_err_buf));
963 	err_args.args[1] = cpu_to_be32(bufsz);
964 	err_args.args[2] = 0;
965 
966 	save_args = rtas_args;
967 	rtas_args = err_args;
968 
969 	do_enter_rtas(&rtas_args);
970 
971 	err_args = rtas_args;
972 	rtas_args = save_args;
973 
974 	/* Log the error in the unlikely case that there was one. */
975 	if (unlikely(err_args.args[2] == 0)) {
976 		if (altbuf) {
977 			buf = altbuf;
978 		} else {
979 			buf = rtas_err_buf;
980 			if (slab_is_available())
981 				buf = kmalloc(RTAS_ERROR_LOG_MAX, GFP_ATOMIC);
982 		}
983 		if (buf)
984 			memcpy(buf, rtas_err_buf, RTAS_ERROR_LOG_MAX);
985 	}
986 
987 	return buf;
988 }
989 
990 #define get_errorlog_buffer()	kmalloc(RTAS_ERROR_LOG_MAX, GFP_KERNEL)
991 
992 #else /* CONFIG_RTAS_ERROR_LOGGING */
993 #define __fetch_rtas_last_error(x)	NULL
994 #define get_errorlog_buffer()		NULL
995 static void __init init_error_log_max(void) {}
996 #endif
997 
998 
999 static void
1000 va_rtas_call_unlocked(struct rtas_args *args, int token, int nargs, int nret,
1001 		      va_list list)
1002 {
1003 	int i;
1004 
1005 	args->token = cpu_to_be32(token);
1006 	args->nargs = cpu_to_be32(nargs);
1007 	args->nret  = cpu_to_be32(nret);
1008 	args->rets  = &(args->args[nargs]);
1009 
1010 	for (i = 0; i < nargs; ++i)
1011 		args->args[i] = cpu_to_be32(va_arg(list, __u32));
1012 
1013 	for (i = 0; i < nret; ++i)
1014 		args->rets[i] = 0;
1015 
1016 	do_enter_rtas(args);
1017 }
1018 
1019 void rtas_call_unlocked(struct rtas_args *args, int token, int nargs, int nret, ...)
1020 {
1021 	va_list list;
1022 
1023 	va_start(list, nret);
1024 	va_rtas_call_unlocked(args, token, nargs, nret, list);
1025 	va_end(list);
1026 }
1027 
1028 static bool token_is_restricted_errinjct(s32 token)
1029 {
1030 	return token == rtas_function_token(RTAS_FN_IBM_OPEN_ERRINJCT) ||
1031 	       token == rtas_function_token(RTAS_FN_IBM_ERRINJCT);
1032 }
1033 
1034 /**
1035  * rtas_call() - Invoke an RTAS firmware function.
1036  * @token: Identifies the function being invoked.
1037  * @nargs: Number of input parameters. Does not include token.
1038  * @nret: Number of output parameters, including the call status.
1039  * @outputs: Array of @nret output words.
1040  * @....: List of @nargs input parameters.
1041  *
1042  * Invokes the RTAS function indicated by @token, which the caller
1043  * should obtain via rtas_function_token().
1044  *
1045  * The @nargs and @nret arguments must match the number of input and
1046  * output parameters specified for the RTAS function.
1047  *
1048  * rtas_call() returns RTAS status codes, not conventional Linux errno
1049  * values. Callers must translate any failure to an appropriate errno
1050  * in syscall context. Most callers of RTAS functions that can return
1051  * -2 or 990x should use rtas_busy_delay() to correctly handle those
1052  * statuses before calling again.
1053  *
1054  * The return value descriptions are adapted from 7.2.8 [RTAS] Return
1055  * Codes of the PAPR and CHRP specifications.
1056  *
1057  * Context: Process context preferably, interrupt context if
1058  *          necessary.  Acquires an internal spinlock and may perform
1059  *          GFP_ATOMIC slab allocation in error path. Unsafe for NMI
1060  *          context.
1061  * Return:
1062  * *                          0 - RTAS function call succeeded.
1063  * *                         -1 - RTAS function encountered a hardware or
1064  *                                platform error, or the token is invalid,
1065  *                                or the function is restricted by kernel policy.
1066  * *                         -2 - Specs say "A necessary hardware device was busy,
1067  *                                and the requested function could not be
1068  *                                performed. The operation should be retried at
1069  *                                a later time." This is misleading, at least with
1070  *                                respect to current RTAS implementations. What it
1071  *                                usually means in practice is that the function
1072  *                                could not be completed while meeting RTAS's
1073  *                                deadline for returning control to the OS (250us
1074  *                                for PAPR/PowerVM, typically), but the call may be
1075  *                                immediately reattempted to resume work on it.
1076  * *                         -3 - Parameter error.
1077  * *                         -7 - Unexpected state change.
1078  * *                9000...9899 - Vendor-specific success codes.
1079  * *                9900...9905 - Advisory extended delay. Caller should try
1080  *                                again after ~10^x ms has elapsed, where x is
1081  *                                the last digit of the status [0-5]. Again going
1082  *                                beyond the PAPR text, 990x on PowerVM indicates
1083  *                                contention for RTAS-internal resources. Other
1084  *                                RTAS call sequences in progress should be
1085  *                                allowed to complete before reattempting the
1086  *                                call.
1087  * *                      -9000 - Multi-level isolation error.
1088  * *              -9999...-9004 - Vendor-specific error codes.
1089  * * Additional negative values - Function-specific error.
1090  * * Additional positive values - Function-specific success.
1091  */
1092 int rtas_call(int token, int nargs, int nret, int *outputs, ...)
1093 {
1094 	va_list list;
1095 	int i;
1096 	unsigned long flags;
1097 	struct rtas_args *args;
1098 	char *buff_copy = NULL;
1099 	int ret;
1100 
1101 	if (!rtas.entry || token == RTAS_UNKNOWN_SERVICE)
1102 		return -1;
1103 
1104 	if (token_is_restricted_errinjct(token)) {
1105 		/*
1106 		 * It would be nicer to not discard the error value
1107 		 * from security_locked_down(), but callers expect an
1108 		 * RTAS status, not an errno.
1109 		 */
1110 		if (security_locked_down(LOCKDOWN_RTAS_ERROR_INJECTION))
1111 			return -1;
1112 	}
1113 
1114 	if ((mfmsr() & (MSR_IR|MSR_DR)) != (MSR_IR|MSR_DR)) {
1115 		WARN_ON_ONCE(1);
1116 		return -1;
1117 	}
1118 
1119 	raw_spin_lock_irqsave(&rtas_lock, flags);
1120 	/* We use the global rtas args buffer */
1121 	args = &rtas_args;
1122 
1123 	va_start(list, outputs);
1124 	va_rtas_call_unlocked(args, token, nargs, nret, list);
1125 	va_end(list);
1126 
1127 	/* A -1 return code indicates that the last command couldn't
1128 	   be completed due to a hardware error. */
1129 	if (be32_to_cpu(args->rets[0]) == -1)
1130 		buff_copy = __fetch_rtas_last_error(NULL);
1131 
1132 	if (nret > 1 && outputs != NULL)
1133 		for (i = 0; i < nret-1; ++i)
1134 			outputs[i] = be32_to_cpu(args->rets[i + 1]);
1135 	ret = (nret > 0) ? be32_to_cpu(args->rets[0]) : 0;
1136 
1137 	raw_spin_unlock_irqrestore(&rtas_lock, flags);
1138 
1139 	if (buff_copy) {
1140 		log_error(buff_copy, ERR_TYPE_RTAS_LOG, 0);
1141 		if (slab_is_available())
1142 			kfree(buff_copy);
1143 	}
1144 	return ret;
1145 }
1146 EXPORT_SYMBOL_GPL(rtas_call);
1147 
1148 /**
1149  * rtas_busy_delay_time() - From an RTAS status value, calculate the
1150  *                          suggested delay time in milliseconds.
1151  *
1152  * @status: a value returned from rtas_call() or similar APIs which return
1153  *          the status of a RTAS function call.
1154  *
1155  * Context: Any context.
1156  *
1157  * Return:
1158  * * 100000 - If @status is 9905.
1159  * * 10000  - If @status is 9904.
1160  * * 1000   - If @status is 9903.
1161  * * 100    - If @status is 9902.
1162  * * 10     - If @status is 9901.
1163  * * 1      - If @status is either 9900 or -2. This is "wrong" for -2, but
1164  *            some callers depend on this behavior, and the worst outcome
1165  *            is that they will delay for longer than necessary.
1166  * * 0      - If @status is not a busy or extended delay value.
1167  */
1168 unsigned int rtas_busy_delay_time(int status)
1169 {
1170 	int order;
1171 	unsigned int ms = 0;
1172 
1173 	if (status == RTAS_BUSY) {
1174 		ms = 1;
1175 	} else if (status >= RTAS_EXTENDED_DELAY_MIN &&
1176 		   status <= RTAS_EXTENDED_DELAY_MAX) {
1177 		order = status - RTAS_EXTENDED_DELAY_MIN;
1178 		for (ms = 1; order > 0; order--)
1179 			ms *= 10;
1180 	}
1181 
1182 	return ms;
1183 }
1184 
1185 /*
1186  * Early boot fallback for rtas_busy_delay().
1187  */
1188 static bool __init rtas_busy_delay_early(int status)
1189 {
1190 	static size_t successive_ext_delays __initdata;
1191 	bool retry;
1192 
1193 	switch (status) {
1194 	case RTAS_EXTENDED_DELAY_MIN...RTAS_EXTENDED_DELAY_MAX:
1195 		/*
1196 		 * In the unlikely case that we receive an extended
1197 		 * delay status in early boot, the OS is probably not
1198 		 * the cause, and there's nothing we can do to clear
1199 		 * the condition. Best we can do is delay for a bit
1200 		 * and hope it's transient. Lie to the caller if it
1201 		 * seems like we're stuck in a retry loop.
1202 		 */
1203 		mdelay(1);
1204 		retry = true;
1205 		successive_ext_delays += 1;
1206 		if (successive_ext_delays > 1000) {
1207 			pr_err("too many extended delays, giving up\n");
1208 			dump_stack();
1209 			retry = false;
1210 			successive_ext_delays = 0;
1211 		}
1212 		break;
1213 	case RTAS_BUSY:
1214 		retry = true;
1215 		successive_ext_delays = 0;
1216 		break;
1217 	default:
1218 		retry = false;
1219 		successive_ext_delays = 0;
1220 		break;
1221 	}
1222 
1223 	return retry;
1224 }
1225 
1226 /**
1227  * rtas_busy_delay() - helper for RTAS busy and extended delay statuses
1228  *
1229  * @status: a value returned from rtas_call() or similar APIs which return
1230  *          the status of a RTAS function call.
1231  *
1232  * Context: Process context. May sleep or schedule.
1233  *
1234  * Return:
1235  * * true  - @status is RTAS_BUSY or an extended delay hint. The
1236  *           caller may assume that the CPU has been yielded if necessary,
1237  *           and that an appropriate delay for @status has elapsed.
1238  *           Generally the caller should reattempt the RTAS call which
1239  *           yielded @status.
1240  *
1241  * * false - @status is not @RTAS_BUSY nor an extended delay hint. The
1242  *           caller is responsible for handling @status.
1243  */
1244 bool __ref rtas_busy_delay(int status)
1245 {
1246 	unsigned int ms;
1247 	bool ret;
1248 
1249 	/*
1250 	 * Can't do timed sleeps before timekeeping is up.
1251 	 */
1252 	if (system_state < SYSTEM_SCHEDULING)
1253 		return rtas_busy_delay_early(status);
1254 
1255 	switch (status) {
1256 	case RTAS_EXTENDED_DELAY_MIN...RTAS_EXTENDED_DELAY_MAX:
1257 		ret = true;
1258 		ms = rtas_busy_delay_time(status);
1259 		/*
1260 		 * The extended delay hint can be as high as 100 seconds.
1261 		 * Surely any function returning such a status is either
1262 		 * buggy or isn't going to be significantly slowed by us
1263 		 * polling at 1HZ. Clamp the sleep time to one second.
1264 		 */
1265 		ms = clamp(ms, 1U, 1000U);
1266 		/*
1267 		 * The delay hint is an order-of-magnitude suggestion, not
1268 		 * a minimum. It is fine, possibly even advantageous, for
1269 		 * us to pause for less time than hinted. For small values,
1270 		 * use usleep_range() to ensure we don't sleep much longer
1271 		 * than actually needed.
1272 		 *
1273 		 * See Documentation/timers/timers-howto.rst for
1274 		 * explanation of the threshold used here. In effect we use
1275 		 * usleep_range() for 9900 and 9901, msleep() for
1276 		 * 9902-9905.
1277 		 */
1278 		if (ms <= 20)
1279 			usleep_range(ms * 100, ms * 1000);
1280 		else
1281 			msleep(ms);
1282 		break;
1283 	case RTAS_BUSY:
1284 		ret = true;
1285 		/*
1286 		 * We should call again immediately if there's no other
1287 		 * work to do.
1288 		 */
1289 		cond_resched();
1290 		break;
1291 	default:
1292 		ret = false;
1293 		/*
1294 		 * Not a busy or extended delay status; the caller should
1295 		 * handle @status itself. Ensure we warn on misuses in
1296 		 * atomic context regardless.
1297 		 */
1298 		might_sleep();
1299 		break;
1300 	}
1301 
1302 	return ret;
1303 }
1304 EXPORT_SYMBOL_GPL(rtas_busy_delay);
1305 
1306 static int rtas_error_rc(int rtas_rc)
1307 {
1308 	int rc;
1309 
1310 	switch (rtas_rc) {
1311 		case -1: 		/* Hardware Error */
1312 			rc = -EIO;
1313 			break;
1314 		case -3:		/* Bad indicator/domain/etc */
1315 			rc = -EINVAL;
1316 			break;
1317 		case -9000:		/* Isolation error */
1318 			rc = -EFAULT;
1319 			break;
1320 		case -9001:		/* Outstanding TCE/PTE */
1321 			rc = -EEXIST;
1322 			break;
1323 		case -9002:		/* No usable slot */
1324 			rc = -ENODEV;
1325 			break;
1326 		default:
1327 			pr_err("%s: unexpected error %d\n", __func__, rtas_rc);
1328 			rc = -ERANGE;
1329 			break;
1330 	}
1331 	return rc;
1332 }
1333 
1334 int rtas_get_power_level(int powerdomain, int *level)
1335 {
1336 	int token = rtas_function_token(RTAS_FN_GET_POWER_LEVEL);
1337 	int rc;
1338 
1339 	if (token == RTAS_UNKNOWN_SERVICE)
1340 		return -ENOENT;
1341 
1342 	while ((rc = rtas_call(token, 1, 2, level, powerdomain)) == RTAS_BUSY)
1343 		udelay(1);
1344 
1345 	if (rc < 0)
1346 		return rtas_error_rc(rc);
1347 	return rc;
1348 }
1349 EXPORT_SYMBOL_GPL(rtas_get_power_level);
1350 
1351 int rtas_set_power_level(int powerdomain, int level, int *setlevel)
1352 {
1353 	int token = rtas_function_token(RTAS_FN_SET_POWER_LEVEL);
1354 	int rc;
1355 
1356 	if (token == RTAS_UNKNOWN_SERVICE)
1357 		return -ENOENT;
1358 
1359 	do {
1360 		rc = rtas_call(token, 2, 2, setlevel, powerdomain, level);
1361 	} while (rtas_busy_delay(rc));
1362 
1363 	if (rc < 0)
1364 		return rtas_error_rc(rc);
1365 	return rc;
1366 }
1367 EXPORT_SYMBOL_GPL(rtas_set_power_level);
1368 
1369 int rtas_get_sensor(int sensor, int index, int *state)
1370 {
1371 	int token = rtas_function_token(RTAS_FN_GET_SENSOR_STATE);
1372 	int rc;
1373 
1374 	if (token == RTAS_UNKNOWN_SERVICE)
1375 		return -ENOENT;
1376 
1377 	do {
1378 		rc = rtas_call(token, 2, 2, state, sensor, index);
1379 	} while (rtas_busy_delay(rc));
1380 
1381 	if (rc < 0)
1382 		return rtas_error_rc(rc);
1383 	return rc;
1384 }
1385 EXPORT_SYMBOL_GPL(rtas_get_sensor);
1386 
1387 int rtas_get_sensor_fast(int sensor, int index, int *state)
1388 {
1389 	int token = rtas_function_token(RTAS_FN_GET_SENSOR_STATE);
1390 	int rc;
1391 
1392 	if (token == RTAS_UNKNOWN_SERVICE)
1393 		return -ENOENT;
1394 
1395 	rc = rtas_call(token, 2, 2, state, sensor, index);
1396 	WARN_ON(rc == RTAS_BUSY || (rc >= RTAS_EXTENDED_DELAY_MIN &&
1397 				    rc <= RTAS_EXTENDED_DELAY_MAX));
1398 
1399 	if (rc < 0)
1400 		return rtas_error_rc(rc);
1401 	return rc;
1402 }
1403 
1404 bool rtas_indicator_present(int token, int *maxindex)
1405 {
1406 	int proplen, count, i;
1407 	const struct indicator_elem {
1408 		__be32 token;
1409 		__be32 maxindex;
1410 	} *indicators;
1411 
1412 	indicators = of_get_property(rtas.dev, "rtas-indicators", &proplen);
1413 	if (!indicators)
1414 		return false;
1415 
1416 	count = proplen / sizeof(struct indicator_elem);
1417 
1418 	for (i = 0; i < count; i++) {
1419 		if (__be32_to_cpu(indicators[i].token) != token)
1420 			continue;
1421 		if (maxindex)
1422 			*maxindex = __be32_to_cpu(indicators[i].maxindex);
1423 		return true;
1424 	}
1425 
1426 	return false;
1427 }
1428 
1429 int rtas_set_indicator(int indicator, int index, int new_value)
1430 {
1431 	int token = rtas_function_token(RTAS_FN_SET_INDICATOR);
1432 	int rc;
1433 
1434 	if (token == RTAS_UNKNOWN_SERVICE)
1435 		return -ENOENT;
1436 
1437 	do {
1438 		rc = rtas_call(token, 3, 1, NULL, indicator, index, new_value);
1439 	} while (rtas_busy_delay(rc));
1440 
1441 	if (rc < 0)
1442 		return rtas_error_rc(rc);
1443 	return rc;
1444 }
1445 EXPORT_SYMBOL_GPL(rtas_set_indicator);
1446 
1447 /*
1448  * Ignoring RTAS extended delay
1449  */
1450 int rtas_set_indicator_fast(int indicator, int index, int new_value)
1451 {
1452 	int token = rtas_function_token(RTAS_FN_SET_INDICATOR);
1453 	int rc;
1454 
1455 	if (token == RTAS_UNKNOWN_SERVICE)
1456 		return -ENOENT;
1457 
1458 	rc = rtas_call(token, 3, 1, NULL, indicator, index, new_value);
1459 
1460 	WARN_ON(rc == RTAS_BUSY || (rc >= RTAS_EXTENDED_DELAY_MIN &&
1461 				    rc <= RTAS_EXTENDED_DELAY_MAX));
1462 
1463 	if (rc < 0)
1464 		return rtas_error_rc(rc);
1465 
1466 	return rc;
1467 }
1468 
1469 /**
1470  * rtas_ibm_suspend_me() - Call ibm,suspend-me to suspend the LPAR.
1471  *
1472  * @fw_status: RTAS call status will be placed here if not NULL.
1473  *
1474  * rtas_ibm_suspend_me() should be called only on a CPU which has
1475  * received H_CONTINUE from the H_JOIN hcall. All other active CPUs
1476  * should be waiting to return from H_JOIN.
1477  *
1478  * rtas_ibm_suspend_me() may suspend execution of the OS
1479  * indefinitely. Callers should take appropriate measures upon return, such as
1480  * resetting watchdog facilities.
1481  *
1482  * Callers may choose to retry this call if @fw_status is
1483  * %RTAS_THREADS_ACTIVE.
1484  *
1485  * Return:
1486  * 0          - The partition has resumed from suspend, possibly after
1487  *              migration to a different host.
1488  * -ECANCELED - The operation was aborted.
1489  * -EAGAIN    - There were other CPUs not in H_JOIN at the time of the call.
1490  * -EBUSY     - Some other condition prevented the suspend from succeeding.
1491  * -EIO       - Hardware/platform error.
1492  */
1493 int rtas_ibm_suspend_me(int *fw_status)
1494 {
1495 	int token = rtas_function_token(RTAS_FN_IBM_SUSPEND_ME);
1496 	int fwrc;
1497 	int ret;
1498 
1499 	fwrc = rtas_call(token, 0, 1, NULL);
1500 
1501 	switch (fwrc) {
1502 	case 0:
1503 		ret = 0;
1504 		break;
1505 	case RTAS_SUSPEND_ABORTED:
1506 		ret = -ECANCELED;
1507 		break;
1508 	case RTAS_THREADS_ACTIVE:
1509 		ret = -EAGAIN;
1510 		break;
1511 	case RTAS_NOT_SUSPENDABLE:
1512 	case RTAS_OUTSTANDING_COPROC:
1513 		ret = -EBUSY;
1514 		break;
1515 	case -1:
1516 	default:
1517 		ret = -EIO;
1518 		break;
1519 	}
1520 
1521 	if (fw_status)
1522 		*fw_status = fwrc;
1523 
1524 	return ret;
1525 }
1526 
1527 void __noreturn rtas_restart(char *cmd)
1528 {
1529 	if (rtas_flash_term_hook)
1530 		rtas_flash_term_hook(SYS_RESTART);
1531 	pr_emerg("system-reboot returned %d\n",
1532 		 rtas_call(rtas_function_token(RTAS_FN_SYSTEM_REBOOT), 0, 1, NULL));
1533 	for (;;);
1534 }
1535 
1536 void rtas_power_off(void)
1537 {
1538 	if (rtas_flash_term_hook)
1539 		rtas_flash_term_hook(SYS_POWER_OFF);
1540 	/* allow power on only with power button press */
1541 	pr_emerg("power-off returned %d\n",
1542 		 rtas_call(rtas_function_token(RTAS_FN_POWER_OFF), 2, 1, NULL, -1, -1));
1543 	for (;;);
1544 }
1545 
1546 void __noreturn rtas_halt(void)
1547 {
1548 	if (rtas_flash_term_hook)
1549 		rtas_flash_term_hook(SYS_HALT);
1550 	/* allow power on only with power button press */
1551 	pr_emerg("power-off returned %d\n",
1552 		 rtas_call(rtas_function_token(RTAS_FN_POWER_OFF), 2, 1, NULL, -1, -1));
1553 	for (;;);
1554 }
1555 
1556 /* Must be in the RMO region, so we place it here */
1557 static char rtas_os_term_buf[2048];
1558 static bool ibm_extended_os_term;
1559 
1560 void rtas_os_term(char *str)
1561 {
1562 	s32 token = rtas_function_token(RTAS_FN_IBM_OS_TERM);
1563 	int status;
1564 
1565 	/*
1566 	 * Firmware with the ibm,extended-os-term property is guaranteed
1567 	 * to always return from an ibm,os-term call. Earlier versions without
1568 	 * this property may terminate the partition which we want to avoid
1569 	 * since it interferes with panic_timeout.
1570 	 */
1571 
1572 	if (token == RTAS_UNKNOWN_SERVICE || !ibm_extended_os_term)
1573 		return;
1574 
1575 	snprintf(rtas_os_term_buf, 2048, "OS panic: %s", str);
1576 
1577 	/*
1578 	 * Keep calling as long as RTAS returns a "try again" status,
1579 	 * but don't use rtas_busy_delay(), which potentially
1580 	 * schedules.
1581 	 */
1582 	do {
1583 		status = rtas_call(token, 1, 1, NULL, __pa(rtas_os_term_buf));
1584 	} while (rtas_busy_delay_time(status));
1585 
1586 	if (status != 0)
1587 		pr_emerg("ibm,os-term call failed %d\n", status);
1588 }
1589 
1590 /**
1591  * rtas_activate_firmware() - Activate a new version of firmware.
1592  *
1593  * Context: This function may sleep.
1594  *
1595  * Activate a new version of partition firmware. The OS must call this
1596  * after resuming from a partition hibernation or migration in order
1597  * to maintain the ability to perform live firmware updates. It's not
1598  * catastrophic for this method to be absent or to fail; just log the
1599  * condition in that case.
1600  */
1601 void rtas_activate_firmware(void)
1602 {
1603 	int token = rtas_function_token(RTAS_FN_IBM_ACTIVATE_FIRMWARE);
1604 	int fwrc;
1605 
1606 	if (token == RTAS_UNKNOWN_SERVICE) {
1607 		pr_notice("ibm,activate-firmware method unavailable\n");
1608 		return;
1609 	}
1610 
1611 	do {
1612 		fwrc = rtas_call(token, 0, 1, NULL);
1613 	} while (rtas_busy_delay(fwrc));
1614 
1615 	if (fwrc)
1616 		pr_err("ibm,activate-firmware failed (%i)\n", fwrc);
1617 }
1618 
1619 /**
1620  * get_pseries_errorlog() - Find a specific pseries error log in an RTAS
1621  *                          extended event log.
1622  * @log: RTAS error/event log
1623  * @section_id: two character section identifier
1624  *
1625  * Return: A pointer to the specified errorlog or NULL if not found.
1626  */
1627 noinstr struct pseries_errorlog *get_pseries_errorlog(struct rtas_error_log *log,
1628 						      uint16_t section_id)
1629 {
1630 	struct rtas_ext_event_log_v6 *ext_log =
1631 		(struct rtas_ext_event_log_v6 *)log->buffer;
1632 	struct pseries_errorlog *sect;
1633 	unsigned char *p, *log_end;
1634 	uint32_t ext_log_length = rtas_error_extended_log_length(log);
1635 	uint8_t log_format = rtas_ext_event_log_format(ext_log);
1636 	uint32_t company_id = rtas_ext_event_company_id(ext_log);
1637 
1638 	/* Check that we understand the format */
1639 	if (ext_log_length < sizeof(struct rtas_ext_event_log_v6) ||
1640 	    log_format != RTAS_V6EXT_LOG_FORMAT_EVENT_LOG ||
1641 	    company_id != RTAS_V6EXT_COMPANY_ID_IBM)
1642 		return NULL;
1643 
1644 	log_end = log->buffer + ext_log_length;
1645 	p = ext_log->vendor_log;
1646 
1647 	while (p < log_end) {
1648 		sect = (struct pseries_errorlog *)p;
1649 		if (pseries_errorlog_id(sect) == section_id)
1650 			return sect;
1651 		p += pseries_errorlog_length(sect);
1652 	}
1653 
1654 	return NULL;
1655 }
1656 
1657 /*
1658  * The sys_rtas syscall, as originally designed, allows root to pass
1659  * arbitrary physical addresses to RTAS calls. A number of RTAS calls
1660  * can be abused to write to arbitrary memory and do other things that
1661  * are potentially harmful to system integrity, and thus should only
1662  * be used inside the kernel and not exposed to userspace.
1663  *
1664  * All known legitimate users of the sys_rtas syscall will only ever
1665  * pass addresses that fall within the RMO buffer, and use a known
1666  * subset of RTAS calls.
1667  *
1668  * Accordingly, we filter RTAS requests to check that the call is
1669  * permitted, and that provided pointers fall within the RMO buffer.
1670  * If a function is allowed to be invoked via the syscall, then its
1671  * entry in the rtas_functions table points to a rtas_filter that
1672  * describes its constraints, with the indexes of the parameters which
1673  * are expected to contain addresses and sizes of buffers allocated
1674  * inside the RMO buffer.
1675  */
1676 
1677 static bool in_rmo_buf(u32 base, u32 end)
1678 {
1679 	return base >= rtas_rmo_buf &&
1680 		base < (rtas_rmo_buf + RTAS_USER_REGION_SIZE) &&
1681 		base <= end &&
1682 		end >= rtas_rmo_buf &&
1683 		end < (rtas_rmo_buf + RTAS_USER_REGION_SIZE);
1684 }
1685 
1686 static bool block_rtas_call(int token, int nargs,
1687 			    struct rtas_args *args)
1688 {
1689 	const struct rtas_function *func;
1690 	const struct rtas_filter *f;
1691 	const bool is_platform_dump = token == rtas_function_token(RTAS_FN_IBM_PLATFORM_DUMP);
1692 	const bool is_config_conn = token == rtas_function_token(RTAS_FN_IBM_CONFIGURE_CONNECTOR);
1693 	u32 base, size, end;
1694 
1695 	/*
1696 	 * If this token doesn't correspond to a function the kernel
1697 	 * understands, you're not allowed to call it.
1698 	 */
1699 	func = rtas_token_to_function(token);
1700 	if (!func)
1701 		goto err;
1702 	/*
1703 	 * And only functions with filters attached are allowed.
1704 	 */
1705 	f = func->filter;
1706 	if (!f)
1707 		goto err;
1708 	/*
1709 	 * And some functions aren't allowed on LE.
1710 	 */
1711 	if (IS_ENABLED(CONFIG_CPU_LITTLE_ENDIAN) && func->banned_for_syscall_on_le)
1712 		goto err;
1713 
1714 	if (f->buf_idx1 != -1) {
1715 		base = be32_to_cpu(args->args[f->buf_idx1]);
1716 		if (f->size_idx1 != -1)
1717 			size = be32_to_cpu(args->args[f->size_idx1]);
1718 		else if (f->fixed_size)
1719 			size = f->fixed_size;
1720 		else
1721 			size = 1;
1722 
1723 		end = base + size - 1;
1724 
1725 		/*
1726 		 * Special case for ibm,platform-dump - NULL buffer
1727 		 * address is used to indicate end of dump processing
1728 		 */
1729 		if (is_platform_dump && base == 0)
1730 			return false;
1731 
1732 		if (!in_rmo_buf(base, end))
1733 			goto err;
1734 	}
1735 
1736 	if (f->buf_idx2 != -1) {
1737 		base = be32_to_cpu(args->args[f->buf_idx2]);
1738 		if (f->size_idx2 != -1)
1739 			size = be32_to_cpu(args->args[f->size_idx2]);
1740 		else if (f->fixed_size)
1741 			size = f->fixed_size;
1742 		else
1743 			size = 1;
1744 		end = base + size - 1;
1745 
1746 		/*
1747 		 * Special case for ibm,configure-connector where the
1748 		 * address can be 0
1749 		 */
1750 		if (is_config_conn && base == 0)
1751 			return false;
1752 
1753 		if (!in_rmo_buf(base, end))
1754 			goto err;
1755 	}
1756 
1757 	return false;
1758 err:
1759 	pr_err_ratelimited("sys_rtas: RTAS call blocked - exploit attempt?\n");
1760 	pr_err_ratelimited("sys_rtas: token=0x%x, nargs=%d (called by %s)\n",
1761 			   token, nargs, current->comm);
1762 	return true;
1763 }
1764 
1765 /* We assume to be passed big endian arguments */
1766 SYSCALL_DEFINE1(rtas, struct rtas_args __user *, uargs)
1767 {
1768 	struct rtas_args args;
1769 	unsigned long flags;
1770 	char *buff_copy, *errbuf = NULL;
1771 	int nargs, nret, token;
1772 
1773 	if (!capable(CAP_SYS_ADMIN))
1774 		return -EPERM;
1775 
1776 	if (!rtas.entry)
1777 		return -EINVAL;
1778 
1779 	if (copy_from_user(&args, uargs, 3 * sizeof(u32)) != 0)
1780 		return -EFAULT;
1781 
1782 	nargs = be32_to_cpu(args.nargs);
1783 	nret  = be32_to_cpu(args.nret);
1784 	token = be32_to_cpu(args.token);
1785 
1786 	if (nargs >= ARRAY_SIZE(args.args)
1787 	    || nret > ARRAY_SIZE(args.args)
1788 	    || nargs + nret > ARRAY_SIZE(args.args))
1789 		return -EINVAL;
1790 
1791 	/* Copy in args. */
1792 	if (copy_from_user(args.args, uargs->args,
1793 			   nargs * sizeof(rtas_arg_t)) != 0)
1794 		return -EFAULT;
1795 
1796 	if (token == RTAS_UNKNOWN_SERVICE)
1797 		return -EINVAL;
1798 
1799 	args.rets = &args.args[nargs];
1800 	memset(args.rets, 0, nret * sizeof(rtas_arg_t));
1801 
1802 	if (block_rtas_call(token, nargs, &args))
1803 		return -EINVAL;
1804 
1805 	if (token_is_restricted_errinjct(token)) {
1806 		int err;
1807 
1808 		err = security_locked_down(LOCKDOWN_RTAS_ERROR_INJECTION);
1809 		if (err)
1810 			return err;
1811 	}
1812 
1813 	/* Need to handle ibm,suspend_me call specially */
1814 	if (token == rtas_function_token(RTAS_FN_IBM_SUSPEND_ME)) {
1815 
1816 		/*
1817 		 * rtas_ibm_suspend_me assumes the streamid handle is in cpu
1818 		 * endian, or at least the hcall within it requires it.
1819 		 */
1820 		int rc = 0;
1821 		u64 handle = ((u64)be32_to_cpu(args.args[0]) << 32)
1822 		              | be32_to_cpu(args.args[1]);
1823 		rc = rtas_syscall_dispatch_ibm_suspend_me(handle);
1824 		if (rc == -EAGAIN)
1825 			args.rets[0] = cpu_to_be32(RTAS_NOT_SUSPENDABLE);
1826 		else if (rc == -EIO)
1827 			args.rets[0] = cpu_to_be32(-1);
1828 		else if (rc)
1829 			return rc;
1830 		goto copy_return;
1831 	}
1832 
1833 	buff_copy = get_errorlog_buffer();
1834 
1835 	raw_spin_lock_irqsave(&rtas_lock, flags);
1836 
1837 	rtas_args = args;
1838 	do_enter_rtas(&rtas_args);
1839 	args = rtas_args;
1840 
1841 	/* A -1 return code indicates that the last command couldn't
1842 	   be completed due to a hardware error. */
1843 	if (be32_to_cpu(args.rets[0]) == -1)
1844 		errbuf = __fetch_rtas_last_error(buff_copy);
1845 
1846 	raw_spin_unlock_irqrestore(&rtas_lock, flags);
1847 
1848 	if (buff_copy) {
1849 		if (errbuf)
1850 			log_error(errbuf, ERR_TYPE_RTAS_LOG, 0);
1851 		kfree(buff_copy);
1852 	}
1853 
1854  copy_return:
1855 	/* Copy out args. */
1856 	if (copy_to_user(uargs->args + nargs,
1857 			 args.args + nargs,
1858 			 nret * sizeof(rtas_arg_t)) != 0)
1859 		return -EFAULT;
1860 
1861 	return 0;
1862 }
1863 
1864 static void __init rtas_function_table_init(void)
1865 {
1866 	struct property *prop;
1867 
1868 	for (size_t i = 0; i < ARRAY_SIZE(rtas_function_table); ++i) {
1869 		struct rtas_function *curr = &rtas_function_table[i];
1870 		struct rtas_function *prior;
1871 		int cmp;
1872 
1873 		curr->token = RTAS_UNKNOWN_SERVICE;
1874 
1875 		if (i == 0)
1876 			continue;
1877 		/*
1878 		 * Ensure table is sorted correctly for binary search
1879 		 * on function names.
1880 		 */
1881 		prior = &rtas_function_table[i - 1];
1882 
1883 		cmp = strcmp(prior->name, curr->name);
1884 		if (cmp < 0)
1885 			continue;
1886 
1887 		if (cmp == 0) {
1888 			pr_err("'%s' has duplicate function table entries\n",
1889 			       curr->name);
1890 		} else {
1891 			pr_err("function table unsorted: '%s' wrongly precedes '%s'\n",
1892 			       prior->name, curr->name);
1893 		}
1894 	}
1895 
1896 	for_each_property_of_node(rtas.dev, prop) {
1897 		struct rtas_function *func;
1898 
1899 		if (prop->length != sizeof(u32))
1900 			continue;
1901 
1902 		func = __rtas_name_to_function(prop->name);
1903 		if (!func)
1904 			continue;
1905 
1906 		func->token = be32_to_cpup((__be32 *)prop->value);
1907 
1908 		pr_debug("function %s has token %u\n", func->name, func->token);
1909 	}
1910 }
1911 
1912 /*
1913  * Call early during boot, before mem init, to retrieve the RTAS
1914  * information from the device-tree and allocate the RMO buffer for userland
1915  * accesses.
1916  */
1917 void __init rtas_initialize(void)
1918 {
1919 	unsigned long rtas_region = RTAS_INSTANTIATE_MAX;
1920 	u32 base, size, entry;
1921 	int no_base, no_size, no_entry;
1922 
1923 	/* Get RTAS dev node and fill up our "rtas" structure with infos
1924 	 * about it.
1925 	 */
1926 	rtas.dev = of_find_node_by_name(NULL, "rtas");
1927 	if (!rtas.dev)
1928 		return;
1929 
1930 	no_base = of_property_read_u32(rtas.dev, "linux,rtas-base", &base);
1931 	no_size = of_property_read_u32(rtas.dev, "rtas-size", &size);
1932 	if (no_base || no_size) {
1933 		of_node_put(rtas.dev);
1934 		rtas.dev = NULL;
1935 		return;
1936 	}
1937 
1938 	rtas.base = base;
1939 	rtas.size = size;
1940 	no_entry = of_property_read_u32(rtas.dev, "linux,rtas-entry", &entry);
1941 	rtas.entry = no_entry ? rtas.base : entry;
1942 
1943 	init_error_log_max();
1944 
1945 	/* Must be called before any function token lookups */
1946 	rtas_function_table_init();
1947 
1948 	/*
1949 	 * Discover this now to avoid a device tree lookup in the
1950 	 * panic path.
1951 	 */
1952 	ibm_extended_os_term = of_property_read_bool(rtas.dev, "ibm,extended-os-term");
1953 
1954 	/* If RTAS was found, allocate the RMO buffer for it and look for
1955 	 * the stop-self token if any
1956 	 */
1957 #ifdef CONFIG_PPC64
1958 	if (firmware_has_feature(FW_FEATURE_LPAR))
1959 		rtas_region = min(ppc64_rma_size, RTAS_INSTANTIATE_MAX);
1960 #endif
1961 	rtas_rmo_buf = memblock_phys_alloc_range(RTAS_USER_REGION_SIZE, PAGE_SIZE,
1962 						 0, rtas_region);
1963 	if (!rtas_rmo_buf)
1964 		panic("ERROR: RTAS: Failed to allocate %lx bytes below %pa\n",
1965 		      PAGE_SIZE, &rtas_region);
1966 
1967 	rtas_work_area_reserve_arena(rtas_region);
1968 }
1969 
1970 int __init early_init_dt_scan_rtas(unsigned long node,
1971 		const char *uname, int depth, void *data)
1972 {
1973 	const u32 *basep, *entryp, *sizep;
1974 
1975 	if (depth != 1 || strcmp(uname, "rtas") != 0)
1976 		return 0;
1977 
1978 	basep  = of_get_flat_dt_prop(node, "linux,rtas-base", NULL);
1979 	entryp = of_get_flat_dt_prop(node, "linux,rtas-entry", NULL);
1980 	sizep  = of_get_flat_dt_prop(node, "rtas-size", NULL);
1981 
1982 #ifdef CONFIG_PPC64
1983 	/* need this feature to decide the crashkernel offset */
1984 	if (of_get_flat_dt_prop(node, "ibm,hypertas-functions", NULL))
1985 		powerpc_firmware_features |= FW_FEATURE_LPAR;
1986 #endif
1987 
1988 	if (basep && entryp && sizep) {
1989 		rtas.base = *basep;
1990 		rtas.entry = *entryp;
1991 		rtas.size = *sizep;
1992 	}
1993 
1994 #ifdef CONFIG_UDBG_RTAS_CONSOLE
1995 	basep = of_get_flat_dt_prop(node, "put-term-char", NULL);
1996 	if (basep)
1997 		rtas_putchar_token = *basep;
1998 
1999 	basep = of_get_flat_dt_prop(node, "get-term-char", NULL);
2000 	if (basep)
2001 		rtas_getchar_token = *basep;
2002 
2003 	if (rtas_putchar_token != RTAS_UNKNOWN_SERVICE &&
2004 	    rtas_getchar_token != RTAS_UNKNOWN_SERVICE)
2005 		udbg_init_rtas_console();
2006 
2007 #endif
2008 
2009 	/* break now */
2010 	return 1;
2011 }
2012 
2013 static DEFINE_RAW_SPINLOCK(timebase_lock);
2014 static u64 timebase = 0;
2015 
2016 void rtas_give_timebase(void)
2017 {
2018 	unsigned long flags;
2019 
2020 	raw_spin_lock_irqsave(&timebase_lock, flags);
2021 	hard_irq_disable();
2022 	rtas_call(rtas_function_token(RTAS_FN_FREEZE_TIME_BASE), 0, 1, NULL);
2023 	timebase = get_tb();
2024 	raw_spin_unlock(&timebase_lock);
2025 
2026 	while (timebase)
2027 		barrier();
2028 	rtas_call(rtas_function_token(RTAS_FN_THAW_TIME_BASE), 0, 1, NULL);
2029 	local_irq_restore(flags);
2030 }
2031 
2032 void rtas_take_timebase(void)
2033 {
2034 	while (!timebase)
2035 		barrier();
2036 	raw_spin_lock(&timebase_lock);
2037 	set_tb(timebase >> 32, timebase & 0xffffffff);
2038 	timebase = 0;
2039 	raw_spin_unlock(&timebase_lock);
2040 }
2041