more harmless space-related matters
[bootcd.git] / initscripts / pl_hwinit
1 #!/usr/bin/python
2
3 # xxx could use a port to python3..
4
5 import sys
6 import pypci
7 import pypcimap
8 import os
9 import time
10
11 def now():
12     format = "%H:%M:%S(%Z)"
13     return time.strftime(format, time.localtime())
14
15 def verbose_message(single):
16     print now(), single
17
18 def modprobe(module, summary_file, args = ""):
19     ret = os.system("/sbin/modprobe {} {}".format(module, args))
20     if os.WEXITSTATUS(ret) == 0:
21         summary_file.write("{}\n".format(module))
22         return True
23     else:
24         return False
25
26 def main(argv):
27     if len(argv) == 0:
28         kernel = os.uname()[2]
29     else:
30         kernel = argv[0]
31
32     if os.path.exists(kernel):
33         path = kernel
34     else:
35         path = "/lib/modules/{}/modules.pcimap".format(kernel)
36
37     blacklisted_modules = []
38     blacklists = os.listdir("/etc/modprobe.d")
39     for blacklist in blacklists:
40         blf = "/etc/modprobe.d/{}".format(blacklist)
41         if os.path.exists(blf):
42             f = open(blf)
43             for i in f.readlines():
44                 if i.startswith("blacklist"):
45                     blacklisted_modules.append(i.split()[1])
46     # unify the list
47     blacklisted_modules = list(set(blacklisted_modules))
48
49     pcimap = pypcimap.PCIMap(path)
50     verbose_message("pl_hwinit: loading applicable modules")
51     devices = pypci.get_devices()
52     storage_devices = 0
53     network_devices = 0
54     missing = []
55     with open('/tmp/loadedmodules', 'w') as loadedmodules:
56         for slot in sorted(devices.keys()):
57             dev = devices[slot]
58             modules = pcimap.get(dev)
59             base = (dev[4] & 0xff0000) >> 16
60             if len(modules) == 0:
61                 if base == 0x01 or base == 0x02:
62                     # storage or network device, in that order
63                     missing.append((slot, dev))
64             else:
65                 if base == 0x01:
66                     storage_devices += 1
67                 elif base == 0x02:
68                     network_devices += 1
69
70                 # FIXME: This needs improved logic in the case of multiple matching modules
71                 for module in modules:
72                     if module not in blacklisted_modules:
73                         verbose_message("pl_hwinit: found and loading module {} (%s)" % (module, slot))
74                         modprobe(module, loadedmodules)
75
76         if network_devices == 0:
77             verbose_message("pl_hwinit: no supported network devices found!")
78             verbose_message("pl_hwinit: the following devices were found, but have no driver:")
79             lines = [ "{} x {}".format(slot, dev) for slot, dev in missing ]
80             for line in lines:
81                 verbose_message("pl_hwinit: missing " + line)
82
83         # XXX: could check for storage devices too, but older kernels have a lot of that built-in
84
85         # sd_mod won't get loaded automatically
86         verbose_message("pl_hwinit: loading sd_mod")
87         modprobe("sd_mod", loadedmodules)
88
89         # load usb_storage to support node conf files on flash disks
90         verbose_message("pl_hwinit: loading usb_storage")
91         modprobe("usb_storage", loadedmodules)
92
93         verbose_message("pl_hwinit: loading floppy device driver")
94         modprobe("floppy", loadedmodules, "floppy=0,allowed_drive_mask")
95
96     # always wait a bit between loading the usb drivers, and checking /sys/
97     # for usb devices (this isn't necessarily for waiting for mass storage files,
98     # that is done below)
99     verbose_message("pl_hwinit: waiting for usb system to initialize.")
100     time.sleep(10)
101
102     # sometimes, flash devices take a while to initialize. in fact, the kernel
103     # intentionally waits 5 seconds for a device to 'settle'. some take even longer
104     # to show up. if there are any mass storage devices on the system, try to
105     # delay until they come online, up to a max delay of 30s.
106
107     # the way this will be done is to look for files in /sys/devices that are named
108     # 'bInterfaceClass', these will be a list of the usb devices on the system, and
109     # their primary usb device interface class ids. The base directory these files
110     # exist in will be the full path to the /sys/device entry for that device.
111     # for each mass storage devices (they have an interface class value of 08),
112     # we wait for a new symbolic link named 'driver' to exist in that directory,
113     # indicating the kernel loaded a driver for that device.
114
115     # usb interface class id for mass storage
116     INTERFACE_CLASS_MASS_STORAGE = "08"
117
118     # how long to wait in seconds before continuing on if devices
119     # aren't available
120     MAX_USB_WAIT_TIME = 30
121
122     # low long in seconds to wait between checks
123     PER_CHECK_USB_WAIT_TIME = 5
124
125
126     # find out if the device identified by the /sys dir has a module
127     # loaded for it. check for a symlink in the dir named driver.
128     def does_device_dir_have_driver(device):
129         return os.path.exists(os.path.join(device, "driver"))
130
131     def filter_and_add(list, directory, files):
132         if ("bInterfaceClass" in files and
133             int(file(os.path.join(directory, "bInterfaceClass")).read(), 16) == INTERFACE_CLASS_MASS_STORAGE):
134             list.append(directory)
135
136     wait_dev_list = []
137     os.path.walk("/sys/devices", filter_and_add, wait_dev_list)
138
139     if len(wait_dev_list) > 0:
140         verbose_message("pl_hwinit: found USB mass storage device(s). Attempting to wait")
141         verbose_message("pl_hwinit: up to %d seconds for them to come online." % MAX_USB_WAIT_TIME)
142
143         total_wait_time = 0
144         success = False
145         while total_wait_time < MAX_USB_WAIT_TIME:
146             total_wait_time += PER_CHECK_USB_WAIT_TIME
147
148             verbose_message("pl_hwinit: waiting {} seconds.".format(PER_CHECK_USB_WAIT_TIME))
149             time.sleep(PER_CHECK_USB_WAIT_TIME)
150
151             all_devices_online = True
152             for device in wait_dev_list:
153                 if not does_device_dir_have_driver(device):
154                     all_devices_online = False
155
156             if all_devices_online:
157                 success = True
158                 verbose_message("pl_hwinit: looks like the devices are now online.")
159                 break
160             else:
161                 verbose_message("pl_hwinit: not all devices online yet, waiting...")
162
163         if success:
164             verbose_message("pl_hwinit: Succesfully waited for USB mass storage devices")
165             verbose_message("pl_hwinit: to come online.")
166         else:
167             verbose_message("pl_hwinit: One or more USB mass storage devices did not")
168             verbose_message("pl_hwinit: initialize in time. Continuing anyway.")
169
170 if __name__ == "__main__":
171     main(sys.argv[1:])