1from devlib.module import Module
2
3
4class HotplugModule(Module):
5
6    name = 'hotplug'
7    base_path = '/sys/devices/system/cpu'
8
9    @classmethod
10    def probe(cls, target):  # pylint: disable=arguments-differ
11        # If a system has just 1 CPU, it makes not sense to hotplug it.
12        # If a system has more than 1 CPU, CPU0 could be configured to be not
13        # hotpluggable. Thus, check for hotplug support by looking at CPU1
14        path = cls._cpu_path(target, 1)
15        return target.file_exists(path) and target.is_rooted
16
17    @classmethod
18    def _cpu_path(cls, target, cpu):
19        if isinstance(cpu, int):
20            cpu = 'cpu{}'.format(cpu)
21        return target.path.join(cls.base_path, cpu, 'online')
22
23    def online_all(self):
24        self.online(*range(self.target.number_of_cpus))
25
26    def online(self, *args):
27        for cpu in args:
28            self.hotplug(cpu, online=True)
29
30    def offline(self, *args):
31        for cpu in args:
32            self.hotplug(cpu, online=False)
33
34    def hotplug(self, cpu, online):
35        path = self._cpu_path(self.target, cpu)
36        if not self.target.file_exists(path):
37            return
38        value = 1 if online else 0
39        self.target.write_value(path, value)
40
41