blob: 1045d971c2088a3ba82f000e6470a6d7cdc489e5 [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
Vic Yangb4e3e742012-06-02 13:17:38 +08005import fdpexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08006import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08007import os
Vic Yangb4e3e742012-06-02 13:17:38 +08008import pexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08009import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080010import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080011import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012import time
13import xmlrpclib
14
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080015from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080016from autotest_lib.client.common_lib import error
Vic Yangebd6de62012-06-26 14:25:57 +080017from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080018from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080019from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080020
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080021dirname = os.path.dirname(sys.modules[__name__].__file__)
22autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
23cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080024
25class FAFTSequence(ServoTest):
26 """
27 The base class of Fully Automated Firmware Test Sequence.
28
29 Many firmware tests require several reboot cycles and verify the resulted
30 system states. To do that, an Autotest test case should detailly handle
31 every action on each step. It makes the test case hard to read and many
32 duplicated code. The base class FAFTSequence is to solve this problem.
33
34 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
35 There are four functions in the FAFT_STEP dict:
36 state_checker: a function to check the current is valid or not,
37 returning True if valid, otherwise, False to break the whole
38 test sequence.
39 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080040 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080041 firmware_action: a function to describe the action ran after reboot.
42
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080043 And configurations:
44 install_deps_after_boot: if True, install the Autotest dependency after
45 boot; otherwise, do nothing. It is for the cases of recovery mode
46 test. The test boots a USB/SD image instead of an internal image.
47 The previous installed Autotest dependency on the internal image
48 is lost. So need to install it again.
49
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080050 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080051 userspace_action and firmware_action. Its reboot_action is a hardware
52 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080053 self.register_faft_template(FAFT_STEP).
54
55 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
56 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
57 fall back to default.
58
59 In the run_once(), it should register and run FAFT_SEQUENCE like:
60 def run_once(self):
61 self.register_faft_sequence(FAFT_SEQUENCE)
62 self.run_faft_sequnce()
63
64 Note that in the last step, we only run state_checker. The
65 userspace_action, reboot_action, and firmware_action are not executed.
66
67 Attributes:
68 _faft_template: The default FAFT_STEP of each step. The actions would
69 be over-written if the registered FAFT_SEQUENCE is valid.
70 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080071 _customized_ctrl_d_key_command: The customized Ctrl-D key command
72 instead of sending key via servo board.
73 _customized_enter_key_command: The customized Enter key command instead
74 of sending key via servo board.
75 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080076 _firmware_update: Boolean. True if firmware update needed after
77 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080078 """
79 version = 1
80
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080081
82 # Mapping of partition number of kernel and rootfs.
83 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
84 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
85 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
86 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
87
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080088 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam211ccba2012-01-13 15:35:53 +080089 FIRMWARE_SCREEN_DELAY = 2
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080090 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080091 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080092 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080093 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080094 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080095 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080096 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080097 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080098 # Delay for waiting client to return before EC reboot
99 EC_REBOOT_DELAY = 1
100 # Delay between EC reboot and pressing power button
101 POWER_BTN_DELAY = 0.5
Vic Yange7553162012-06-20 16:20:47 +0800102 # Delay between sending keystroke to firmware
103 FIRMWARE_KEY_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800104 # Delay of EC software sync hash calculating time
105 SOFTWARE_SYNC_DELAY = 6
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800106
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800107 # The developer screen timeouts fit our spec.
108 DEV_SCREEN_TIMEOUT = 30
109
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800110 CHROMEOS_MAGIC = "CHROMEOS"
111 CORRUPTED_MAGIC = "CORRUPTD"
112
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800113 # Recovery reason codes, copied from:
114 # vboot_reference/firmware/lib/vboot_nvstorage.h
115 # vboot_reference/firmware/lib/vboot_struct.h
116 RECOVERY_REASON = {
117 # Recovery not requested
118 'NOT_REQUESTED': '0', # 0x00
119 # Recovery requested from legacy utility
120 'LEGACY': '1', # 0x01
121 # User manually requested recovery via recovery button
122 'RO_MANUAL': '2', # 0x02
123 # RW firmware failed signature check
124 'RO_INVALID_RW': '3', # 0x03
125 # S3 resume failed
126 'RO_S3_RESUME': '4', # 0x04
127 # TPM error in read-only firmware
128 'RO_TPM_ERROR': '5', # 0x05
129 # Shared data error in read-only firmware
130 'RO_SHARED_DATA': '6', # 0x06
131 # Test error from S3Resume()
132 'RO_TEST_S3': '7', # 0x07
133 # Test error from LoadFirmwareSetup()
134 'RO_TEST_LFS': '8', # 0x08
135 # Test error from LoadFirmware()
136 'RO_TEST_LF': '9', # 0x09
137 # RW firmware failed signature check
138 'RW_NOT_DONE': '16', # 0x10
139 'RW_DEV_MISMATCH': '17', # 0x11
140 'RW_REC_MISMATCH': '18', # 0x12
141 'RW_VERIFY_KEYBLOCK': '19', # 0x13
142 'RW_KEY_ROLLBACK': '20', # 0x14
143 'RW_DATA_KEY_PARSE': '21', # 0x15
144 'RW_VERIFY_PREAMBLE': '22', # 0x16
145 'RW_FW_ROLLBACK': '23', # 0x17
146 'RW_HEADER_VALID': '24', # 0x18
147 'RW_GET_FW_BODY': '25', # 0x19
148 'RW_HASH_WRONG_SIZE': '26', # 0x1A
149 'RW_VERIFY_BODY': '27', # 0x1B
150 'RW_VALID': '28', # 0x1C
151 # Read-only normal path requested by firmware preamble, but
152 # unsupported by firmware.
153 'RW_NO_RO_NORMAL': '29', # 0x1D
154 # Firmware boot failure outside of verified boot
155 'RO_FIRMWARE': '32', # 0x20
156 # Recovery mode TPM initialization requires a system reboot.
157 # The system was already in recovery mode for some other reason
158 # when this happened.
159 'RO_TPM_REBOOT': '33', # 0x21
160 # Unspecified/unknown error in read-only firmware
161 'RO_UNSPECIFIED': '63', # 0x3F
162 # User manually requested recovery by pressing a key at developer
163 # warning screen.
164 'RW_DEV_SCREEN': '65', # 0x41
165 # No OS kernel detected
166 'RW_NO_OS': '66', # 0x42
167 # OS kernel failed signature check
168 'RW_INVALID_OS': '67', # 0x43
169 # TPM error in rewritable firmware
170 'RW_TPM_ERROR': '68', # 0x44
171 # RW firmware in dev mode, but dev switch is off.
172 'RW_DEV_MISMATCH': '69', # 0x45
173 # Shared data error in rewritable firmware
174 'RW_SHARED_DATA': '70', # 0x46
175 # Test error from LoadKernel()
176 'RW_TEST_LK': '71', # 0x47
177 # No bootable disk found
178 'RW_NO_DISK': '72', # 0x48
179 # Unspecified/unknown error in rewritable firmware
180 'RW_UNSPECIFIED': '127', # 0x7F
181 # DM-verity error
182 'KE_DM_VERITY': '129', # 0x81
183 # Unspecified/unknown error in kernel
184 'KE_UNSPECIFIED': '191', # 0xBF
185 # Recovery mode test from user-mode
186 'US_TEST': '193', # 0xC1
187 # Unspecified/unknown error in user-mode
188 'US_UNSPECIFIED': '255', # 0xFF
189 }
190
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800191 # GBB flags
192 GBB_FLAG_DEV_SCREEN_SHORT_DELAY = 0x00000001
193 GBB_FLAG_LOAD_OPTION_ROMS = 0x00000002
194 GBB_FLAG_ENABLE_ALTERNATE_OS = 0x00000004
195 GBB_FLAG_FORCE_DEV_SWITCH_ON = 0x00000008
196 GBB_FLAG_FORCE_DEV_BOOT_USB = 0x00000010
197 GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK = 0x00000020
198
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800199 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800200 _faft_sequence = ()
201
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800202 _customized_ctrl_d_key_command = None
203 _customized_enter_key_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800204 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800205 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800206
207
208 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
209 # Parse arguments from command line
210 args = {}
211 for arg in cmdline_args:
212 match = re.search("^(\w+)=(.+)", arg)
213 if match:
214 args[match.group(1)] = match.group(2)
215
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800216 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800217 if 'ctrl_d_cmd' in args:
218 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
219 logging.info('Customized Ctrl-D key command: %s' %
220 self._customized_ctrl_d_key_command)
221 if 'enter_cmd' in args:
222 self._customized_enter_key_command = args['enter_cmd']
223 logging.info('Customized Enter key command: %s' %
224 self._customized_enter_key_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800225 if 'image' in args:
226 self._install_image_path = args['image']
227 logging.info('Install Chrome OS test image path: %s' %
228 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800229 if 'firmware_update' in args and args['firmware_update'].lower() \
230 not in ('0', 'false', 'no'):
231 if self._install_image_path:
232 self._firmware_update = True
233 logging.info('Also update firmware after installing.')
234 else:
235 logging.warning('Firmware update will not not performed '
236 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800237
238 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
239 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800240 if use_faft:
241 self.client_attr = FAFTClientAttribute(
242 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800243
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800244
245 def setup(self):
246 """Autotest setup function."""
247 super(FAFTSequence, self).setup()
248 if not self._remote_infos['faft']['used']:
249 raise error.TestError('The use_faft flag should be enabled.')
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800250 self.clear_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800251 self.register_faft_template({
252 'state_checker': (None),
253 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800254 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800255 'firmware_action': (None)
256 })
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800257 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800258 self.install_test_image(self._install_image_path,
259 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800260
261
262 def cleanup(self):
263 """Autotest cleanup function."""
264 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800265 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800266 super(FAFTSequence, self).cleanup()
267
268
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800269 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800270 """Assert an USB disk plugged-in on servo and a test image inside.
271
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800272 Args:
273 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
274 If None, it is detected automatically.
275
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800276 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800277 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800278 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800279 if usb_dev:
280 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
281 else:
282 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
283 usb_dev = self.servo.probe_host_usb_dev()
284 if not usb_dev:
285 raise error.TestError(
286 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800287
288 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800289 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800290 code = utils.system(
291 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
292 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800293 utils.system('sudo umount %s' % tmp_dir)
294 os.removedirs(tmp_dir)
295 if code != 0:
296 raise error.TestError(
297 'The image in the USB disk should be a test image.')
298
299
Simran Basi741b5d42012-05-18 11:27:15 -0700300 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800301 """Install the test image specied by the path onto the USB and DUT disk.
302
303 The method first copies the image to USB disk and reboots into it via
304 recovery mode. Then runs 'chromeos-install' to install it to DUT disk.
305
306 Args:
307 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800308 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800309 """
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800310 install_cmd = 'chromeos-install --yes'
311 if firmware_update:
312 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800313 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
314 image_path)
315 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800316
317 # Reuse the install_recovery_image method by using a test image.
318 # Don't wait for completion but run chromeos-install to install it.
Simran Basi741b5d42012-05-18 11:27:15 -0700319 self.servo.install_recovery_image(image_path)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800320 self.wait_for_client(install_deps=True)
321 self.run_faft_step({
322 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800323 install_cmd)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800324 })
325
326
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800327 def clear_gbb_flags(self, mask):
328 """Clear the GBB flags in the current flashrom.
329
330 Args:
331 mask: A mask of flags to be cleared.
332 """
333 gbb_flags = self.faft_client.get_gbb_flags()
334 if (gbb_flags & mask):
335 logging.info('Clear the GBB flags of 0x%x, from 0x%x to 0x%x.' %
336 (mask, gbb_flags, gbb_flags ^ mask))
337 self.faft_client.run_shell_command(
338 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' %
339 (gbb_flags ^ mask))
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800340 self.faft_client.reload_firmware()
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800341
342
Vic Yangb4e3e742012-06-02 13:17:38 +0800343 def _open_uart_pty(self):
344 """Open UART pty and spawn pexpect object.
345
346 Returns:
347 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
348 child is a fdpexpect object tied to it.
349 """
350 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
351 child = fdpexpect.fdspawn(fd)
352 return (fd, child)
353
354
355 def _flush_uart_pty(self, child):
356 """Flush UART output to prevent previous pending message interferring.
357
358 Args:
359 child: The fdpexpect object tied to UART pty.
360 """
361 child.sendline("")
362 while True:
363 try:
364 child.expect(".", timeout=0.01)
365 except pexpect.TIMEOUT:
366 break
367
368
369 def _uart_send(self, child, line):
370 """Flush and send command through UART.
371
372 Args:
373 child: The pexpect object tied to UART pty.
374 line: String to send through UART.
375
376 Raises:
377 error.TestFail: Raised when writing to UART fails.
378 """
379 logging.info("Sending UART command: %s" % line)
380 self._flush_uart_pty(child)
381 if child.sendline(line) != len(line) + 1:
382 raise error.TestFail("Failed to send UART command.")
383
384
385 def send_uart_command(self, command):
386 """Send command through UART.
387
388 This function open UART pty when called, and then command is sent
389 through UART.
390
391 Args:
392 command: The command string to send.
393
394 Raises:
395 error.TestFail: Raised when writing to UART fails.
396 """
397 (fd, child) = self._open_uart_pty()
398 try:
399 self._uart_send(child, command)
400 finally:
401 os.close(fd)
402
403
404 def send_uart_command_get_output(self, command, regex_list, timeout=1):
405 """Send command through UART and wait for response.
406
407 This function waits for response message matching regular expressions.
408
409 Args:
410 command: The command sent.
411 regex_list: List of regular expressions used to match response message.
412 Note, list must be ordered.
413
414 Returns:
415 List of match objects of response message.
416
417 Raises:
418 error.TestFail: If timed out waiting for EC response.
419 """
420 if not isinstance(regex_list, list):
421 regex_list = [regex_list]
422 result_list = []
423 (fd, child) = self._open_uart_pty()
424 try:
425 self._uart_send(child, command)
426 for regex in regex_list:
427 child.expect(regex, timeout=timeout)
428 result_list.append(child.match)
429 except pexpect.TIMEOUT:
430 raise error.TestFail("Timeout waiting for UART response.")
431 finally:
432 os.close(fd)
433 return result_list
434
435
Vic Yang4d72cb62012-07-24 11:51:09 +0800436 def check_ec_capability(self, required_cap=[]):
437 """Check if current platform has required EC capabilities.
438
439 Args:
440 required_cap: A list containing required EC capabilities. Pass in
441 None to only check for presence of Chrome EC.
442
443 Returns:
444 True if requirements are met. Otherwise, False.
445 """
446 if not self.client_attr.chrome_ec:
447 logging.warn('Requires Chrome EC to run this test.')
448 return False
449
450 for cap in required_cap:
451 if cap not in self.client_attr.ec_capability:
452 logging.warn('Requires EC capability "%s" to run this test.' %
453 cap)
454 return False
455
456 return True
457
458
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800459 def _parse_crossystem_output(self, lines):
460 """Parse the crossystem output into a dict.
461
462 Args:
463 lines: The list of crossystem output strings.
464
465 Returns:
466 A dict which contains the crossystem keys/values.
467
468 Raises:
469 error.TestError: If wrong format in crossystem output.
470
471 >>> seq = FAFTSequence()
472 >>> seq._parse_crossystem_output([ \
473 "arch = x86 # Platform architecture", \
474 "cros_debug = 1 # OS should allow debug", \
475 ])
476 {'cros_debug': '1', 'arch': 'x86'}
477 >>> seq._parse_crossystem_output([ \
478 "arch=x86", \
479 ])
480 Traceback (most recent call last):
481 ...
482 TestError: Failed to parse crossystem output: arch=x86
483 >>> seq._parse_crossystem_output([ \
484 "arch = x86 # Platform architecture", \
485 "arch = arm # Platform architecture", \
486 ])
487 Traceback (most recent call last):
488 ...
489 TestError: Duplicated crossystem key: arch
490 """
491 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
492 parsed_list = {}
493 for line in lines:
494 matched = re.match(pattern, line.strip())
495 if not matched:
496 raise error.TestError("Failed to parse crossystem output: %s"
497 % line)
498 (name, value) = (matched.group(1), matched.group(2))
499 if name in parsed_list:
500 raise error.TestError("Duplicated crossystem key: %s" % name)
501 parsed_list[name] = value
502 return parsed_list
503
504
505 def crossystem_checker(self, expected_dict):
506 """Check the crossystem values matched.
507
508 Given an expect_dict which describes the expected crossystem values,
509 this function check the current crossystem values are matched or not.
510
511 Args:
512 expected_dict: A dict which contains the expected values.
513
514 Returns:
515 True if the crossystem value matched; otherwise, False.
516 """
517 lines = self.faft_client.run_shell_command_get_output('crossystem')
518 got_dict = self._parse_crossystem_output(lines)
519 for key in expected_dict:
520 if key not in got_dict:
521 logging.info('Expected key "%s" not in crossystem result' % key)
522 return False
523 if isinstance(expected_dict[key], str):
524 if got_dict[key] != expected_dict[key]:
525 logging.info("Expected '%s' value '%s' but got '%s'" %
526 (key, expected_dict[key], got_dict[key]))
527 return False
528 elif isinstance(expected_dict[key], tuple):
529 # Expected value is a tuple of possible actual values.
530 if got_dict[key] not in expected_dict[key]:
531 logging.info("Expected '%s' values %s but got '%s'" %
532 (key, str(expected_dict[key]), got_dict[key]))
533 return False
534 else:
535 logging.info("The expected_dict is neither a str nor a dict.")
536 return False
537 return True
538
539
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800540 def root_part_checker(self, expected_part):
541 """Check the partition number of the root device matched.
542
543 Args:
544 expected_part: A string containing the number of the expected root
545 partition.
546
547 Returns:
548 True if the currect root partition number matched; otherwise, False.
549 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800550 part = self.faft_client.get_root_part()[-1]
551 if self.ROOTFS_MAP[expected_part] != part:
552 logging.info("Expected root part %s but got %s" %
553 (self.ROOTFS_MAP[expected_part], part))
554 return False
555 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800556
557
Vic Yang59cac9c2012-05-21 15:28:42 +0800558 def ec_act_copy_checker(self, expected_copy):
559 """Check the EC running firmware copy matches.
560
561 Args:
562 expected_copy: A string containing 'RO', 'A', or 'B' indicating
563 the expected copy of EC running firmware.
564
565 Returns:
566 True if the current EC running copy matches; otherwise, False.
567 """
568 lines = self.faft_client.run_shell_command_get_output('ectool version')
569 pattern = re.compile("Firmware copy: (.*)")
570 for line in lines:
571 matched = pattern.match(line)
572 if matched and matched.group(1) == expected_copy:
573 return True
574 return False
575
576
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800577 def check_root_part_on_non_recovery(self, part):
578 """Check the partition number of root device and on normal/dev boot.
579
580 Returns:
581 True if the root device matched and on normal/dev boot;
582 otherwise, False.
583 """
584 return self.root_part_checker(part) and \
585 self.crossystem_checker({
586 'mainfw_type': ('normal', 'developer'),
587 'recoverysw_boot': '0',
588 })
589
590
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800591 def _join_part(self, dev, part):
592 """Return a concatenated string of device and partition number.
593
594 Args:
595 dev: A string of device, e.g.'/dev/sda'.
596 part: A string of partition number, e.g.'3'.
597
598 Returns:
599 A concatenated string of device and partition number, e.g.'/dev/sda3'.
600
601 >>> seq = FAFTSequence()
602 >>> seq._join_part('/dev/sda', '3')
603 '/dev/sda3'
604 >>> seq._join_part('/dev/mmcblk0', '2')
605 '/dev/mmcblk0p2'
606 """
607 if 'mmcblk' in dev:
608 return dev + 'p' + part
609 else:
610 return dev + part
611
612
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800613 def copy_kernel_and_rootfs(self, from_part, to_part):
614 """Copy kernel and rootfs from from_part to to_part.
615
616 Args:
617 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800618 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800619 """
620 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800621 logging.info('Copying kernel from %s to %s. Please wait...' %
622 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800623 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800624 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
625 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
626 logging.info('Copying rootfs from %s to %s. Please wait...' %
627 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800628 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800629 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
630 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800631
632
633 def ensure_kernel_boot(self, part):
634 """Ensure the request kernel boot.
635
636 If not, it duplicates the current kernel to the requested kernel
637 and sets the requested higher priority to ensure it boot.
638
639 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800640 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800641 """
642 if not self.root_part_checker(part):
643 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
644 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800645 self.run_faft_step({
646 'userspace_action': (self.reset_and_prioritize_kernel, part),
647 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800648
649
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800650 def send_ctrl_d_to_dut(self):
651 """Send Ctrl-D key to DUT."""
652 if self._customized_ctrl_d_key_command:
653 logging.info('running the customized Ctrl-D key command')
654 os.system(self._customized_ctrl_d_key_command)
655 else:
656 self.servo.ctrl_d()
657
658
659 def send_enter_to_dut(self):
660 """Send Enter key to DUT."""
661 if self._customized_enter_key_command:
662 logging.info('running the customized Enter key command')
663 os.system(self._customized_enter_key_command)
664 else:
665 self.servo.enter_key()
666
667
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800668 def wait_fw_screen_and_ctrl_d(self):
669 """Wait for firmware warning screen and press Ctrl-D."""
670 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800671 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800672
673
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800674 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
675 """Wait for firmware warning screen and trigger recovery boot."""
676 time.sleep(self.FIRMWARE_SCREEN_DELAY)
677 self.send_enter_to_dut()
678
679 # For Alex/ZGB, there is a dev warning screen in text mode.
680 # Skip it by pressing Ctrl-D.
681 if need_dev_transition:
682 time.sleep(self.TEXT_SCREEN_DELAY)
683 self.send_ctrl_d_to_dut()
684
685
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800686 def wait_fw_screen_and_plug_usb(self):
687 """Wait for firmware warning screen and then unplug and plug the USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800688 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800689 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
690 time.sleep(self.USB_PLUG_DELAY)
691 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
692
693
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800694 def wait_fw_screen_and_press_power(self):
695 """Wait for firmware warning screen and press power button."""
696 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800697 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800698
699
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800700 def wait_longer_fw_screen_and_press_power(self):
701 """Wait for firmware screen without timeout and press power button."""
702 time.sleep(self.DEV_SCREEN_TIMEOUT)
703 self.wait_fw_screen_and_press_power()
704
705
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800706 def wait_fw_screen_and_close_lid(self):
707 """Wait for firmware warning screen and close lid."""
708 time.sleep(self.FIRMWARE_SCREEN_DELAY)
709 self.servo.lid_close()
710
711
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800712 def wait_longer_fw_screen_and_close_lid(self):
713 """Wait for firmware screen without timeout and close lid."""
714 time.sleep(self.FIRMWARE_SCREEN_DELAY)
715 self.wait_fw_screen_and_close_lid()
716
717
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800718 def setup_tried_fwb(self, tried_fwb):
719 """Setup for fw B tried state.
720
721 It makes sure the system in the requested fw B tried state. If not, it
722 tries to do so.
723
724 Args:
725 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
726 """
727 if tried_fwb:
728 if not self.crossystem_checker({'tried_fwb': '1'}):
729 logging.info(
730 'Firmware is not booted with tried_fwb. Reboot into it.')
731 self.run_faft_step({
732 'userspace_action': self.faft_client.set_try_fw_b,
733 })
734 else:
735 if not self.crossystem_checker({'tried_fwb': '0'}):
736 logging.info(
737 'Firmware is booted with tried_fwb. Reboot to clear.')
738 self.run_faft_step({})
739
740
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800741 def enable_dev_mode_and_fw(self):
742 """Enable developer mode and use developer firmware."""
Vic Yange7553162012-06-20 16:20:47 +0800743 if self.client_attr.keyboard_dev:
744 self.enable_keyboard_dev_mode()
745 else:
746 self.servo.enable_development_mode()
747 self.faft_client.run_shell_command(
748 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800749
750
751 def enable_normal_mode_and_fw(self):
752 """Enable normal mode and use normal firmware."""
Vic Yange7553162012-06-20 16:20:47 +0800753 if self.client_attr.keyboard_dev:
754 self.disable_keyboard_dev_mode()
755 else:
756 self.servo.disable_development_mode()
757 self.faft_client.run_shell_command(
758 'chromeos-firmwareupdate --mode tonormal && reboot')
759
760
761 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
762 """Wait for firmware screen and then switch into or out of dev mode.
763
764 Args:
765 dev: True if switching into dev mode. Otherwise, False.
766 """
767 time.sleep(self.FIRMWARE_SCREEN_DELAY)
768 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800769 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800770 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800771 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800772 time.sleep(self.FIRMWARE_KEY_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800773 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800774
775
776 def enable_keyboard_dev_mode(self):
777 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800778 # Plug out USB disk for preventing recovery boot without warning
779 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800780 # Rebooting EC with rec mode on. Should power on AP.
781 self.servo.enable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800782 self.cold_reboot()
Vic Yange7553162012-06-20 16:20:47 +0800783 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
784 self.servo.disable_recovery_mode()
785
786
787 def disable_keyboard_dev_mode(self):
788 logging.info("Disabling keyboard controlled developer mode")
789 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800790 self.cold_reboot()
Vic Yange7553162012-06-20 16:20:47 +0800791 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800792
793
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800794 def setup_dev_mode(self, dev_mode):
795 """Setup for development mode.
796
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800797 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800798 tries to do so.
799
800 Args:
801 dev_mode: True if requested in dev mode; False if normal mode.
802 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800803 # Change the default firmware_action for dev mode passing the fw screen.
804 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800805 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
806 else None),
807 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800808 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800809 if (not self.client_attr.keyboard_dev and
810 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800811 logging.info('Dev switch is not on. Now switch it on.')
812 self.servo.enable_development_mode()
813 if not self.crossystem_checker({'devsw_boot': '1',
814 'mainfw_type': 'developer'}):
815 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800816 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800817 'userspace_action': None if self.client_attr.keyboard_dev
818 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800819 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800820 'reboot_action': self.enable_keyboard_dev_mode if
821 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800822 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800823 else:
Vic Yange7553162012-06-20 16:20:47 +0800824 if (not self.client_attr.keyboard_dev and
825 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800826 logging.info('Dev switch is not off. Now switch it off.')
827 self.servo.disable_development_mode()
828 if not self.crossystem_checker({'devsw_boot': '0',
829 'mainfw_type': 'normal'}):
830 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800831 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800832 'userspace_action': None if self.client_attr.keyboard_dev
833 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800834 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800835 'reboot_action': self.disable_keyboard_dev_mode if
836 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800837 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800838
839
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800840 def setup_kernel(self, part):
841 """Setup for kernel test.
842
843 It makes sure both kernel A and B bootable and the current boot is
844 the requested kernel part.
845
846 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800847 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800848 """
849 self.ensure_kernel_boot(part)
850 self.copy_kernel_and_rootfs(from_part=part,
851 to_part=self.OTHER_KERNEL_MAP[part])
852 self.reset_and_prioritize_kernel(part)
853
854
855 def reset_and_prioritize_kernel(self, part):
856 """Make the requested partition highest priority.
857
858 This function also reset kerenl A and B to bootable.
859
860 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800861 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800862 """
863 root_dev = self.faft_client.get_root_dev()
864 # Reset kernel A and B to bootable.
865 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
866 (self.KERNEL_MAP['a'], root_dev))
867 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
868 (self.KERNEL_MAP['b'], root_dev))
869 # Set kernel part highest priority.
870 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
871 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800872 # Safer to sync and wait until the cgpt status written to the disk.
873 self.faft_client.run_shell_command('sync')
874 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800875
876
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800877 def warm_reboot(self):
878 """Request a warm reboot.
879
880 This directly calls the servo warm reset.
881 """
882 self.servo.warm_reset()
883
884
885 def cold_reboot(self):
886 """Request a cold reboot.
887
888 A wrapper for underlying servo cold reset.
889 """
890 if self.check_ec_capability():
891 # We don't use servo.cold_reset() here because software sync is
892 # not yet finished, and device may or may not come up after cold
893 # reset. Pressing power button before firmware comes up solves this.
894 #
895 # The correct behavior should be (not work now):
896 # - If rebooting EC with rec mode on, power on AP and it boots
897 # into recovery mode.
898 # - If rebooting EC with rec mode off, power on AP for software
899 # sync. Then AP checks if lid open or not. If lid open, continue;
900 # otherwise, shut AP down and need servo for a power button
901 # press.
902 self.servo.set('cold_reset', 'on')
903 self.servo.set('cold_reset', 'off')
904 time.sleep(self.POWER_BTN_DELAY)
905 self.servo.power_short_press()
906 else:
907 self.servo.cold_reset()
908
909
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800910 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800911 """Request the client sync and do a warm reboot.
912
913 This is the default reboot action on FAFT.
914 """
915 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800916 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800917 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800918
919
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800920 def sync_and_cold_reboot(self):
921 """Request the client sync and do a cold reboot.
922
923 This reboot action is used to reset EC for recovery mode.
924 """
925 self.faft_client.run_shell_command('sync')
926 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800927 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800928
929
Vic Yang59cac9c2012-05-21 15:28:42 +0800930 def sync_and_ec_reboot(self):
931 """Request the client sync and do a EC triggered reboot."""
932 self.faft_client.run_shell_command('sync')
933 time.sleep(self.SYNC_DELAY)
934 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
935 self.EC_REBOOT_DELAY)
Vic Yangf86728a2012-07-30 10:44:07 +0800936 time.sleep(self.EC_REBOOT_DELAY)
937 self.check_lid_and_power_on()
938
939
940 def check_lid_and_power_on(self):
941 """
942 On devices with EC software sync, system powers on after EC reboots if
943 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
944 This method checks lid switch state and presses power button if
945 necessary.
946 """
947 if self.servo.get("lid_open") == "no":
948 time.sleep(self.SOFTWARE_SYNC_DELAY)
949 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +0800950
951
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800952 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
953 """Modify the kernel header magic in USB stick.
954
955 The kernel header magic is the first 8-byte of kernel partition.
956 We modify it to make it fail on kernel verification check.
957
958 Args:
959 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
960 from_magic: A string of magic which we change it from.
961 to_magic: A string of magic which we change it to.
962
963 Raises:
964 error.TestError: if failed to change magic.
965 """
966 assert len(from_magic) == 8
967 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800968 # USB image only contains one kernel.
969 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800970 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
971 current_magic = utils.system_output(read_cmd)
972 if current_magic == to_magic:
973 logging.info("The kernel magic is already %s." % current_magic)
974 return
975 if current_magic != from_magic:
976 raise error.TestError("Invalid kernel image on USB: wrong magic.")
977
978 logging.info('Modify the kernel magic in USB, from %s to %s.' %
979 (from_magic, to_magic))
980 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
981 " 2>/dev/null" % (to_magic, kernel_part))
982 utils.system(write_cmd)
983
984 if utils.system_output(read_cmd) != to_magic:
985 raise error.TestError("Failed to write new magic.")
986
987
988 def corrupt_usb_kernel(self, usb_dev):
989 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
990
991 Args:
992 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
993 """
994 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
995 self.CORRUPTED_MAGIC)
996
997
998 def restore_usb_kernel(self, usb_dev):
999 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1000
1001 Args:
1002 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1003 """
1004 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1005 self.CHROMEOS_MAGIC)
1006
1007
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001008 def _call_action(self, action_tuple):
1009 """Call the action function with/without arguments.
1010
1011 Args:
1012 action_tuple: A function, or a tuple which consisted of a function
1013 and its arguments (if any).
1014
1015 Returns:
1016 The result value of the action function.
1017 """
1018 if isinstance(action_tuple, tuple):
1019 action = action_tuple[0]
1020 args = action_tuple[1:]
1021 if callable(action):
1022 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001023 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001024 return action(*args)
1025 else:
1026 logging.info('action is not callable!')
1027 else:
1028 action = action_tuple
1029 if action is not None:
1030 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001031 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001032 return action()
1033 else:
1034 logging.info('action is not callable!')
1035
1036 return None
1037
1038
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001039 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1040 post_power_action=None):
1041 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1042
1043 Args:
1044 shutdown_action: a function which makes DUT shutdown, like pressing
1045 power key.
1046 pre_power_action: a function which is called before next power on.
1047 post_power_action: a function which is called after next power on.
1048
1049 Raises:
1050 error.TestFail: if the shutdown_action() failed to turn DUT off.
1051 """
1052 self._call_action(shutdown_action)
1053 logging.info('Wait to ensure DUT shut down...')
1054 try:
1055 self.wait_for_client()
1056 raise error.TestFail(
1057 'Should shut the device down after calling %s.' %
1058 str(shutdown_action))
1059 except AssertionError:
1060 logging.info(
1061 'DUT is surely shutdown. We are going to power it on again...')
1062
1063 if pre_power_action:
1064 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001065 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001066 if post_power_action:
1067 self._call_action(post_power_action)
1068
1069
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001070 def register_faft_template(self, template):
1071 """Register FAFT template, the default FAFT_STEP of each step.
1072
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001073 Any missing field falls back to the original faft_template.
1074
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001075 Args:
1076 template: A FAFT_STEP dict.
1077 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001078 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001079
1080
1081 def register_faft_sequence(self, sequence):
1082 """Register FAFT sequence.
1083
1084 Args:
1085 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1086 """
1087 self._faft_sequence = sequence
1088
1089
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001090 def run_faft_step(self, step, no_reboot=False):
1091 """Run a single FAFT step.
1092
1093 Any missing field falls back to faft_template. An empty step means
1094 running the default faft_template.
1095
1096 Args:
1097 step: A FAFT_STEP dict.
1098 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001099
1100 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001101 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001102 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001103 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001104 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1105 'firmware_action', 'install_deps_after_boot')
1106
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001107 test = {}
1108 test.update(self._faft_template)
1109 test.update(step)
1110
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001111 for key in test:
1112 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001113 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001114
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001115 if test['state_checker']:
1116 if not self._call_action(test['state_checker']):
1117 raise error.TestFail('State checker failed!')
1118
1119 self._call_action(test['userspace_action'])
1120
1121 # Don't run reboot_action and firmware_action if no_reboot is True.
1122 if not no_reboot:
1123 self._call_action(test['reboot_action'])
1124 self.wait_for_client_offline()
1125 self._call_action(test['firmware_action'])
1126
1127 if 'install_deps_after_boot' in test:
1128 self.wait_for_client(
1129 install_deps=test['install_deps_after_boot'])
1130 else:
1131 self.wait_for_client()
1132
1133
1134 def run_faft_sequence(self):
1135 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001136 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001137 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001138 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001139 logging.info('======== Running FAFT sequence step %d ========' %
1140 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001141 # Don't reboot in the last step.
1142 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001143 index += 1