blob: 38270a35e4421bae19d624e38b6b58140b7f88a9 [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 Tam76c75072011-10-25 18:00:12 +0800209 def assert_test_image_in_usb_disk(self):
210 """Assert an USB disk plugged-in on servo and a test image inside.
211
212 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800213 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800214 """
215 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Jon Salzc88e5b62011-11-30 14:38:54 +0800216 usb_dev = self.servo.probe_host_usb_dev()
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800217 if not usb_dev:
218 raise error.TestError(
219 'An USB disk should be plugged in the servo board.')
220
221 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800222 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800223 code = utils.system(
224 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
225 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800226 utils.system('sudo umount %s' % tmp_dir)
227 os.removedirs(tmp_dir)
228 if code != 0:
229 raise error.TestError(
230 'The image in the USB disk should be a test image.')
231
232
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800233 def _parse_crossystem_output(self, lines):
234 """Parse the crossystem output into a dict.
235
236 Args:
237 lines: The list of crossystem output strings.
238
239 Returns:
240 A dict which contains the crossystem keys/values.
241
242 Raises:
243 error.TestError: If wrong format in crossystem output.
244
245 >>> seq = FAFTSequence()
246 >>> seq._parse_crossystem_output([ \
247 "arch = x86 # Platform architecture", \
248 "cros_debug = 1 # OS should allow debug", \
249 ])
250 {'cros_debug': '1', 'arch': 'x86'}
251 >>> seq._parse_crossystem_output([ \
252 "arch=x86", \
253 ])
254 Traceback (most recent call last):
255 ...
256 TestError: Failed to parse crossystem output: arch=x86
257 >>> seq._parse_crossystem_output([ \
258 "arch = x86 # Platform architecture", \
259 "arch = arm # Platform architecture", \
260 ])
261 Traceback (most recent call last):
262 ...
263 TestError: Duplicated crossystem key: arch
264 """
265 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
266 parsed_list = {}
267 for line in lines:
268 matched = re.match(pattern, line.strip())
269 if not matched:
270 raise error.TestError("Failed to parse crossystem output: %s"
271 % line)
272 (name, value) = (matched.group(1), matched.group(2))
273 if name in parsed_list:
274 raise error.TestError("Duplicated crossystem key: %s" % name)
275 parsed_list[name] = value
276 return parsed_list
277
278
279 def crossystem_checker(self, expected_dict):
280 """Check the crossystem values matched.
281
282 Given an expect_dict which describes the expected crossystem values,
283 this function check the current crossystem values are matched or not.
284
285 Args:
286 expected_dict: A dict which contains the expected values.
287
288 Returns:
289 True if the crossystem value matched; otherwise, False.
290 """
291 lines = self.faft_client.run_shell_command_get_output('crossystem')
292 got_dict = self._parse_crossystem_output(lines)
293 for key in expected_dict:
294 if key not in got_dict:
295 logging.info('Expected key "%s" not in crossystem result' % key)
296 return False
297 if isinstance(expected_dict[key], str):
298 if got_dict[key] != expected_dict[key]:
299 logging.info("Expected '%s' value '%s' but got '%s'" %
300 (key, expected_dict[key], got_dict[key]))
301 return False
302 elif isinstance(expected_dict[key], tuple):
303 # Expected value is a tuple of possible actual values.
304 if got_dict[key] not in expected_dict[key]:
305 logging.info("Expected '%s' values %s but got '%s'" %
306 (key, str(expected_dict[key]), got_dict[key]))
307 return False
308 else:
309 logging.info("The expected_dict is neither a str nor a dict.")
310 return False
311 return True
312
313
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800314 def root_part_checker(self, expected_part):
315 """Check the partition number of the root device matched.
316
317 Args:
318 expected_part: A string containing the number of the expected root
319 partition.
320
321 Returns:
322 True if the currect root partition number matched; otherwise, False.
323 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800324 part = self.faft_client.get_root_part()[-1]
325 if self.ROOTFS_MAP[expected_part] != part:
326 logging.info("Expected root part %s but got %s" %
327 (self.ROOTFS_MAP[expected_part], part))
328 return False
329 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800330
331
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800332 def _join_part(self, dev, part):
333 """Return a concatenated string of device and partition number.
334
335 Args:
336 dev: A string of device, e.g.'/dev/sda'.
337 part: A string of partition number, e.g.'3'.
338
339 Returns:
340 A concatenated string of device and partition number, e.g.'/dev/sda3'.
341
342 >>> seq = FAFTSequence()
343 >>> seq._join_part('/dev/sda', '3')
344 '/dev/sda3'
345 >>> seq._join_part('/dev/mmcblk0', '2')
346 '/dev/mmcblk0p2'
347 """
348 if 'mmcblk' in dev:
349 return dev + 'p' + part
350 else:
351 return dev + part
352
353
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800354 def copy_kernel_and_rootfs(self, from_part, to_part):
355 """Copy kernel and rootfs from from_part to to_part.
356
357 Args:
358 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800359 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800360 """
361 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800362 logging.info('Copying kernel from %s to %s. Please wait...' %
363 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800364 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800365 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
366 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
367 logging.info('Copying rootfs from %s to %s. Please wait...' %
368 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800369 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800370 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
371 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800372
373
374 def ensure_kernel_boot(self, part):
375 """Ensure the request kernel boot.
376
377 If not, it duplicates the current kernel to the requested kernel
378 and sets the requested higher priority to ensure it boot.
379
380 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800381 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800382 """
383 if not self.root_part_checker(part):
384 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
385 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800386 self.run_faft_step({
387 'userspace_action': (self.reset_and_prioritize_kernel, part),
388 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800389
390
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800391 def send_ctrl_d_to_dut(self):
392 """Send Ctrl-D key to DUT."""
393 if self._customized_ctrl_d_key_command:
394 logging.info('running the customized Ctrl-D key command')
395 os.system(self._customized_ctrl_d_key_command)
396 else:
397 self.servo.ctrl_d()
398
399
400 def send_enter_to_dut(self):
401 """Send Enter key to DUT."""
402 if self._customized_enter_key_command:
403 logging.info('running the customized Enter key command')
404 os.system(self._customized_enter_key_command)
405 else:
406 self.servo.enter_key()
407
408
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800409 def wait_fw_screen_and_ctrl_d(self):
410 """Wait for firmware warning screen and press Ctrl-D."""
411 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800412 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800413
414
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800415 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
416 """Wait for firmware warning screen and trigger recovery boot."""
417 time.sleep(self.FIRMWARE_SCREEN_DELAY)
418 self.send_enter_to_dut()
419
420 # For Alex/ZGB, there is a dev warning screen in text mode.
421 # Skip it by pressing Ctrl-D.
422 if need_dev_transition:
423 time.sleep(self.TEXT_SCREEN_DELAY)
424 self.send_ctrl_d_to_dut()
425
426
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800427 def wait_fw_screen_and_plug_usb(self):
428 """Wait for firmware warning screen and then unplug and plug the USB."""
429 time.sleep(self.FIRMWARE_SCREEN_DELAY)
430 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
431 time.sleep(self.USB_PLUG_DELAY)
432 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
433
434
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800435 def wait_fw_screen_and_press_power(self):
436 """Wait for firmware warning screen and press power button."""
437 time.sleep(self.FIRMWARE_SCREEN_DELAY)
438 self.servo.power_normal_press()
439
440
441 def wait_fw_screen_and_close_lid(self):
442 """Wait for firmware warning screen and close lid."""
443 time.sleep(self.FIRMWARE_SCREEN_DELAY)
444 self.servo.lid_close()
445
446
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800447 def setup_tried_fwb(self, tried_fwb):
448 """Setup for fw B tried state.
449
450 It makes sure the system in the requested fw B tried state. If not, it
451 tries to do so.
452
453 Args:
454 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
455 """
456 if tried_fwb:
457 if not self.crossystem_checker({'tried_fwb': '1'}):
458 logging.info(
459 'Firmware is not booted with tried_fwb. Reboot into it.')
460 self.run_faft_step({
461 'userspace_action': self.faft_client.set_try_fw_b,
462 })
463 else:
464 if not self.crossystem_checker({'tried_fwb': '0'}):
465 logging.info(
466 'Firmware is booted with tried_fwb. Reboot to clear.')
467 self.run_faft_step({})
468
469
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800470 def enable_dev_mode_and_fw(self):
471 """Enable developer mode and use developer firmware."""
472 self.servo.enable_development_mode()
473 self.faft_client.run_shell_command(
474 'chromeos-firmwareupdate --mode todev && reboot')
475
476
477 def enable_normal_mode_and_fw(self):
478 """Enable normal mode and use normal firmware."""
479 self.servo.disable_development_mode()
480 self.faft_client.run_shell_command(
481 'chromeos-firmwareupdate --mode tonormal && reboot')
482
483
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800484 def setup_dev_mode(self, dev_mode):
485 """Setup for development mode.
486
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800487 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800488 tries to do so.
489
490 Args:
491 dev_mode: True if requested in dev mode; False if normal mode.
492 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800493 # Change the default firmware_action for dev mode passing the fw screen.
494 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800495 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
496 else None),
497 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800498 if dev_mode:
499 if not self.crossystem_checker({'devsw_cur': '1'}):
500 logging.info('Dev switch is not on. Now switch it on.')
501 self.servo.enable_development_mode()
502 if not self.crossystem_checker({'devsw_boot': '1',
503 'mainfw_type': 'developer'}):
504 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800505 self.run_faft_step({
506 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800507 'chromeos-firmwareupdate --mode todev && reboot'),
508 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800509 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800510 else:
511 if not self.crossystem_checker({'devsw_cur': '0'}):
512 logging.info('Dev switch is not off. Now switch it off.')
513 self.servo.disable_development_mode()
514 if not self.crossystem_checker({'devsw_boot': '0',
515 'mainfw_type': 'normal'}):
516 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800517 self.run_faft_step({
518 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800519 'chromeos-firmwareupdate --mode tonormal && reboot'),
520 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800521 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800522
523
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800524 def setup_kernel(self, part):
525 """Setup for kernel test.
526
527 It makes sure both kernel A and B bootable and the current boot is
528 the requested kernel part.
529
530 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800531 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800532 """
533 self.ensure_kernel_boot(part)
534 self.copy_kernel_and_rootfs(from_part=part,
535 to_part=self.OTHER_KERNEL_MAP[part])
536 self.reset_and_prioritize_kernel(part)
537
538
539 def reset_and_prioritize_kernel(self, part):
540 """Make the requested partition highest priority.
541
542 This function also reset kerenl A and B to bootable.
543
544 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800545 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800546 """
547 root_dev = self.faft_client.get_root_dev()
548 # Reset kernel A and B to bootable.
549 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
550 (self.KERNEL_MAP['a'], root_dev))
551 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
552 (self.KERNEL_MAP['b'], root_dev))
553 # Set kernel part highest priority.
554 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
555 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800556 # Safer to sync and wait until the cgpt status written to the disk.
557 self.faft_client.run_shell_command('sync')
558 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800559
560
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800561 def sync_and_hw_reboot(self):
562 """Request the client sync and do a warm reboot.
563
564 This is the default reboot action on FAFT.
565 """
566 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800567 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800568 self.servo.warm_reset()
569
570
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800571 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
572 """Modify the kernel header magic in USB stick.
573
574 The kernel header magic is the first 8-byte of kernel partition.
575 We modify it to make it fail on kernel verification check.
576
577 Args:
578 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
579 from_magic: A string of magic which we change it from.
580 to_magic: A string of magic which we change it to.
581
582 Raises:
583 error.TestError: if failed to change magic.
584 """
585 assert len(from_magic) == 8
586 assert len(to_magic) == 8
587 kernel_part = self._join_part(usb_dev, '2')
588 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
589 current_magic = utils.system_output(read_cmd)
590 if current_magic == to_magic:
591 logging.info("The kernel magic is already %s." % current_magic)
592 return
593 if current_magic != from_magic:
594 raise error.TestError("Invalid kernel image on USB: wrong magic.")
595
596 logging.info('Modify the kernel magic in USB, from %s to %s.' %
597 (from_magic, to_magic))
598 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
599 " 2>/dev/null" % (to_magic, kernel_part))
600 utils.system(write_cmd)
601
602 if utils.system_output(read_cmd) != to_magic:
603 raise error.TestError("Failed to write new magic.")
604
605
606 def corrupt_usb_kernel(self, usb_dev):
607 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
608
609 Args:
610 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
611 """
612 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
613 self.CORRUPTED_MAGIC)
614
615
616 def restore_usb_kernel(self, usb_dev):
617 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
618
619 Args:
620 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
621 """
622 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
623 self.CHROMEOS_MAGIC)
624
625
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800626 def _call_action(self, action_tuple):
627 """Call the action function with/without arguments.
628
629 Args:
630 action_tuple: A function, or a tuple which consisted of a function
631 and its arguments (if any).
632
633 Returns:
634 The result value of the action function.
635 """
636 if isinstance(action_tuple, tuple):
637 action = action_tuple[0]
638 args = action_tuple[1:]
639 if callable(action):
640 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800641 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800642 return action(*args)
643 else:
644 logging.info('action is not callable!')
645 else:
646 action = action_tuple
647 if action is not None:
648 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800649 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800650 return action()
651 else:
652 logging.info('action is not callable!')
653
654 return None
655
656
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800657 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
658 post_power_action=None):
659 """Run shutdown_action(), which makes DUT shutdown, and power it on.
660
661 Args:
662 shutdown_action: a function which makes DUT shutdown, like pressing
663 power key.
664 pre_power_action: a function which is called before next power on.
665 post_power_action: a function which is called after next power on.
666
667 Raises:
668 error.TestFail: if the shutdown_action() failed to turn DUT off.
669 """
670 self._call_action(shutdown_action)
671 logging.info('Wait to ensure DUT shut down...')
672 try:
673 self.wait_for_client()
674 raise error.TestFail(
675 'Should shut the device down after calling %s.' %
676 str(shutdown_action))
677 except AssertionError:
678 logging.info(
679 'DUT is surely shutdown. We are going to power it on again...')
680
681 if pre_power_action:
682 self._call_action(pre_power_action)
683 self.servo.power_normal_press()
684 if post_power_action:
685 self._call_action(post_power_action)
686
687
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800688 def register_faft_template(self, template):
689 """Register FAFT template, the default FAFT_STEP of each step.
690
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800691 Any missing field falls back to the original faft_template.
692
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800693 Args:
694 template: A FAFT_STEP dict.
695 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800696 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800697
698
699 def register_faft_sequence(self, sequence):
700 """Register FAFT sequence.
701
702 Args:
703 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
704 """
705 self._faft_sequence = sequence
706
707
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800708 def run_faft_step(self, step, no_reboot=False):
709 """Run a single FAFT step.
710
711 Any missing field falls back to faft_template. An empty step means
712 running the default faft_template.
713
714 Args:
715 step: A FAFT_STEP dict.
716 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800717
718 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800719 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800720 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800721 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800722 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
723 'firmware_action', 'install_deps_after_boot')
724
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800725 test = {}
726 test.update(self._faft_template)
727 test.update(step)
728
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800729 for key in test:
730 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800731 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800732
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800733 if test['state_checker']:
734 if not self._call_action(test['state_checker']):
735 raise error.TestFail('State checker failed!')
736
737 self._call_action(test['userspace_action'])
738
739 # Don't run reboot_action and firmware_action if no_reboot is True.
740 if not no_reboot:
741 self._call_action(test['reboot_action'])
742 self.wait_for_client_offline()
743 self._call_action(test['firmware_action'])
744
745 if 'install_deps_after_boot' in test:
746 self.wait_for_client(
747 install_deps=test['install_deps_after_boot'])
748 else:
749 self.wait_for_client()
750
751
752 def run_faft_sequence(self):
753 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800754 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800755 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800756 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800757 logging.info('======== Running FAFT sequence step %d ========' %
758 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800759 # Don't reboot in the last step.
760 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800761 index += 1