blob: f7eddeb59392cee8b9fd12a04545781d9c7c3bf8 [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 Tam40fd9472012-01-09 17:11:02 +08008import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08009import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080010import time
11import xmlrpclib
12
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080013from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080014from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080015from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080016from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080017
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080018dirname = os.path.dirname(sys.modules[__name__].__file__)
19autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
20cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080021
22class FAFTSequence(ServoTest):
23 """
24 The base class of Fully Automated Firmware Test Sequence.
25
26 Many firmware tests require several reboot cycles and verify the resulted
27 system states. To do that, an Autotest test case should detailly handle
28 every action on each step. It makes the test case hard to read and many
29 duplicated code. The base class FAFTSequence is to solve this problem.
30
31 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
32 There are four functions in the FAFT_STEP dict:
33 state_checker: a function to check the current is valid or not,
34 returning True if valid, otherwise, False to break the whole
35 test sequence.
36 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080037 reboot_action: a function to do reboot, default: sync_and_hw_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080038 firmware_action: a function to describe the action ran after reboot.
39
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080040 And configurations:
41 install_deps_after_boot: if True, install the Autotest dependency after
42 boot; otherwise, do nothing. It is for the cases of recovery mode
43 test. The test boots a USB/SD image instead of an internal image.
44 The previous installed Autotest dependency on the internal image
45 is lost. So need to install it again.
46
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080047 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080048 userspace_action and firmware_action. Its reboot_action is a hardware
49 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080050 self.register_faft_template(FAFT_STEP).
51
52 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
53 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
54 fall back to default.
55
56 In the run_once(), it should register and run FAFT_SEQUENCE like:
57 def run_once(self):
58 self.register_faft_sequence(FAFT_SEQUENCE)
59 self.run_faft_sequnce()
60
61 Note that in the last step, we only run state_checker. The
62 userspace_action, reboot_action, and firmware_action are not executed.
63
64 Attributes:
65 _faft_template: The default FAFT_STEP of each step. The actions would
66 be over-written if the registered FAFT_SEQUENCE is valid.
67 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080068 _customized_ctrl_d_key_command: The customized Ctrl-D key command
69 instead of sending key via servo board.
70 _customized_enter_key_command: The customized Enter key command instead
71 of sending key via servo board.
72 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080073 _firmware_update: Boolean. True if firmware update needed after
74 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080075 """
76 version = 1
77
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080078
79 # Mapping of partition number of kernel and rootfs.
80 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
81 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
82 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
83 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
84
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080085 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam211ccba2012-01-13 15:35:53 +080086 FIRMWARE_SCREEN_DELAY = 2
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080087 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080088 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080089 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080090 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080091 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080092 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080093 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080094 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080095 # Delay for waiting client to return before EC reboot
96 EC_REBOOT_DELAY = 1
97 # Delay between EC reboot and pressing power button
98 POWER_BTN_DELAY = 0.5
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080099
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800100 CHROMEOS_MAGIC = "CHROMEOS"
101 CORRUPTED_MAGIC = "CORRUPTD"
102
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800103 # Recovery reason codes, copied from:
104 # vboot_reference/firmware/lib/vboot_nvstorage.h
105 # vboot_reference/firmware/lib/vboot_struct.h
106 RECOVERY_REASON = {
107 # Recovery not requested
108 'NOT_REQUESTED': '0', # 0x00
109 # Recovery requested from legacy utility
110 'LEGACY': '1', # 0x01
111 # User manually requested recovery via recovery button
112 'RO_MANUAL': '2', # 0x02
113 # RW firmware failed signature check
114 'RO_INVALID_RW': '3', # 0x03
115 # S3 resume failed
116 'RO_S3_RESUME': '4', # 0x04
117 # TPM error in read-only firmware
118 'RO_TPM_ERROR': '5', # 0x05
119 # Shared data error in read-only firmware
120 'RO_SHARED_DATA': '6', # 0x06
121 # Test error from S3Resume()
122 'RO_TEST_S3': '7', # 0x07
123 # Test error from LoadFirmwareSetup()
124 'RO_TEST_LFS': '8', # 0x08
125 # Test error from LoadFirmware()
126 'RO_TEST_LF': '9', # 0x09
127 # RW firmware failed signature check
128 'RW_NOT_DONE': '16', # 0x10
129 'RW_DEV_MISMATCH': '17', # 0x11
130 'RW_REC_MISMATCH': '18', # 0x12
131 'RW_VERIFY_KEYBLOCK': '19', # 0x13
132 'RW_KEY_ROLLBACK': '20', # 0x14
133 'RW_DATA_KEY_PARSE': '21', # 0x15
134 'RW_VERIFY_PREAMBLE': '22', # 0x16
135 'RW_FW_ROLLBACK': '23', # 0x17
136 'RW_HEADER_VALID': '24', # 0x18
137 'RW_GET_FW_BODY': '25', # 0x19
138 'RW_HASH_WRONG_SIZE': '26', # 0x1A
139 'RW_VERIFY_BODY': '27', # 0x1B
140 'RW_VALID': '28', # 0x1C
141 # Read-only normal path requested by firmware preamble, but
142 # unsupported by firmware.
143 'RW_NO_RO_NORMAL': '29', # 0x1D
144 # Firmware boot failure outside of verified boot
145 'RO_FIRMWARE': '32', # 0x20
146 # Recovery mode TPM initialization requires a system reboot.
147 # The system was already in recovery mode for some other reason
148 # when this happened.
149 'RO_TPM_REBOOT': '33', # 0x21
150 # Unspecified/unknown error in read-only firmware
151 'RO_UNSPECIFIED': '63', # 0x3F
152 # User manually requested recovery by pressing a key at developer
153 # warning screen.
154 'RW_DEV_SCREEN': '65', # 0x41
155 # No OS kernel detected
156 'RW_NO_OS': '66', # 0x42
157 # OS kernel failed signature check
158 'RW_INVALID_OS': '67', # 0x43
159 # TPM error in rewritable firmware
160 'RW_TPM_ERROR': '68', # 0x44
161 # RW firmware in dev mode, but dev switch is off.
162 'RW_DEV_MISMATCH': '69', # 0x45
163 # Shared data error in rewritable firmware
164 'RW_SHARED_DATA': '70', # 0x46
165 # Test error from LoadKernel()
166 'RW_TEST_LK': '71', # 0x47
167 # No bootable disk found
168 'RW_NO_DISK': '72', # 0x48
169 # Unspecified/unknown error in rewritable firmware
170 'RW_UNSPECIFIED': '127', # 0x7F
171 # DM-verity error
172 'KE_DM_VERITY': '129', # 0x81
173 # Unspecified/unknown error in kernel
174 'KE_UNSPECIFIED': '191', # 0xBF
175 # Recovery mode test from user-mode
176 'US_TEST': '193', # 0xC1
177 # Unspecified/unknown error in user-mode
178 'US_UNSPECIFIED': '255', # 0xFF
179 }
180
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800181 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800182 _faft_sequence = ()
183
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800184 _customized_ctrl_d_key_command = None
185 _customized_enter_key_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800186 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800187 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800188
189
190 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
191 # Parse arguments from command line
192 args = {}
193 for arg in cmdline_args:
194 match = re.search("^(\w+)=(.+)", arg)
195 if match:
196 args[match.group(1)] = match.group(2)
197
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800198 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800199 if 'ctrl_d_cmd' in args:
200 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
201 logging.info('Customized Ctrl-D key command: %s' %
202 self._customized_ctrl_d_key_command)
203 if 'enter_cmd' in args:
204 self._customized_enter_key_command = args['enter_cmd']
205 logging.info('Customized Enter key command: %s' %
206 self._customized_enter_key_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800207 if 'image' in args:
208 self._install_image_path = args['image']
209 logging.info('Install Chrome OS test image path: %s' %
210 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800211 if 'firmware_update' in args and args['firmware_update'].lower() \
212 not in ('0', 'false', 'no'):
213 if self._install_image_path:
214 self._firmware_update = True
215 logging.info('Also update firmware after installing.')
216 else:
217 logging.warning('Firmware update will not not performed '
218 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800219
220 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
221 use_faft)
222
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800223
224 def setup(self):
225 """Autotest setup function."""
226 super(FAFTSequence, self).setup()
227 if not self._remote_infos['faft']['used']:
228 raise error.TestError('The use_faft flag should be enabled.')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800229
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800230 self.register_faft_template({
231 'state_checker': (None),
232 'userspace_action': (None),
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800233 'reboot_action': (self.sync_and_hw_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800234 'firmware_action': (None)
235 })
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800236 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800237 self.install_test_image(self._install_image_path,
238 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800239
240
241 def cleanup(self):
242 """Autotest cleanup function."""
243 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800244 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800245 super(FAFTSequence, self).cleanup()
246
247
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800248 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800249 """Assert an USB disk plugged-in on servo and a test image inside.
250
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800251 Args:
252 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
253 If None, it is detected automatically.
254
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800255 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800256 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800257 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800258 if usb_dev:
259 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
260 else:
261 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
262 usb_dev = self.servo.probe_host_usb_dev()
263 if not usb_dev:
264 raise error.TestError(
265 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800266
267 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800268 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800269 code = utils.system(
270 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
271 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800272 utils.system('sudo umount %s' % tmp_dir)
273 os.removedirs(tmp_dir)
274 if code != 0:
275 raise error.TestError(
276 'The image in the USB disk should be a test image.')
277
278
Simran Basi741b5d42012-05-18 11:27:15 -0700279 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800280 """Install the test image specied by the path onto the USB and DUT disk.
281
282 The method first copies the image to USB disk and reboots into it via
283 recovery mode. Then runs 'chromeos-install' to install it to DUT disk.
284
285 Args:
286 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800287 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800288 """
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800289 install_cmd = 'chromeos-install --yes'
290 if firmware_update:
291 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800292 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
293 image_path)
294 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800295
296 # Reuse the install_recovery_image method by using a test image.
297 # Don't wait for completion but run chromeos-install to install it.
Simran Basi741b5d42012-05-18 11:27:15 -0700298 self.servo.install_recovery_image(image_path)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800299 self.wait_for_client(install_deps=True)
300 self.run_faft_step({
301 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800302 install_cmd)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800303 })
304
305
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800306 def _parse_crossystem_output(self, lines):
307 """Parse the crossystem output into a dict.
308
309 Args:
310 lines: The list of crossystem output strings.
311
312 Returns:
313 A dict which contains the crossystem keys/values.
314
315 Raises:
316 error.TestError: If wrong format in crossystem output.
317
318 >>> seq = FAFTSequence()
319 >>> seq._parse_crossystem_output([ \
320 "arch = x86 # Platform architecture", \
321 "cros_debug = 1 # OS should allow debug", \
322 ])
323 {'cros_debug': '1', 'arch': 'x86'}
324 >>> seq._parse_crossystem_output([ \
325 "arch=x86", \
326 ])
327 Traceback (most recent call last):
328 ...
329 TestError: Failed to parse crossystem output: arch=x86
330 >>> seq._parse_crossystem_output([ \
331 "arch = x86 # Platform architecture", \
332 "arch = arm # Platform architecture", \
333 ])
334 Traceback (most recent call last):
335 ...
336 TestError: Duplicated crossystem key: arch
337 """
338 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
339 parsed_list = {}
340 for line in lines:
341 matched = re.match(pattern, line.strip())
342 if not matched:
343 raise error.TestError("Failed to parse crossystem output: %s"
344 % line)
345 (name, value) = (matched.group(1), matched.group(2))
346 if name in parsed_list:
347 raise error.TestError("Duplicated crossystem key: %s" % name)
348 parsed_list[name] = value
349 return parsed_list
350
351
352 def crossystem_checker(self, expected_dict):
353 """Check the crossystem values matched.
354
355 Given an expect_dict which describes the expected crossystem values,
356 this function check the current crossystem values are matched or not.
357
358 Args:
359 expected_dict: A dict which contains the expected values.
360
361 Returns:
362 True if the crossystem value matched; otherwise, False.
363 """
364 lines = self.faft_client.run_shell_command_get_output('crossystem')
365 got_dict = self._parse_crossystem_output(lines)
366 for key in expected_dict:
367 if key not in got_dict:
368 logging.info('Expected key "%s" not in crossystem result' % key)
369 return False
370 if isinstance(expected_dict[key], str):
371 if got_dict[key] != expected_dict[key]:
372 logging.info("Expected '%s' value '%s' but got '%s'" %
373 (key, expected_dict[key], got_dict[key]))
374 return False
375 elif isinstance(expected_dict[key], tuple):
376 # Expected value is a tuple of possible actual values.
377 if got_dict[key] not in expected_dict[key]:
378 logging.info("Expected '%s' values %s but got '%s'" %
379 (key, str(expected_dict[key]), got_dict[key]))
380 return False
381 else:
382 logging.info("The expected_dict is neither a str nor a dict.")
383 return False
384 return True
385
386
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800387 def root_part_checker(self, expected_part):
388 """Check the partition number of the root device matched.
389
390 Args:
391 expected_part: A string containing the number of the expected root
392 partition.
393
394 Returns:
395 True if the currect root partition number matched; otherwise, False.
396 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800397 part = self.faft_client.get_root_part()[-1]
398 if self.ROOTFS_MAP[expected_part] != part:
399 logging.info("Expected root part %s but got %s" %
400 (self.ROOTFS_MAP[expected_part], part))
401 return False
402 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800403
404
Vic Yang59cac9c2012-05-21 15:28:42 +0800405 def ec_act_copy_checker(self, expected_copy):
406 """Check the EC running firmware copy matches.
407
408 Args:
409 expected_copy: A string containing 'RO', 'A', or 'B' indicating
410 the expected copy of EC running firmware.
411
412 Returns:
413 True if the current EC running copy matches; otherwise, False.
414 """
415 lines = self.faft_client.run_shell_command_get_output('ectool version')
416 pattern = re.compile("Firmware copy: (.*)")
417 for line in lines:
418 matched = pattern.match(line)
419 if matched and matched.group(1) == expected_copy:
420 return True
421 return False
422
423
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800424 def check_root_part_on_non_recovery(self, part):
425 """Check the partition number of root device and on normal/dev boot.
426
427 Returns:
428 True if the root device matched and on normal/dev boot;
429 otherwise, False.
430 """
431 return self.root_part_checker(part) and \
432 self.crossystem_checker({
433 'mainfw_type': ('normal', 'developer'),
434 'recoverysw_boot': '0',
435 })
436
437
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800438 def _join_part(self, dev, part):
439 """Return a concatenated string of device and partition number.
440
441 Args:
442 dev: A string of device, e.g.'/dev/sda'.
443 part: A string of partition number, e.g.'3'.
444
445 Returns:
446 A concatenated string of device and partition number, e.g.'/dev/sda3'.
447
448 >>> seq = FAFTSequence()
449 >>> seq._join_part('/dev/sda', '3')
450 '/dev/sda3'
451 >>> seq._join_part('/dev/mmcblk0', '2')
452 '/dev/mmcblk0p2'
453 """
454 if 'mmcblk' in dev:
455 return dev + 'p' + part
456 else:
457 return dev + part
458
459
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800460 def copy_kernel_and_rootfs(self, from_part, to_part):
461 """Copy kernel and rootfs from from_part to to_part.
462
463 Args:
464 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800465 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800466 """
467 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800468 logging.info('Copying kernel from %s to %s. Please wait...' %
469 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800470 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800471 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
472 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
473 logging.info('Copying rootfs from %s to %s. Please wait...' %
474 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800475 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800476 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
477 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800478
479
480 def ensure_kernel_boot(self, part):
481 """Ensure the request kernel boot.
482
483 If not, it duplicates the current kernel to the requested kernel
484 and sets the requested higher priority to ensure it boot.
485
486 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800487 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800488 """
489 if not self.root_part_checker(part):
490 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
491 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800492 self.run_faft_step({
493 'userspace_action': (self.reset_and_prioritize_kernel, part),
494 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800495
496
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800497 def send_ctrl_d_to_dut(self):
498 """Send Ctrl-D key to DUT."""
499 if self._customized_ctrl_d_key_command:
500 logging.info('running the customized Ctrl-D key command')
501 os.system(self._customized_ctrl_d_key_command)
502 else:
503 self.servo.ctrl_d()
504
505
506 def send_enter_to_dut(self):
507 """Send Enter key to DUT."""
508 if self._customized_enter_key_command:
509 logging.info('running the customized Enter key command')
510 os.system(self._customized_enter_key_command)
511 else:
512 self.servo.enter_key()
513
514
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800515 def wait_fw_screen_and_ctrl_d(self):
516 """Wait for firmware warning screen and press Ctrl-D."""
517 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800518 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800519
520
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800521 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
522 """Wait for firmware warning screen and trigger recovery boot."""
523 time.sleep(self.FIRMWARE_SCREEN_DELAY)
524 self.send_enter_to_dut()
525
526 # For Alex/ZGB, there is a dev warning screen in text mode.
527 # Skip it by pressing Ctrl-D.
528 if need_dev_transition:
529 time.sleep(self.TEXT_SCREEN_DELAY)
530 self.send_ctrl_d_to_dut()
531
532
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800533 def wait_fw_screen_and_plug_usb(self):
534 """Wait for firmware warning screen and then unplug and plug the USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800535 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800536 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
537 time.sleep(self.USB_PLUG_DELAY)
538 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
539
540
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800541 def wait_fw_screen_and_press_power(self):
542 """Wait for firmware warning screen and press power button."""
543 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800544 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800545
546
547 def wait_fw_screen_and_close_lid(self):
548 """Wait for firmware warning screen and close lid."""
549 time.sleep(self.FIRMWARE_SCREEN_DELAY)
550 self.servo.lid_close()
551
552
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800553 def setup_tried_fwb(self, tried_fwb):
554 """Setup for fw B tried state.
555
556 It makes sure the system in the requested fw B tried state. If not, it
557 tries to do so.
558
559 Args:
560 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
561 """
562 if tried_fwb:
563 if not self.crossystem_checker({'tried_fwb': '1'}):
564 logging.info(
565 'Firmware is not booted with tried_fwb. Reboot into it.')
566 self.run_faft_step({
567 'userspace_action': self.faft_client.set_try_fw_b,
568 })
569 else:
570 if not self.crossystem_checker({'tried_fwb': '0'}):
571 logging.info(
572 'Firmware is booted with tried_fwb. Reboot to clear.')
573 self.run_faft_step({})
574
575
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800576 def enable_dev_mode_and_fw(self):
577 """Enable developer mode and use developer firmware."""
578 self.servo.enable_development_mode()
579 self.faft_client.run_shell_command(
580 'chromeos-firmwareupdate --mode todev && reboot')
581
582
583 def enable_normal_mode_and_fw(self):
584 """Enable normal mode and use normal firmware."""
585 self.servo.disable_development_mode()
586 self.faft_client.run_shell_command(
587 'chromeos-firmwareupdate --mode tonormal && reboot')
588
589
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800590 def setup_dev_mode(self, dev_mode):
591 """Setup for development mode.
592
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800593 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800594 tries to do so.
595
596 Args:
597 dev_mode: True if requested in dev mode; False if normal mode.
598 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800599 # Change the default firmware_action for dev mode passing the fw screen.
600 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800601 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
602 else None),
603 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800604 if dev_mode:
605 if not self.crossystem_checker({'devsw_cur': '1'}):
606 logging.info('Dev switch is not on. Now switch it on.')
607 self.servo.enable_development_mode()
608 if not self.crossystem_checker({'devsw_boot': '1',
609 'mainfw_type': 'developer'}):
610 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800611 self.run_faft_step({
612 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800613 'chromeos-firmwareupdate --mode todev && reboot'),
614 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800615 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800616 else:
617 if not self.crossystem_checker({'devsw_cur': '0'}):
618 logging.info('Dev switch is not off. Now switch it off.')
619 self.servo.disable_development_mode()
620 if not self.crossystem_checker({'devsw_boot': '0',
621 'mainfw_type': 'normal'}):
622 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800623 self.run_faft_step({
624 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800625 'chromeos-firmwareupdate --mode tonormal && reboot'),
626 'reboot_action': None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800627 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800628
629
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800630 def setup_kernel(self, part):
631 """Setup for kernel test.
632
633 It makes sure both kernel A and B bootable and the current boot is
634 the requested kernel part.
635
636 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800637 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800638 """
639 self.ensure_kernel_boot(part)
640 self.copy_kernel_and_rootfs(from_part=part,
641 to_part=self.OTHER_KERNEL_MAP[part])
642 self.reset_and_prioritize_kernel(part)
643
644
645 def reset_and_prioritize_kernel(self, part):
646 """Make the requested partition highest priority.
647
648 This function also reset kerenl A and B to bootable.
649
650 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800651 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800652 """
653 root_dev = self.faft_client.get_root_dev()
654 # Reset kernel A and B to bootable.
655 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
656 (self.KERNEL_MAP['a'], root_dev))
657 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
658 (self.KERNEL_MAP['b'], root_dev))
659 # Set kernel part highest priority.
660 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
661 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800662 # Safer to sync and wait until the cgpt status written to the disk.
663 self.faft_client.run_shell_command('sync')
664 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800665
666
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800667 def sync_and_hw_reboot(self):
668 """Request the client sync and do a warm reboot.
669
670 This is the default reboot action on FAFT.
671 """
672 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800673 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800674 self.servo.warm_reset()
675
676
Vic Yang59cac9c2012-05-21 15:28:42 +0800677 def sync_and_ec_reboot(self):
678 """Request the client sync and do a EC triggered reboot."""
679 self.faft_client.run_shell_command('sync')
680 time.sleep(self.SYNC_DELAY)
681 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
682 self.EC_REBOOT_DELAY)
683 time.sleep(self.EC_REBOOT_DELAY + self.POWER_BTN_DELAY)
684 self.servo.power_normal_press()
685
686
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800687 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
688 """Modify the kernel header magic in USB stick.
689
690 The kernel header magic is the first 8-byte of kernel partition.
691 We modify it to make it fail on kernel verification check.
692
693 Args:
694 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
695 from_magic: A string of magic which we change it from.
696 to_magic: A string of magic which we change it to.
697
698 Raises:
699 error.TestError: if failed to change magic.
700 """
701 assert len(from_magic) == 8
702 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800703 # USB image only contains one kernel.
704 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800705 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
706 current_magic = utils.system_output(read_cmd)
707 if current_magic == to_magic:
708 logging.info("The kernel magic is already %s." % current_magic)
709 return
710 if current_magic != from_magic:
711 raise error.TestError("Invalid kernel image on USB: wrong magic.")
712
713 logging.info('Modify the kernel magic in USB, from %s to %s.' %
714 (from_magic, to_magic))
715 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
716 " 2>/dev/null" % (to_magic, kernel_part))
717 utils.system(write_cmd)
718
719 if utils.system_output(read_cmd) != to_magic:
720 raise error.TestError("Failed to write new magic.")
721
722
723 def corrupt_usb_kernel(self, usb_dev):
724 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
725
726 Args:
727 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
728 """
729 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
730 self.CORRUPTED_MAGIC)
731
732
733 def restore_usb_kernel(self, usb_dev):
734 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
735
736 Args:
737 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
738 """
739 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
740 self.CHROMEOS_MAGIC)
741
742
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800743 def _call_action(self, action_tuple):
744 """Call the action function with/without arguments.
745
746 Args:
747 action_tuple: A function, or a tuple which consisted of a function
748 and its arguments (if any).
749
750 Returns:
751 The result value of the action function.
752 """
753 if isinstance(action_tuple, tuple):
754 action = action_tuple[0]
755 args = action_tuple[1:]
756 if callable(action):
757 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800758 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800759 return action(*args)
760 else:
761 logging.info('action is not callable!')
762 else:
763 action = action_tuple
764 if action is not None:
765 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800766 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800767 return action()
768 else:
769 logging.info('action is not callable!')
770
771 return None
772
773
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800774 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
775 post_power_action=None):
776 """Run shutdown_action(), which makes DUT shutdown, and power it on.
777
778 Args:
779 shutdown_action: a function which makes DUT shutdown, like pressing
780 power key.
781 pre_power_action: a function which is called before next power on.
782 post_power_action: a function which is called after next power on.
783
784 Raises:
785 error.TestFail: if the shutdown_action() failed to turn DUT off.
786 """
787 self._call_action(shutdown_action)
788 logging.info('Wait to ensure DUT shut down...')
789 try:
790 self.wait_for_client()
791 raise error.TestFail(
792 'Should shut the device down after calling %s.' %
793 str(shutdown_action))
794 except AssertionError:
795 logging.info(
796 'DUT is surely shutdown. We are going to power it on again...')
797
798 if pre_power_action:
799 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800800 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800801 if post_power_action:
802 self._call_action(post_power_action)
803
804
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800805 def register_faft_template(self, template):
806 """Register FAFT template, the default FAFT_STEP of each step.
807
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800808 Any missing field falls back to the original faft_template.
809
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800810 Args:
811 template: A FAFT_STEP dict.
812 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800813 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800814
815
816 def register_faft_sequence(self, sequence):
817 """Register FAFT sequence.
818
819 Args:
820 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
821 """
822 self._faft_sequence = sequence
823
824
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800825 def run_faft_step(self, step, no_reboot=False):
826 """Run a single FAFT step.
827
828 Any missing field falls back to faft_template. An empty step means
829 running the default faft_template.
830
831 Args:
832 step: A FAFT_STEP dict.
833 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800834
835 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800836 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800837 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800838 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800839 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
840 'firmware_action', 'install_deps_after_boot')
841
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800842 test = {}
843 test.update(self._faft_template)
844 test.update(step)
845
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800846 for key in test:
847 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800848 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +0800849
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800850 if test['state_checker']:
851 if not self._call_action(test['state_checker']):
852 raise error.TestFail('State checker failed!')
853
854 self._call_action(test['userspace_action'])
855
856 # Don't run reboot_action and firmware_action if no_reboot is True.
857 if not no_reboot:
858 self._call_action(test['reboot_action'])
859 self.wait_for_client_offline()
860 self._call_action(test['firmware_action'])
861
862 if 'install_deps_after_boot' in test:
863 self.wait_for_client(
864 install_deps=test['install_deps_after_boot'])
865 else:
866 self.wait_for_client()
867
868
869 def run_faft_sequence(self):
870 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800871 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800872 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800873 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800874 logging.info('======== Running FAFT sequence step %d ========' %
875 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +0800876 # Don't reboot in the last step.
877 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +0800878 index += 1