GNU Linux-libre 4.19.295-gnu1
[releases.git] / drivers / firmware / psci_checker.c
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License version 2 as
4  * published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  * GNU General Public License for more details.
10  *
11  * Copyright (C) 2016 ARM Limited
12  */
13
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15
16 #include <linux/atomic.h>
17 #include <linux/completion.h>
18 #include <linux/cpu.h>
19 #include <linux/cpuidle.h>
20 #include <linux/cpu_pm.h>
21 #include <linux/kernel.h>
22 #include <linux/kthread.h>
23 #include <uapi/linux/sched/types.h>
24 #include <linux/module.h>
25 #include <linux/preempt.h>
26 #include <linux/psci.h>
27 #include <linux/slab.h>
28 #include <linux/tick.h>
29 #include <linux/topology.h>
30
31 #include <asm/cpuidle.h>
32
33 #include <uapi/linux/psci.h>
34
35 #define NUM_SUSPEND_CYCLE (10)
36
37 static unsigned int nb_available_cpus;
38 static int tos_resident_cpu = -1;
39
40 static atomic_t nb_active_threads;
41 static struct completion suspend_threads_started =
42         COMPLETION_INITIALIZER(suspend_threads_started);
43 static struct completion suspend_threads_done =
44         COMPLETION_INITIALIZER(suspend_threads_done);
45
46 /*
47  * We assume that PSCI operations are used if they are available. This is not
48  * necessarily true on arm64, since the decision is based on the
49  * "enable-method" property of each CPU in the DT, but given that there is no
50  * arch-specific way to check this, we assume that the DT is sensible.
51  */
52 static int psci_ops_check(void)
53 {
54         int migrate_type = -1;
55         int cpu;
56
57         if (!(psci_ops.cpu_off && psci_ops.cpu_on && psci_ops.cpu_suspend)) {
58                 pr_warn("Missing PSCI operations, aborting tests\n");
59                 return -EOPNOTSUPP;
60         }
61
62         if (psci_ops.migrate_info_type)
63                 migrate_type = psci_ops.migrate_info_type();
64
65         if (migrate_type == PSCI_0_2_TOS_UP_MIGRATE ||
66             migrate_type == PSCI_0_2_TOS_UP_NO_MIGRATE) {
67                 /* There is a UP Trusted OS, find on which core it resides. */
68                 for_each_online_cpu(cpu)
69                         if (psci_tos_resident_on(cpu)) {
70                                 tos_resident_cpu = cpu;
71                                 break;
72                         }
73                 if (tos_resident_cpu == -1)
74                         pr_warn("UP Trusted OS resides on no online CPU\n");
75         }
76
77         return 0;
78 }
79
80 /*
81  * offlined_cpus is a temporary array but passing it as an argument avoids
82  * multiple allocations.
83  */
84 static unsigned int down_and_up_cpus(const struct cpumask *cpus,
85                                      struct cpumask *offlined_cpus)
86 {
87         int cpu;
88         int err = 0;
89
90         cpumask_clear(offlined_cpus);
91
92         /* Try to power down all CPUs in the mask. */
93         for_each_cpu(cpu, cpus) {
94                 int ret = cpu_down(cpu);
95
96                 /*
97                  * cpu_down() checks the number of online CPUs before the TOS
98                  * resident CPU.
99                  */
100                 if (cpumask_weight(offlined_cpus) + 1 == nb_available_cpus) {
101                         if (ret != -EBUSY) {
102                                 pr_err("Unexpected return code %d while trying "
103                                        "to power down last online CPU %d\n",
104                                        ret, cpu);
105                                 ++err;
106                         }
107                 } else if (cpu == tos_resident_cpu) {
108                         if (ret != -EPERM) {
109                                 pr_err("Unexpected return code %d while trying "
110                                        "to power down TOS resident CPU %d\n",
111                                        ret, cpu);
112                                 ++err;
113                         }
114                 } else if (ret != 0) {
115                         pr_err("Error occurred (%d) while trying "
116                                "to power down CPU %d\n", ret, cpu);
117                         ++err;
118                 }
119
120                 if (ret == 0)
121                         cpumask_set_cpu(cpu, offlined_cpus);
122         }
123
124         /* Try to power up all the CPUs that have been offlined. */
125         for_each_cpu(cpu, offlined_cpus) {
126                 int ret = cpu_up(cpu);
127
128                 if (ret != 0) {
129                         pr_err("Error occurred (%d) while trying "
130                                "to power up CPU %d\n", ret, cpu);
131                         ++err;
132                 } else {
133                         cpumask_clear_cpu(cpu, offlined_cpus);
134                 }
135         }
136
137         /*
138          * Something went bad at some point and some CPUs could not be turned
139          * back on.
140          */
141         WARN_ON(!cpumask_empty(offlined_cpus) ||
142                 num_online_cpus() != nb_available_cpus);
143
144         return err;
145 }
146
147 static void free_cpu_groups(int num, cpumask_var_t **pcpu_groups)
148 {
149         int i;
150         cpumask_var_t *cpu_groups = *pcpu_groups;
151
152         for (i = 0; i < num; ++i)
153                 free_cpumask_var(cpu_groups[i]);
154         kfree(cpu_groups);
155 }
156
157 static int alloc_init_cpu_groups(cpumask_var_t **pcpu_groups)
158 {
159         int num_groups = 0;
160         cpumask_var_t tmp, *cpu_groups;
161
162         if (!alloc_cpumask_var(&tmp, GFP_KERNEL))
163                 return -ENOMEM;
164
165         cpu_groups = kcalloc(nb_available_cpus, sizeof(*cpu_groups),
166                              GFP_KERNEL);
167         if (!cpu_groups) {
168                 free_cpumask_var(tmp);
169                 return -ENOMEM;
170         }
171
172         cpumask_copy(tmp, cpu_online_mask);
173
174         while (!cpumask_empty(tmp)) {
175                 const struct cpumask *cpu_group =
176                         topology_core_cpumask(cpumask_any(tmp));
177
178                 if (!alloc_cpumask_var(&cpu_groups[num_groups], GFP_KERNEL)) {
179                         free_cpumask_var(tmp);
180                         free_cpu_groups(num_groups, &cpu_groups);
181                         return -ENOMEM;
182                 }
183                 cpumask_copy(cpu_groups[num_groups++], cpu_group);
184                 cpumask_andnot(tmp, tmp, cpu_group);
185         }
186
187         free_cpumask_var(tmp);
188         *pcpu_groups = cpu_groups;
189
190         return num_groups;
191 }
192
193 static int hotplug_tests(void)
194 {
195         int i, nb_cpu_group, err = -ENOMEM;
196         cpumask_var_t offlined_cpus, *cpu_groups;
197         char *page_buf;
198
199         if (!alloc_cpumask_var(&offlined_cpus, GFP_KERNEL))
200                 return err;
201
202         nb_cpu_group = alloc_init_cpu_groups(&cpu_groups);
203         if (nb_cpu_group < 0)
204                 goto out_free_cpus;
205         page_buf = (char *)__get_free_page(GFP_KERNEL);
206         if (!page_buf)
207                 goto out_free_cpu_groups;
208
209         err = 0;
210         /*
211          * Of course the last CPU cannot be powered down and cpu_down() should
212          * refuse doing that.
213          */
214         pr_info("Trying to turn off and on again all CPUs\n");
215         err += down_and_up_cpus(cpu_online_mask, offlined_cpus);
216
217         /*
218          * Take down CPUs by cpu group this time. When the last CPU is turned
219          * off, the cpu group itself should shut down.
220          */
221         for (i = 0; i < nb_cpu_group; ++i) {
222                 ssize_t len = cpumap_print_to_pagebuf(true, page_buf,
223                                                       cpu_groups[i]);
224                 /* Remove trailing newline. */
225                 page_buf[len - 1] = '\0';
226                 pr_info("Trying to turn off and on again group %d (CPUs %s)\n",
227                         i, page_buf);
228                 err += down_and_up_cpus(cpu_groups[i], offlined_cpus);
229         }
230
231         free_page((unsigned long)page_buf);
232 out_free_cpu_groups:
233         free_cpu_groups(nb_cpu_group, &cpu_groups);
234 out_free_cpus:
235         free_cpumask_var(offlined_cpus);
236         return err;
237 }
238
239 static void dummy_callback(struct timer_list *unused) {}
240
241 static int suspend_cpu(int index, bool broadcast)
242 {
243         int ret;
244
245         arch_cpu_idle_enter();
246
247         if (broadcast) {
248                 /*
249                  * The local timer will be shut down, we need to enter tick
250                  * broadcast.
251                  */
252                 ret = tick_broadcast_enter();
253                 if (ret) {
254                         /*
255                          * In the absence of hardware broadcast mechanism,
256                          * this CPU might be used to broadcast wakeups, which
257                          * may be why entering tick broadcast has failed.
258                          * There is little the kernel can do to work around
259                          * that, so enter WFI instead (idle state 0).
260                          */
261                         cpu_do_idle();
262                         ret = 0;
263                         goto out_arch_exit;
264                 }
265         }
266
267         /*
268          * Replicate the common ARM cpuidle enter function
269          * (arm_enter_idle_state).
270          */
271         ret = CPU_PM_CPU_IDLE_ENTER(arm_cpuidle_suspend, index);
272
273         if (broadcast)
274                 tick_broadcast_exit();
275
276 out_arch_exit:
277         arch_cpu_idle_exit();
278
279         return ret;
280 }
281
282 static int suspend_test_thread(void *arg)
283 {
284         int cpu = (long)arg;
285         int i, nb_suspend = 0, nb_shallow_sleep = 0, nb_err = 0;
286         struct sched_param sched_priority = { .sched_priority = MAX_RT_PRIO-1 };
287         struct cpuidle_device *dev;
288         struct cpuidle_driver *drv;
289         /* No need for an actual callback, we just want to wake up the CPU. */
290         struct timer_list wakeup_timer;
291
292         /* Wait for the main thread to give the start signal. */
293         wait_for_completion(&suspend_threads_started);
294
295         /* Set maximum priority to preempt all other threads on this CPU. */
296         if (sched_setscheduler_nocheck(current, SCHED_FIFO, &sched_priority))
297                 pr_warn("Failed to set suspend thread scheduler on CPU %d\n",
298                         cpu);
299
300         dev = this_cpu_read(cpuidle_devices);
301         drv = cpuidle_get_cpu_driver(dev);
302
303         pr_info("CPU %d entering suspend cycles, states 1 through %d\n",
304                 cpu, drv->state_count - 1);
305
306         timer_setup_on_stack(&wakeup_timer, dummy_callback, 0);
307         for (i = 0; i < NUM_SUSPEND_CYCLE; ++i) {
308                 int index;
309                 /*
310                  * Test all possible states, except 0 (which is usually WFI and
311                  * doesn't use PSCI).
312                  */
313                 for (index = 1; index < drv->state_count; ++index) {
314                         struct cpuidle_state *state = &drv->states[index];
315                         bool broadcast = state->flags & CPUIDLE_FLAG_TIMER_STOP;
316                         int ret;
317
318                         /*
319                          * Set the timer to wake this CPU up in some time (which
320                          * should be largely sufficient for entering suspend).
321                          * If the local tick is disabled when entering suspend,
322                          * suspend_cpu() takes care of switching to a broadcast
323                          * tick, so the timer will still wake us up.
324                          */
325                         mod_timer(&wakeup_timer, jiffies +
326                                   usecs_to_jiffies(state->target_residency));
327
328                         /* IRQs must be disabled during suspend operations. */
329                         local_irq_disable();
330
331                         ret = suspend_cpu(index, broadcast);
332
333                         /*
334                          * We have woken up. Re-enable IRQs to handle any
335                          * pending interrupt, do not wait until the end of the
336                          * loop.
337                          */
338                         local_irq_enable();
339
340                         if (ret == index) {
341                                 ++nb_suspend;
342                         } else if (ret >= 0) {
343                                 /* We did not enter the expected state. */
344                                 ++nb_shallow_sleep;
345                         } else {
346                                 pr_err("Failed to suspend CPU %d: error %d "
347                                        "(requested state %d, cycle %d)\n",
348                                        cpu, ret, index, i);
349                                 ++nb_err;
350                         }
351                 }
352         }
353
354         /*
355          * Disable the timer to make sure that the timer will not trigger
356          * later.
357          */
358         del_timer(&wakeup_timer);
359         destroy_timer_on_stack(&wakeup_timer);
360
361         if (atomic_dec_return_relaxed(&nb_active_threads) == 0)
362                 complete(&suspend_threads_done);
363
364         /* Give up on RT scheduling and wait for termination. */
365         sched_priority.sched_priority = 0;
366         if (sched_setscheduler_nocheck(current, SCHED_NORMAL, &sched_priority))
367                 pr_warn("Failed to set suspend thread scheduler on CPU %d\n",
368                         cpu);
369         for (;;) {
370                 /* Needs to be set first to avoid missing a wakeup. */
371                 set_current_state(TASK_INTERRUPTIBLE);
372                 if (kthread_should_park())
373                         break;
374                 schedule();
375         }
376
377         pr_info("CPU %d suspend test results: success %d, shallow states %d, errors %d\n",
378                 cpu, nb_suspend, nb_shallow_sleep, nb_err);
379
380         kthread_parkme();
381
382         return nb_err;
383 }
384
385 static int suspend_tests(void)
386 {
387         int i, cpu, err = 0;
388         struct task_struct **threads;
389         int nb_threads = 0;
390
391         threads = kmalloc_array(nb_available_cpus, sizeof(*threads),
392                                 GFP_KERNEL);
393         if (!threads)
394                 return -ENOMEM;
395
396         /*
397          * Stop cpuidle to prevent the idle tasks from entering a deep sleep
398          * mode, as it might interfere with the suspend threads on other CPUs.
399          * This does not prevent the suspend threads from using cpuidle (only
400          * the idle tasks check this status). Take the idle lock so that
401          * the cpuidle driver and device look-up can be carried out safely.
402          */
403         cpuidle_pause_and_lock();
404
405         for_each_online_cpu(cpu) {
406                 struct task_struct *thread;
407                 /* Check that cpuidle is available on that CPU. */
408                 struct cpuidle_device *dev = per_cpu(cpuidle_devices, cpu);
409                 struct cpuidle_driver *drv = cpuidle_get_cpu_driver(dev);
410
411                 if (!dev || !drv) {
412                         pr_warn("cpuidle not available on CPU %d, ignoring\n",
413                                 cpu);
414                         continue;
415                 }
416
417                 thread = kthread_create_on_cpu(suspend_test_thread,
418                                                (void *)(long)cpu, cpu,
419                                                "psci_suspend_test");
420                 if (IS_ERR(thread))
421                         pr_err("Failed to create kthread on CPU %d\n", cpu);
422                 else
423                         threads[nb_threads++] = thread;
424         }
425
426         if (nb_threads < 1) {
427                 err = -ENODEV;
428                 goto out;
429         }
430
431         atomic_set(&nb_active_threads, nb_threads);
432
433         /*
434          * Wake up the suspend threads. To avoid the main thread being preempted
435          * before all the threads have been unparked, the suspend threads will
436          * wait for the completion of suspend_threads_started.
437          */
438         for (i = 0; i < nb_threads; ++i)
439                 wake_up_process(threads[i]);
440         complete_all(&suspend_threads_started);
441
442         wait_for_completion(&suspend_threads_done);
443
444
445         /* Stop and destroy all threads, get return status. */
446         for (i = 0; i < nb_threads; ++i) {
447                 err += kthread_park(threads[i]);
448                 err += kthread_stop(threads[i]);
449         }
450  out:
451         cpuidle_resume_and_unlock();
452         kfree(threads);
453         return err;
454 }
455
456 static int __init psci_checker(void)
457 {
458         int ret;
459
460         /*
461          * Since we're in an initcall, we assume that all the CPUs that all
462          * CPUs that can be onlined have been onlined.
463          *
464          * The tests assume that hotplug is enabled but nobody else is using it,
465          * otherwise the results will be unpredictable. However, since there
466          * is no userspace yet in initcalls, that should be fine, as long as
467          * no torture test is running at the same time (see Kconfig).
468          */
469         nb_available_cpus = num_online_cpus();
470
471         /* Check PSCI operations are set up and working. */
472         ret = psci_ops_check();
473         if (ret)
474                 return ret;
475
476         pr_info("PSCI checker started using %u CPUs\n", nb_available_cpus);
477
478         pr_info("Starting hotplug tests\n");
479         ret = hotplug_tests();
480         if (ret == 0)
481                 pr_info("Hotplug tests passed OK\n");
482         else if (ret > 0)
483                 pr_err("%d error(s) encountered in hotplug tests\n", ret);
484         else {
485                 pr_err("Out of memory\n");
486                 return ret;
487         }
488
489         pr_info("Starting suspend tests (%d cycles per state)\n",
490                 NUM_SUSPEND_CYCLE);
491         ret = suspend_tests();
492         if (ret == 0)
493                 pr_info("Suspend tests passed OK\n");
494         else if (ret > 0)
495                 pr_err("%d error(s) encountered in suspend tests\n", ret);
496         else {
497                 switch (ret) {
498                 case -ENOMEM:
499                         pr_err("Out of memory\n");
500                         break;
501                 case -ENODEV:
502                         pr_warn("Could not start suspend tests on any CPU\n");
503                         break;
504                 }
505         }
506
507         pr_info("PSCI checker completed\n");
508         return ret < 0 ? ret : 0;
509 }
510 late_initcall(psci_checker);