blob: 943c031eca25dfc58be105d07e379af0463d27a8 [file] [log] [blame]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08006import os
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08007import re
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08008import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08009import time
10import xmlrpclib
11
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080012from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080013from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080014from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080015
16
17class FAFTSequence(ServoTest):
18 """
19 The base class of Fully Automated Firmware Test Sequence.
20
21 Many firmware tests require several reboot cycles and verify the resulted
22 system states. To do that, an Autotest test case should detailly handle
23 every action on each step. It makes the test case hard to read and many
24 duplicated code. The base class FAFTSequence is to solve this problem.
25
26 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
27 There are four functions in the FAFT_STEP dict:
28 state_checker: a function to check the current is valid or not,
29 returning True if valid, otherwise, False to break the whole
30 test sequence.
31 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080032 reboot_action: a function to do reboot, default: sync_and_hw_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080033 firmware_action: a function to describe the action ran after reboot.
34
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080035 And configurations:
36 install_deps_after_boot: if True, install the Autotest dependency after
37 boot; otherwise, do nothing. It is for the cases of recovery mode
38 test. The test boots a USB/SD image instead of an internal image.
39 The previous installed Autotest dependency on the internal image
40 is lost. So need to install it again.
41
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080042 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080043 userspace_action and firmware_action. Its reboot_action is a hardware
44 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080045 self.register_faft_template(FAFT_STEP).
46
47 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
48 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
49 fall back to default.
50
51 In the run_once(), it should register and run FAFT_SEQUENCE like:
52 def run_once(self):
53 self.register_faft_sequence(FAFT_SEQUENCE)
54 self.run_faft_sequnce()
55
56 Note that in the last step, we only run state_checker. The
57 userspace_action, reboot_action, and firmware_action are not executed.
58
59 Attributes:
60 _faft_template: The default FAFT_STEP of each step. The actions would
61 be over-written if the registered FAFT_SEQUENCE is valid.
62 _faft_sequence: The registered FAFT_SEQUENCE.
63 """
64 version = 1
65
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080066
67 # Mapping of partition number of kernel and rootfs.
68 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
69 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
70 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
71 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
72
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080073 # Delay timing
74 FIRMWARE_SCREEN_DELAY = 10
75 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080076 USB_PLUG_DELAY = 10
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080077 SYNC_DELAY = 5
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080078
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +080079 CHROMEOS_MAGIC = "CHROMEOS"
80 CORRUPTED_MAGIC = "CORRUPTD"
81
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +080082 # Recovery reason codes, copied from:
83 # vboot_reference/firmware/lib/vboot_nvstorage.h
84 # vboot_reference/firmware/lib/vboot_struct.h
85 RECOVERY_REASON = {
86 # Recovery not requested
87 'NOT_REQUESTED': '0', # 0x00
88 # Recovery requested from legacy utility
89 'LEGACY': '1', # 0x01
90 # User manually requested recovery via recovery button
91 'RO_MANUAL': '2', # 0x02
92 # RW firmware failed signature check
93 'RO_INVALID_RW': '3', # 0x03
94 # S3 resume failed
95 'RO_S3_RESUME': '4', # 0x04
96 # TPM error in read-only firmware
97 'RO_TPM_ERROR': '5', # 0x05
98 # Shared data error in read-only firmware
99 'RO_SHARED_DATA': '6', # 0x06
100 # Test error from S3Resume()
101 'RO_TEST_S3': '7', # 0x07
102 # Test error from LoadFirmwareSetup()
103 'RO_TEST_LFS': '8', # 0x08
104 # Test error from LoadFirmware()
105 'RO_TEST_LF': '9', # 0x09
106 # RW firmware failed signature check
107 'RW_NOT_DONE': '16', # 0x10
108 'RW_DEV_MISMATCH': '17', # 0x11
109 'RW_REC_MISMATCH': '18', # 0x12
110 'RW_VERIFY_KEYBLOCK': '19', # 0x13
111 'RW_KEY_ROLLBACK': '20', # 0x14
112 'RW_DATA_KEY_PARSE': '21', # 0x15
113 'RW_VERIFY_PREAMBLE': '22', # 0x16
114 'RW_FW_ROLLBACK': '23', # 0x17
115 'RW_HEADER_VALID': '24', # 0x18
116 'RW_GET_FW_BODY': '25', # 0x19
117 'RW_HASH_WRONG_SIZE': '26', # 0x1A
118 'RW_VERIFY_BODY': '27', # 0x1B
119 'RW_VALID': '28', # 0x1C
120 # Read-only normal path requested by firmware preamble, but
121 # unsupported by firmware.
122 'RW_NO_RO_NORMAL': '29', # 0x1D
123 # Firmware boot failure outside of verified boot
124 'RO_FIRMWARE': '32', # 0x20
125 # Recovery mode TPM initialization requires a system reboot.
126 # The system was already in recovery mode for some other reason
127 # when this happened.
128 'RO_TPM_REBOOT': '33', # 0x21
129 # Unspecified/unknown error in read-only firmware
130 'RO_UNSPECIFIED': '63', # 0x3F
131 # User manually requested recovery by pressing a key at developer
132 # warning screen.
133 'RW_DEV_SCREEN': '65', # 0x41
134 # No OS kernel detected
135 'RW_NO_OS': '66', # 0x42
136 # OS kernel failed signature check
137 'RW_INVALID_OS': '67', # 0x43
138 # TPM error in rewritable firmware
139 'RW_TPM_ERROR': '68', # 0x44
140 # RW firmware in dev mode, but dev switch is off.
141 'RW_DEV_MISMATCH': '69', # 0x45
142 # Shared data error in rewritable firmware
143 'RW_SHARED_DATA': '70', # 0x46
144 # Test error from LoadKernel()
145 'RW_TEST_LK': '71', # 0x47
146 # No bootable disk found
147 'RW_NO_DISK': '72', # 0x48
148 # Unspecified/unknown error in rewritable firmware
149 'RW_UNSPECIFIED': '127', # 0x7F
150 # DM-verity error
151 'KE_DM_VERITY': '129', # 0x81
152 # Unspecified/unknown error in kernel
153 'KE_UNSPECIFIED': '191', # 0xBF
154 # Recovery mode test from user-mode
155 'US_TEST': '193', # 0xC1
156 # Unspecified/unknown error in user-mode
157 'US_UNSPECIFIED': '255', # 0xFF
158 }
159
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800160 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800161 _faft_sequence = ()
162
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800163 _customized_ctrl_d_key_command = None
164 _customized_enter_key_command = None
165
166
167 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
168 # Parse arguments from command line
169 args = {}
170 for arg in cmdline_args:
171 match = re.search("^(\w+)=(.+)", arg)
172 if match:
173 args[match.group(1)] = match.group(2)
174
175 # Keep the customized Ctrl-D and Enter key commands.
176 if 'ctrl_d_cmd' in args:
177 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
178 logging.info('Customized Ctrl-D key command: %s' %
179 self._customized_ctrl_d_key_command)
180 if 'enter_cmd' in args:
181 self._customized_enter_key_command = args['enter_cmd']
182 logging.info('Customized Enter key command: %s' %
183 self._customized_enter_key_command)
184
185 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
186 use_faft)
187
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800188
189 def setup(self):
190 """Autotest setup function."""
191 super(FAFTSequence, self).setup()
192 if not self._remote_infos['faft']['used']:
193 raise error.TestError('The use_faft flag should be enabled.')
194 self.register_faft_template({
195 'state_checker': (None),
196 'userspace_action': (None),
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800197 'reboot_action': (self.sync_and_hw_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800198 'firmware_action': (None)
199 })
200
201
202 def cleanup(self):
203 """Autotest cleanup function."""
204 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800205 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800206 super(FAFTSequence, self).cleanup()
207
208
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800209 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800210 """Assert an USB disk plugged-in on servo and a test image inside.
211
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800212 Args:
213 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
214 If None, it is detected automatically.
215
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800216 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800217 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800218 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800219 if usb_dev:
220 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
221 else:
222 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
223 usb_dev = self.servo.probe_host_usb_dev()
224 if not usb_dev:
225 raise error.TestError(
226 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800227
228 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800229 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800230 code = utils.system(
231 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
232 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800233 utils.system('sudo umount %s' % tmp_dir)
234 os.removedirs(tmp_dir)
235 if code != 0:
236 raise error.TestError(
237 'The image in the USB disk should be a test image.')
238
239
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800240 def _parse_crossystem_output(self, lines):
241 """Parse the crossystem output into a dict.
242
243 Args:
244 lines: The list of crossystem output strings.
245
246 Returns:
247 A dict which contains the crossystem keys/values.
248
249 Raises:
250 error.TestError: If wrong format in crossystem output.
251
252 >>> seq = FAFTSequence()
253 >>> seq._parse_crossystem_output([ \
254 "arch = x86 # Platform architecture", \
255 "cros_debug = 1 # OS should allow debug", \
256 ])
257 {'cros_debug': '1', 'arch': 'x86'}
258 >>> seq._parse_crossystem_output([ \
259 "arch=x86", \
260 ])
261 Traceback (most recent call last):
262 ...
263 TestError: Failed to parse crossystem output: arch=x86
264 >>> seq._parse_crossystem_output([ \
265 "arch = x86 # Platform architecture", \
266 "arch = arm # Platform architecture", \
267 ])
268 Traceback (most recent call last):
269 ...
270 TestError: Duplicated crossystem key: arch
271 """
272 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
273 parsed_list = {}
274 for line in lines:
275 matched = re.match(pattern, line.strip())
276 if not matched:
277 raise error.TestError("Failed to parse crossystem output: %s"
278 % line)
279 (name, value) = (matched.group(1), matched.group(2))
280 if name in parsed_list:
281 raise error.TestError("Duplicated crossystem key: %s" % name)
282 parsed_list[name] = value
283 return parsed_list
284
285
286 def crossystem_checker(self, expected_dict):
287 """Check the crossystem values matched.
288
289 Given an expect_dict which describes the expected crossystem values,
290 this function check the current crossystem values are matched or not.
291
292 Args:
293 expected_dict: A dict which contains the expected values.
294
295 Returns:
296 True if the crossystem value matched; otherwise, False.
297 """
298 lines = self.faft_client.run_shell_command_get_output('crossystem')
299 got_dict = self._parse_crossystem_output(lines)
300 for key in expected_dict:
301 if key not in got_dict:
302 logging.info('Expected key "%s" not in crossystem result' % key)
303 return False
304 if isinstance(expected_dict[key], str):
305 if got_dict[key] != expected_dict[key]:
306 logging.info("Expected '%s' value '%s' but got '%s'" %
307 (key, expected_dict[key], got_dict[key]))
308 return False
309 elif isinstance(expected_dict[key], tuple):
310 # Expected value is a tuple of possible actual values.
311 if got_dict[key] not in expected_dict[key]:
312 logging.info("Expected '%s' values %s but got '%s'" %
313 (key, str(expected_dict[key]), got_dict[key]))
314 return False
315 else:
316 logging.info("The expected_dict is neither a str nor a dict.")
317 return False
318 return True
319
320
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800321 def root_part_checker(self, expected_part):
322 """Check the partition number of the root device matched.
323
324 Args:
325 expected_part: A string containing the number of the expected root
326 partition.
327
328 Returns:
329 True if the currect root partition number matched; otherwise, False.
330 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800331 part = self.faft_client.get_root_part()[-1]
332 if self.ROOTFS_MAP[expected_part] != part:
333 logging.info("Expected root part %s but got %s" %
334 (self.ROOTFS_MAP[expected_part], part))
335 return False
336 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800337
338
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800339 def _join_part(self, dev, part):
340 """Return a concatenated string of device and partition number.
341
342 Args:
343 dev: A string of device, e.g.'/dev/sda'.
344 part: A string of partition number, e.g.'3'.
345
346 Returns:
347 A concatenated string of device and partition number, e.g.'/dev/sda3'.
348
349 >>> seq = FAFTSequence()
350 >>> seq._join_part('/dev/sda', '3')
351 '/dev/sda3'
352 >>> seq._join_part('/dev/mmcblk0', '2')
353 '/dev/mmcblk0p2'
354 """
355 if 'mmcblk' in dev:
356 return dev + 'p' + part
357 else:
358 return dev + part
359
360
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800361 def copy_kernel_and_rootfs(self, from_part, to_part):
362 """Copy kernel and rootfs from from_part to to_part.
363
364 Args:
365 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800366 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800367 """
368 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800369 logging.info('Copying kernel from %s to %s. Please wait...' %
370 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800371 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800372 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
373 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
374 logging.info('Copying rootfs from %s to %s. Please wait...' %
375 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800376 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800377 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
378 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800379
380
381 def ensure_kernel_boot(self, part):
382 """Ensure the request kernel boot.
383
384 If not, it duplicates the current kernel to the requested kernel
385 and sets the requested higher priority to ensure it boot.
386
387 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800388 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800389 """
390 if not self.root_part_checker(part):
391 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
392 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800393 self.run_faft_step({
394 'userspace_action': (self.reset_and_prioritize_kernel, part),
395 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800396
397
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800398 def send_ctrl_d_to_dut(self):
399 """Send Ctrl-D key to DUT."""
400 if self._customized_ctrl_d_key_command:
401 logging.info('running the customized Ctrl-D key command')
402 os.system(self._customized_ctrl_d_key_command)
403 else:
404 self.servo.ctrl_d()
405
406
407 def send_enter_to_dut(self):
408 """Send Enter key to DUT."""
409 if self._customized_enter_key_command:
410 logging.info('running the customized Enter key command')
411 os.system(self._customized_enter_key_command)
412 else:
413 self.servo.enter_key()
414
415
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800416 def wait_fw_screen_and_ctrl_d(self):
417 """Wait for firmware warning screen and press Ctrl-D."""
418 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800419 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800420
421
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800422 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
423 """Wait for firmware warning screen and trigger recovery boot."""
424 time.sleep(self.FIRMWARE_SCREEN_DELAY)
425 self.send_enter_to_dut()
426
427 # For Alex/ZGB, there is a dev warning screen in text mode.
428 # Skip it by pressing Ctrl-D.
429 if need_dev_transition:
430 time.sleep(self.TEXT_SCREEN_DELAY)
431 self.send_ctrl_d_to_dut()
432
433
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800434 def wait_fw_screen_and_plug_usb(self):
435 """Wait for firmware warning screen and then unplug and plug the USB."""
436 time.sleep(self.FIRMWARE_SCREEN_DELAY)
437 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
438 time.sleep(self.USB_PLUG_DELAY)
439 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
440
441
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800442 def wait_fw_screen_and_press_power(self):
443 """Wait for firmware warning screen and press power button."""
444 time.sleep(self.FIRMWARE_SCREEN_DELAY)
445 self.servo.power_normal_press()
446
447
448 def wait_fw_screen_and_close_lid(self):
449 """Wait for firmware warning screen and close lid."""
450 time.sleep(self.FIRMWARE_SCREEN_DELAY)
451 self.servo.lid_close()
452
453
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800454 def setup_tried_fwb(self, tried_fwb):
455 """Setup for fw B tried state.
456
457 It makes sure the system in the requested fw B tried state. If not, it
458 tries to do so.
459
460 Args:
461 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
462 """
463 if tried_fwb:
464 if not self.crossystem_checker({'tried_fwb': '1'}):
465 logging.info(
466 'Firmware is not booted with tried_fwb. Reboot into it.')
467 self.run_faft_step({
468 'userspace_action': self.faft_client.set_try_fw_b,
469 })
470 else:
471 if not self.crossystem_checker({'tried_fwb': '0'}):
472 logging.info(
473 'Firmware is booted with tried_fwb. Reboot to clear.')
474 self.run_faft_step({})
475
476
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800477 def enable_dev_mode_and_fw(self):
478 """Enable developer mode and use developer firmware."""
479 self.servo.enable_development_mode()
480 self.faft_client.run_shell_command(
481 'chromeos-firmwareupdate --mode todev && reboot')
482
483
484 def enable_normal_mode_and_fw(self):
485 """Enable normal mode and use normal firmware."""
486 self.servo.disable_development_mode()
487 self.faft_client.run_shell_command(
488 'chromeos-firmwareupdate --mode tonormal && reboot')
489
490
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800491 def setup_dev_mode(self, dev_mode):
492 """Setup for development mode.
493
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800494 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800495 tries to do so.
496
497 Args:
498 dev_mode: True if requested in dev mode; False if normal mode.
499 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800500 # Change the default firmware_action for dev mode passing the fw screen.
501 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800502 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
503 else None),
504 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800505 if dev_mode:
506 if not self.crossystem_checker({'devsw_cur': '1'}):
507 logging.info('Dev switch is not on. Now switch it on.')
508 self.servo.enable_development_mode()
509 if not self.crossystem_checker({'devsw_boot': '1',
510 'mainfw_type': 'developer'}):
511 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800512 self.run_faft_step({
513 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800514 'chromeos-firmwareupdate --mode todev && reboot'),
515 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800516 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800517 else:
518 if not self.crossystem_checker({'devsw_cur': '0'}):
519 logging.info('Dev switch is not off. Now switch it off.')
520 self.servo.disable_development_mode()
521 if not self.crossystem_checker({'devsw_boot': '0',
522 'mainfw_type': 'normal'}):
523 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800524 self.run_faft_step({
525 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800526 'chromeos-firmwareupdate --mode tonormal && reboot'),
527 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800528 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800529
530
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800531 def setup_kernel(self, part):
532 """Setup for kernel test.
533
534 It makes sure both kernel A and B bootable and the current boot is
535 the requested kernel part.
536
537 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800538 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800539 """
540 self.ensure_kernel_boot(part)
541 self.copy_kernel_and_rootfs(from_part=part,
542 to_part=self.OTHER_KERNEL_MAP[part])
543 self.reset_and_prioritize_kernel(part)
544
545
546 def reset_and_prioritize_kernel(self, part):
547 """Make the requested partition highest priority.
548
549 This function also reset kerenl A and B to bootable.
550
551 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800552 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800553 """
554 root_dev = self.faft_client.get_root_dev()
555 # Reset kernel A and B to bootable.
556 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
557 (self.KERNEL_MAP['a'], root_dev))
558 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
559 (self.KERNEL_MAP['b'], root_dev))
560 # Set kernel part highest priority.
561 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
562 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800563 # Safer to sync and wait until the cgpt status written to the disk.
564 self.faft_client.run_shell_command('sync')
565 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800566
567
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800568 def sync_and_hw_reboot(self):
569 """Request the client sync and do a warm reboot.
570
571 This is the default reboot action on FAFT.
572 """
573 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800574 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800575 self.servo.warm_reset()
576
577
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800578 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
579 """Modify the kernel header magic in USB stick.
580
581 The kernel header magic is the first 8-byte of kernel partition.
582 We modify it to make it fail on kernel verification check.
583
584 Args:
585 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
586 from_magic: A string of magic which we change it from.
587 to_magic: A string of magic which we change it to.
588
589 Raises:
590 error.TestError: if failed to change magic.
591 """
592 assert len(from_magic) == 8
593 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800594 # USB image only contains one kernel.
595 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800596 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
597 current_magic = utils.system_output(read_cmd)
598 if current_magic == to_magic:
599 logging.info("The kernel magic is already %s." % current_magic)
600 return
601 if current_magic != from_magic:
602 raise error.TestError("Invalid kernel image on USB: wrong magic.")
603
604 logging.info('Modify the kernel magic in USB, from %s to %s.' %
605 (from_magic, to_magic))
606 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
607 " 2>/dev/null" % (to_magic, kernel_part))
608 utils.system(write_cmd)
609
610 if utils.system_output(read_cmd) != to_magic:
611 raise error.TestError("Failed to write new magic.")
612
613
614 def corrupt_usb_kernel(self, usb_dev):
615 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
616
617 Args:
618 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
619 """
620 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
621 self.CORRUPTED_MAGIC)
622
623
624 def restore_usb_kernel(self, usb_dev):
625 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
626
627 Args:
628 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
629 """
630 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
631 self.CHROMEOS_MAGIC)
632
633
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800634 def _call_action(self, action_tuple):
635 """Call the action function with/without arguments.
636
637 Args:
638 action_tuple: A function, or a tuple which consisted of a function
639 and its arguments (if any).
640
641 Returns:
642 The result value of the action function.
643 """
644 if isinstance(action_tuple, tuple):
645 action = action_tuple[0]
646 args = action_tuple[1:]
647 if callable(action):
648 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800649 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800650 return action(*args)
651 else:
652 logging.info('action is not callable!')
653 else:
654 action = action_tuple
655 if action is not None:
656 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800657 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800658 return action()
659 else:
660 logging.info('action is not callable!')
661
662 return None
663
664
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800665 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
666 post_power_action=None):
667 """Run shutdown_action(), which makes DUT shutdown, and power it on.
668
669 Args:
670 shutdown_action: a function which makes DUT shutdown, like pressing
671 power key.
672 pre_power_action: a function which is called before next power on.
673 post_power_action: a function which is called after next power on.
674
675 Raises:
676 error.TestFail: if the shutdown_action() failed to turn DUT off.
677 """
678 self._call_action(shutdown_action)
679 logging.info('Wait to ensure DUT shut down...')
680 try:
681 self.wait_for_client()
682 raise error.TestFail(
683 'Should shut the device down after calling %s.' %
684 str(shutdown_action))
685 except AssertionError:
686 logging.info(
687 'DUT is surely shutdown. We are going to power it on again...')
688
689 if pre_power_action:
690 self._call_action(pre_power_action)
691 self.servo.power_normal_press()
692 if post_power_action:
693 self._call_action(post_power_action)
694
695
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800696 def register_faft_template(self, template):
697 """Register FAFT template, the default FAFT_STEP of each step.
698
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800699 Any missing field falls back to the original faft_template.
700
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800701 Args:
702 template: A FAFT_STEP dict.
703 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800704 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800705
706
707 def register_faft_sequence(self, sequence):
708 """Register FAFT sequence.
709
710 Args:
711 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
712 """
713 self._faft_sequence = sequence
714
715
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800716 def run_faft_step(self, step, no_reboot=False):
717 """Run a single FAFT step.
718
719 Any missing field falls back to faft_template. An empty step means
720 running the default faft_template.
721
722 Args:
723 step: A FAFT_STEP dict.
724 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800725
726 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800727 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800728 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800729 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800730 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
731 'firmware_action', 'install_deps_after_boot')
732
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800733 test = {}
734 test.update(self._faft_template)
735 test.update(step)
736
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800737 for key in test:
738 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800739 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800740
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800741 if test['state_checker']:
742 if not self._call_action(test['state_checker']):
743 raise error.TestFail('State checker failed!')
744
745 self._call_action(test['userspace_action'])
746
747 # Don't run reboot_action and firmware_action if no_reboot is True.
748 if not no_reboot:
749 self._call_action(test['reboot_action'])
750 self.wait_for_client_offline()
751 self._call_action(test['firmware_action'])
752
753 if 'install_deps_after_boot' in test:
754 self.wait_for_client(
755 install_deps=test['install_deps_after_boot'])
756 else:
757 self.wait_for_client()
758
759
760 def run_faft_sequence(self):
761 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800762 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800763 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800764 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800765 logging.info('======== Running FAFT sequence step %d ========' %
766 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800767 # Don't reboot in the last step.
768 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800769 index += 1