blob: 7a6042eff89e8bfd49c44333834ba294fc33e299 [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 Tam1408f172012-07-31 15:06:21 +080089 FIRMWARE_SCREEN_DELAY = 5
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 Yangf86728a2012-07-30 10:44:07 +0800102 # Delay of EC software sync hash calculating time
103 SOFTWARE_SYNC_DELAY = 6
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800104
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800105 # The developer screen timeouts fit our spec.
106 DEV_SCREEN_TIMEOUT = 30
107
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800108 CHROMEOS_MAGIC = "CHROMEOS"
109 CORRUPTED_MAGIC = "CORRUPTD"
110
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800111 # Recovery reason codes, copied from:
112 # vboot_reference/firmware/lib/vboot_nvstorage.h
113 # vboot_reference/firmware/lib/vboot_struct.h
114 RECOVERY_REASON = {
115 # Recovery not requested
116 'NOT_REQUESTED': '0', # 0x00
117 # Recovery requested from legacy utility
118 'LEGACY': '1', # 0x01
119 # User manually requested recovery via recovery button
120 'RO_MANUAL': '2', # 0x02
121 # RW firmware failed signature check
122 'RO_INVALID_RW': '3', # 0x03
123 # S3 resume failed
124 'RO_S3_RESUME': '4', # 0x04
125 # TPM error in read-only firmware
126 'RO_TPM_ERROR': '5', # 0x05
127 # Shared data error in read-only firmware
128 'RO_SHARED_DATA': '6', # 0x06
129 # Test error from S3Resume()
130 'RO_TEST_S3': '7', # 0x07
131 # Test error from LoadFirmwareSetup()
132 'RO_TEST_LFS': '8', # 0x08
133 # Test error from LoadFirmware()
134 'RO_TEST_LF': '9', # 0x09
135 # RW firmware failed signature check
136 'RW_NOT_DONE': '16', # 0x10
137 'RW_DEV_MISMATCH': '17', # 0x11
138 'RW_REC_MISMATCH': '18', # 0x12
139 'RW_VERIFY_KEYBLOCK': '19', # 0x13
140 'RW_KEY_ROLLBACK': '20', # 0x14
141 'RW_DATA_KEY_PARSE': '21', # 0x15
142 'RW_VERIFY_PREAMBLE': '22', # 0x16
143 'RW_FW_ROLLBACK': '23', # 0x17
144 'RW_HEADER_VALID': '24', # 0x18
145 'RW_GET_FW_BODY': '25', # 0x19
146 'RW_HASH_WRONG_SIZE': '26', # 0x1A
147 'RW_VERIFY_BODY': '27', # 0x1B
148 'RW_VALID': '28', # 0x1C
149 # Read-only normal path requested by firmware preamble, but
150 # unsupported by firmware.
151 'RW_NO_RO_NORMAL': '29', # 0x1D
152 # Firmware boot failure outside of verified boot
153 'RO_FIRMWARE': '32', # 0x20
154 # Recovery mode TPM initialization requires a system reboot.
155 # The system was already in recovery mode for some other reason
156 # when this happened.
157 'RO_TPM_REBOOT': '33', # 0x21
158 # Unspecified/unknown error in read-only firmware
159 'RO_UNSPECIFIED': '63', # 0x3F
160 # User manually requested recovery by pressing a key at developer
161 # warning screen.
162 'RW_DEV_SCREEN': '65', # 0x41
163 # No OS kernel detected
164 'RW_NO_OS': '66', # 0x42
165 # OS kernel failed signature check
166 'RW_INVALID_OS': '67', # 0x43
167 # TPM error in rewritable firmware
168 'RW_TPM_ERROR': '68', # 0x44
169 # RW firmware in dev mode, but dev switch is off.
170 'RW_DEV_MISMATCH': '69', # 0x45
171 # Shared data error in rewritable firmware
172 'RW_SHARED_DATA': '70', # 0x46
173 # Test error from LoadKernel()
174 'RW_TEST_LK': '71', # 0x47
175 # No bootable disk found
176 'RW_NO_DISK': '72', # 0x48
177 # Unspecified/unknown error in rewritable firmware
178 'RW_UNSPECIFIED': '127', # 0x7F
179 # DM-verity error
180 'KE_DM_VERITY': '129', # 0x81
181 # Unspecified/unknown error in kernel
182 'KE_UNSPECIFIED': '191', # 0xBF
183 # Recovery mode test from user-mode
184 'US_TEST': '193', # 0xC1
185 # Unspecified/unknown error in user-mode
186 'US_UNSPECIFIED': '255', # 0xFF
187 }
188
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800189 # GBB flags
190 GBB_FLAG_DEV_SCREEN_SHORT_DELAY = 0x00000001
191 GBB_FLAG_LOAD_OPTION_ROMS = 0x00000002
192 GBB_FLAG_ENABLE_ALTERNATE_OS = 0x00000004
193 GBB_FLAG_FORCE_DEV_SWITCH_ON = 0x00000008
194 GBB_FLAG_FORCE_DEV_BOOT_USB = 0x00000010
195 GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK = 0x00000020
196
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800197 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800198 _faft_sequence = ()
199
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800200 _customized_ctrl_d_key_command = None
201 _customized_enter_key_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800202 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800203 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800204
205
206 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
207 # Parse arguments from command line
208 args = {}
209 for arg in cmdline_args:
210 match = re.search("^(\w+)=(.+)", arg)
211 if match:
212 args[match.group(1)] = match.group(2)
213
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800214 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800215 if 'ctrl_d_cmd' in args:
216 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
217 logging.info('Customized Ctrl-D key command: %s' %
218 self._customized_ctrl_d_key_command)
219 if 'enter_cmd' in args:
220 self._customized_enter_key_command = args['enter_cmd']
221 logging.info('Customized Enter key command: %s' %
222 self._customized_enter_key_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800223 if 'image' in args:
224 self._install_image_path = args['image']
225 logging.info('Install Chrome OS test image path: %s' %
226 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800227 if 'firmware_update' in args and args['firmware_update'].lower() \
228 not in ('0', 'false', 'no'):
229 if self._install_image_path:
230 self._firmware_update = True
231 logging.info('Also update firmware after installing.')
232 else:
233 logging.warning('Firmware update will not not performed '
234 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800235
236 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
237 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800238 if use_faft:
239 self.client_attr = FAFTClientAttribute(
240 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800241
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800242
243 def setup(self):
244 """Autotest setup function."""
245 super(FAFTSequence, self).setup()
246 if not self._remote_infos['faft']['used']:
247 raise error.TestError('The use_faft flag should be enabled.')
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800248 self.clear_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON)
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800249 self.clear_gbb_flags(self.GBB_FLAG_DEV_SCREEN_SHORT_DELAY)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800250 self.register_faft_template({
251 'state_checker': (None),
252 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800253 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800254 'firmware_action': (None)
255 })
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800256 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800257 self.install_test_image(self._install_image_path,
258 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800259
260
261 def cleanup(self):
262 """Autotest cleanup function."""
263 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800264 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800265 super(FAFTSequence, self).cleanup()
266
267
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800268 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800269 """Assert an USB disk plugged-in on servo and a test image inside.
270
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800271 Args:
272 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
273 If None, it is detected automatically.
274
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800275 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800276 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800277 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800278 if usb_dev:
279 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
280 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700281 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800282 usb_dev = self.servo.probe_host_usb_dev()
283 if not usb_dev:
284 raise error.TestError(
285 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800286
287 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800288 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800289 code = utils.system(
290 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
291 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800292 utils.system('sudo umount %s' % tmp_dir)
293 os.removedirs(tmp_dir)
294 if code != 0:
295 raise error.TestError(
296 'The image in the USB disk should be a test image.')
297
298
Simran Basi741b5d42012-05-18 11:27:15 -0700299 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800300 """Install the test image specied by the path onto the USB and DUT disk.
301
302 The method first copies the image to USB disk and reboots into it via
303 recovery mode. Then runs 'chromeos-install' to install it to DUT disk.
304
305 Args:
306 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800307 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800308 """
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800309 install_cmd = 'chromeos-install --yes'
310 if firmware_update:
311 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800312 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
313 image_path)
314 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800315
316 # Reuse the install_recovery_image method by using a test image.
317 # Don't wait for completion but run chromeos-install to install it.
Simran Basi741b5d42012-05-18 11:27:15 -0700318 self.servo.install_recovery_image(image_path)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800319 self.wait_for_client(install_deps=True)
320 self.run_faft_step({
321 'userspace_action': (self.faft_client.run_shell_command,
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800322 install_cmd)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800323 })
324
325
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800326 def clear_gbb_flags(self, mask):
327 """Clear the GBB flags in the current flashrom.
328
329 Args:
330 mask: A mask of flags to be cleared.
331 """
332 gbb_flags = self.faft_client.get_gbb_flags()
333 if (gbb_flags & mask):
334 logging.info('Clear the GBB flags of 0x%x, from 0x%x to 0x%x.' %
335 (mask, gbb_flags, gbb_flags ^ mask))
336 self.faft_client.run_shell_command(
337 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' %
338 (gbb_flags ^ mask))
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800339 self.faft_client.reload_firmware()
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800340
341
Vic Yangb4e3e742012-06-02 13:17:38 +0800342 def _open_uart_pty(self):
343 """Open UART pty and spawn pexpect object.
344
345 Returns:
346 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
347 child is a fdpexpect object tied to it.
348 """
349 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
350 child = fdpexpect.fdspawn(fd)
351 return (fd, child)
352
353
354 def _flush_uart_pty(self, child):
355 """Flush UART output to prevent previous pending message interferring.
356
357 Args:
358 child: The fdpexpect object tied to UART pty.
359 """
360 child.sendline("")
361 while True:
362 try:
363 child.expect(".", timeout=0.01)
364 except pexpect.TIMEOUT:
365 break
366
367
368 def _uart_send(self, child, line):
369 """Flush and send command through UART.
370
371 Args:
372 child: The pexpect object tied to UART pty.
373 line: String to send through UART.
374
375 Raises:
376 error.TestFail: Raised when writing to UART fails.
377 """
378 logging.info("Sending UART command: %s" % line)
379 self._flush_uart_pty(child)
380 if child.sendline(line) != len(line) + 1:
381 raise error.TestFail("Failed to send UART command.")
382
383
384 def send_uart_command(self, command):
385 """Send command through UART.
386
387 This function open UART pty when called, and then command is sent
388 through UART.
389
390 Args:
391 command: The command string to send.
392
393 Raises:
394 error.TestFail: Raised when writing to UART fails.
395 """
396 (fd, child) = self._open_uart_pty()
397 try:
398 self._uart_send(child, command)
399 finally:
400 os.close(fd)
401
402
403 def send_uart_command_get_output(self, command, regex_list, timeout=1):
404 """Send command through UART and wait for response.
405
406 This function waits for response message matching regular expressions.
407
408 Args:
409 command: The command sent.
410 regex_list: List of regular expressions used to match response message.
411 Note, list must be ordered.
412
413 Returns:
414 List of match objects of response message.
415
416 Raises:
417 error.TestFail: If timed out waiting for EC response.
418 """
419 if not isinstance(regex_list, list):
420 regex_list = [regex_list]
421 result_list = []
422 (fd, child) = self._open_uart_pty()
423 try:
424 self._uart_send(child, command)
425 for regex in regex_list:
426 child.expect(regex, timeout=timeout)
427 result_list.append(child.match)
428 except pexpect.TIMEOUT:
429 raise error.TestFail("Timeout waiting for UART response.")
430 finally:
431 os.close(fd)
432 return result_list
433
434
Vic Yang4d72cb62012-07-24 11:51:09 +0800435 def check_ec_capability(self, required_cap=[]):
436 """Check if current platform has required EC capabilities.
437
438 Args:
439 required_cap: A list containing required EC capabilities. Pass in
440 None to only check for presence of Chrome EC.
441
442 Returns:
443 True if requirements are met. Otherwise, False.
444 """
445 if not self.client_attr.chrome_ec:
446 logging.warn('Requires Chrome EC to run this test.')
447 return False
448
449 for cap in required_cap:
450 if cap not in self.client_attr.ec_capability:
451 logging.warn('Requires EC capability "%s" to run this test.' %
452 cap)
453 return False
454
455 return True
456
457
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800458 def _parse_crossystem_output(self, lines):
459 """Parse the crossystem output into a dict.
460
461 Args:
462 lines: The list of crossystem output strings.
463
464 Returns:
465 A dict which contains the crossystem keys/values.
466
467 Raises:
468 error.TestError: If wrong format in crossystem output.
469
470 >>> seq = FAFTSequence()
471 >>> seq._parse_crossystem_output([ \
472 "arch = x86 # Platform architecture", \
473 "cros_debug = 1 # OS should allow debug", \
474 ])
475 {'cros_debug': '1', 'arch': 'x86'}
476 >>> seq._parse_crossystem_output([ \
477 "arch=x86", \
478 ])
479 Traceback (most recent call last):
480 ...
481 TestError: Failed to parse crossystem output: arch=x86
482 >>> seq._parse_crossystem_output([ \
483 "arch = x86 # Platform architecture", \
484 "arch = arm # Platform architecture", \
485 ])
486 Traceback (most recent call last):
487 ...
488 TestError: Duplicated crossystem key: arch
489 """
490 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
491 parsed_list = {}
492 for line in lines:
493 matched = re.match(pattern, line.strip())
494 if not matched:
495 raise error.TestError("Failed to parse crossystem output: %s"
496 % line)
497 (name, value) = (matched.group(1), matched.group(2))
498 if name in parsed_list:
499 raise error.TestError("Duplicated crossystem key: %s" % name)
500 parsed_list[name] = value
501 return parsed_list
502
503
504 def crossystem_checker(self, expected_dict):
505 """Check the crossystem values matched.
506
507 Given an expect_dict which describes the expected crossystem values,
508 this function check the current crossystem values are matched or not.
509
510 Args:
511 expected_dict: A dict which contains the expected values.
512
513 Returns:
514 True if the crossystem value matched; otherwise, False.
515 """
516 lines = self.faft_client.run_shell_command_get_output('crossystem')
517 got_dict = self._parse_crossystem_output(lines)
518 for key in expected_dict:
519 if key not in got_dict:
520 logging.info('Expected key "%s" not in crossystem result' % key)
521 return False
522 if isinstance(expected_dict[key], str):
523 if got_dict[key] != expected_dict[key]:
524 logging.info("Expected '%s' value '%s' but got '%s'" %
525 (key, expected_dict[key], got_dict[key]))
526 return False
527 elif isinstance(expected_dict[key], tuple):
528 # Expected value is a tuple of possible actual values.
529 if got_dict[key] not in expected_dict[key]:
530 logging.info("Expected '%s' values %s but got '%s'" %
531 (key, str(expected_dict[key]), got_dict[key]))
532 return False
533 else:
534 logging.info("The expected_dict is neither a str nor a dict.")
535 return False
536 return True
537
538
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800539 def root_part_checker(self, expected_part):
540 """Check the partition number of the root device matched.
541
542 Args:
543 expected_part: A string containing the number of the expected root
544 partition.
545
546 Returns:
547 True if the currect root partition number matched; otherwise, False.
548 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800549 part = self.faft_client.get_root_part()[-1]
550 if self.ROOTFS_MAP[expected_part] != part:
551 logging.info("Expected root part %s but got %s" %
552 (self.ROOTFS_MAP[expected_part], part))
553 return False
554 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800555
556
Vic Yang59cac9c2012-05-21 15:28:42 +0800557 def ec_act_copy_checker(self, expected_copy):
558 """Check the EC running firmware copy matches.
559
560 Args:
561 expected_copy: A string containing 'RO', 'A', or 'B' indicating
562 the expected copy of EC running firmware.
563
564 Returns:
565 True if the current EC running copy matches; otherwise, False.
566 """
567 lines = self.faft_client.run_shell_command_get_output('ectool version')
568 pattern = re.compile("Firmware copy: (.*)")
569 for line in lines:
570 matched = pattern.match(line)
571 if matched and matched.group(1) == expected_copy:
572 return True
573 return False
574
575
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800576 def check_root_part_on_non_recovery(self, part):
577 """Check the partition number of root device and on normal/dev boot.
578
579 Returns:
580 True if the root device matched and on normal/dev boot;
581 otherwise, False.
582 """
583 return self.root_part_checker(part) and \
584 self.crossystem_checker({
585 'mainfw_type': ('normal', 'developer'),
586 'recoverysw_boot': '0',
587 })
588
589
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800590 def _join_part(self, dev, part):
591 """Return a concatenated string of device and partition number.
592
593 Args:
594 dev: A string of device, e.g.'/dev/sda'.
595 part: A string of partition number, e.g.'3'.
596
597 Returns:
598 A concatenated string of device and partition number, e.g.'/dev/sda3'.
599
600 >>> seq = FAFTSequence()
601 >>> seq._join_part('/dev/sda', '3')
602 '/dev/sda3'
603 >>> seq._join_part('/dev/mmcblk0', '2')
604 '/dev/mmcblk0p2'
605 """
606 if 'mmcblk' in dev:
607 return dev + 'p' + part
608 else:
609 return dev + part
610
611
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800612 def copy_kernel_and_rootfs(self, from_part, to_part):
613 """Copy kernel and rootfs from from_part to to_part.
614
615 Args:
616 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800617 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800618 """
619 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800620 logging.info('Copying kernel from %s to %s. Please wait...' %
621 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800622 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800623 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
624 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
625 logging.info('Copying rootfs from %s to %s. Please wait...' %
626 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800627 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800628 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
629 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800630
631
632 def ensure_kernel_boot(self, part):
633 """Ensure the request kernel boot.
634
635 If not, it duplicates the current kernel to the requested kernel
636 and sets the requested higher priority to ensure it boot.
637
638 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800639 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800640 """
641 if not self.root_part_checker(part):
642 self.copy_kernel_and_rootfs(from_part=self.OTHER_KERNEL_MAP[part],
643 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800644 self.run_faft_step({
645 'userspace_action': (self.reset_and_prioritize_kernel, part),
646 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800647
648
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800649 def send_ctrl_d_to_dut(self):
650 """Send Ctrl-D key to DUT."""
651 if self._customized_ctrl_d_key_command:
652 logging.info('running the customized Ctrl-D key command')
653 os.system(self._customized_ctrl_d_key_command)
654 else:
655 self.servo.ctrl_d()
656
657
658 def send_enter_to_dut(self):
659 """Send Enter key to DUT."""
660 if self._customized_enter_key_command:
661 logging.info('running the customized Enter key command')
662 os.system(self._customized_enter_key_command)
663 else:
664 self.servo.enter_key()
665
666
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800667 def wait_fw_screen_and_ctrl_d(self):
668 """Wait for firmware warning screen and press Ctrl-D."""
669 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800670 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800671
672
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800673 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
674 """Wait for firmware warning screen and trigger recovery boot."""
675 time.sleep(self.FIRMWARE_SCREEN_DELAY)
676 self.send_enter_to_dut()
677
678 # For Alex/ZGB, there is a dev warning screen in text mode.
679 # Skip it by pressing Ctrl-D.
680 if need_dev_transition:
681 time.sleep(self.TEXT_SCREEN_DELAY)
682 self.send_ctrl_d_to_dut()
683
684
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800685 def wait_fw_screen_and_plug_usb(self):
686 """Wait for firmware warning screen and then unplug and plug the USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800687 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800688 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
689 time.sleep(self.USB_PLUG_DELAY)
690 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
691
692
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800693 def wait_fw_screen_and_press_power(self):
694 """Wait for firmware warning screen and press power button."""
695 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +0800696 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800697
698
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800699 def wait_longer_fw_screen_and_press_power(self):
700 """Wait for firmware screen without timeout and press power button."""
701 time.sleep(self.DEV_SCREEN_TIMEOUT)
702 self.wait_fw_screen_and_press_power()
703
704
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800705 def wait_fw_screen_and_close_lid(self):
706 """Wait for firmware warning screen and close lid."""
707 time.sleep(self.FIRMWARE_SCREEN_DELAY)
708 self.servo.lid_close()
709
710
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800711 def wait_longer_fw_screen_and_close_lid(self):
712 """Wait for firmware screen without timeout and close lid."""
713 time.sleep(self.FIRMWARE_SCREEN_DELAY)
714 self.wait_fw_screen_and_close_lid()
715
716
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800717 def setup_tried_fwb(self, tried_fwb):
718 """Setup for fw B tried state.
719
720 It makes sure the system in the requested fw B tried state. If not, it
721 tries to do so.
722
723 Args:
724 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
725 """
726 if tried_fwb:
727 if not self.crossystem_checker({'tried_fwb': '1'}):
728 logging.info(
729 'Firmware is not booted with tried_fwb. Reboot into it.')
730 self.run_faft_step({
731 'userspace_action': self.faft_client.set_try_fw_b,
732 })
733 else:
734 if not self.crossystem_checker({'tried_fwb': '0'}):
735 logging.info(
736 'Firmware is booted with tried_fwb. Reboot to clear.')
737 self.run_faft_step({})
738
739
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800740 def enable_rec_mode_and_reboot(self):
741 """Switch to rec mode and reboot.
742
743 This method emulates the behavior of the old physical recovery switch,
744 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
745 recovery mode, i.e. just press Power + Esc + Refresh.
746 """
747 self.servo.enable_recovery_mode()
748 self.cold_reboot()
749 time.sleep(self.EC_REBOOT_DELAY)
750 self.servo.disable_recovery_mode()
751
752
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800753 def enable_dev_mode_and_reboot(self):
754 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800755 if self.client_attr.keyboard_dev:
756 self.enable_keyboard_dev_mode()
757 else:
758 self.servo.enable_development_mode()
759 self.faft_client.run_shell_command(
760 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800761
762
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800763 def enable_normal_mode_and_reboot(self):
764 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800765 if self.client_attr.keyboard_dev:
766 self.disable_keyboard_dev_mode()
767 else:
768 self.servo.disable_development_mode()
769 self.faft_client.run_shell_command(
770 'chromeos-firmwareupdate --mode tonormal && reboot')
771
772
773 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
774 """Wait for firmware screen and then switch into or out of dev mode.
775
776 Args:
777 dev: True if switching into dev mode. Otherwise, False.
778 """
779 time.sleep(self.FIRMWARE_SCREEN_DELAY)
780 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800781 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800782 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800783 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800784 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800785 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800786
787
788 def enable_keyboard_dev_mode(self):
789 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800790 # Plug out USB disk for preventing recovery boot without warning
791 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800792 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800793 self.enable_rec_mode_and_reboot()
Vic Yange7553162012-06-20 16:20:47 +0800794 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800795
796
797 def disable_keyboard_dev_mode(self):
798 logging.info("Disabling keyboard controlled developer mode")
799 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800800 self.cold_reboot()
Vic Yange7553162012-06-20 16:20:47 +0800801 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800802
803
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800804 def setup_dev_mode(self, dev_mode):
805 """Setup for development mode.
806
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800807 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800808 tries to do so.
809
810 Args:
811 dev_mode: True if requested in dev mode; False if normal mode.
812 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800813 # Change the default firmware_action for dev mode passing the fw screen.
814 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800815 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
816 else None),
817 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800818 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800819 if (not self.client_attr.keyboard_dev and
820 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800821 logging.info('Dev switch is not on. Now switch it on.')
822 self.servo.enable_development_mode()
823 if not self.crossystem_checker({'devsw_boot': '1',
824 'mainfw_type': 'developer'}):
825 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800826 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800827 'userspace_action': None if self.client_attr.keyboard_dev
828 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800829 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800830 'reboot_action': self.enable_keyboard_dev_mode if
831 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800832 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800833 else:
Vic Yange7553162012-06-20 16:20:47 +0800834 if (not self.client_attr.keyboard_dev and
835 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800836 logging.info('Dev switch is not off. Now switch it off.')
837 self.servo.disable_development_mode()
838 if not self.crossystem_checker({'devsw_boot': '0',
839 'mainfw_type': 'normal'}):
840 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800841 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800842 'userspace_action': None if self.client_attr.keyboard_dev
843 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800844 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800845 'reboot_action': self.disable_keyboard_dev_mode if
846 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800847 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800848
849
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800850 def setup_kernel(self, part):
851 """Setup for kernel test.
852
853 It makes sure both kernel A and B bootable and the current boot is
854 the requested kernel part.
855
856 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800857 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800858 """
859 self.ensure_kernel_boot(part)
860 self.copy_kernel_and_rootfs(from_part=part,
861 to_part=self.OTHER_KERNEL_MAP[part])
862 self.reset_and_prioritize_kernel(part)
863
864
865 def reset_and_prioritize_kernel(self, part):
866 """Make the requested partition highest priority.
867
868 This function also reset kerenl A and B to bootable.
869
870 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800871 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800872 """
873 root_dev = self.faft_client.get_root_dev()
874 # Reset kernel A and B to bootable.
875 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
876 (self.KERNEL_MAP['a'], root_dev))
877 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
878 (self.KERNEL_MAP['b'], root_dev))
879 # Set kernel part highest priority.
880 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
881 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800882 # Safer to sync and wait until the cgpt status written to the disk.
883 self.faft_client.run_shell_command('sync')
884 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800885
886
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800887 def warm_reboot(self):
888 """Request a warm reboot.
889
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800890 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800891 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800892 # Use cold reset if the warm reset is broken.
893 if self.client_attr.broken_warm_reset:
894 self.servo.cold_reset()
895 else:
896 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800897
898
899 def cold_reboot(self):
900 """Request a cold reboot.
901
902 A wrapper for underlying servo cold reset.
903 """
904 if self.check_ec_capability():
905 # We don't use servo.cold_reset() here because software sync is
906 # not yet finished, and device may or may not come up after cold
907 # reset. Pressing power button before firmware comes up solves this.
908 #
909 # The correct behavior should be (not work now):
910 # - If rebooting EC with rec mode on, power on AP and it boots
911 # into recovery mode.
912 # - If rebooting EC with rec mode off, power on AP for software
913 # sync. Then AP checks if lid open or not. If lid open, continue;
914 # otherwise, shut AP down and need servo for a power button
915 # press.
916 self.servo.set('cold_reset', 'on')
917 self.servo.set('cold_reset', 'off')
918 time.sleep(self.POWER_BTN_DELAY)
919 self.servo.power_short_press()
920 else:
921 self.servo.cold_reset()
922
923
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800924 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800925 """Request the client sync and do a warm reboot.
926
927 This is the default reboot action on FAFT.
928 """
929 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800930 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800931 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +0800932
933
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800934 def sync_and_cold_reboot(self):
935 """Request the client sync and do a cold reboot.
936
937 This reboot action is used to reset EC for recovery mode.
938 """
939 self.faft_client.run_shell_command('sync')
940 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800941 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800942
943
Vic Yang59cac9c2012-05-21 15:28:42 +0800944 def sync_and_ec_reboot(self):
945 """Request the client sync and do a EC triggered reboot."""
946 self.faft_client.run_shell_command('sync')
947 time.sleep(self.SYNC_DELAY)
948 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
949 self.EC_REBOOT_DELAY)
Vic Yangf86728a2012-07-30 10:44:07 +0800950 time.sleep(self.EC_REBOOT_DELAY)
951 self.check_lid_and_power_on()
952
953
954 def check_lid_and_power_on(self):
955 """
956 On devices with EC software sync, system powers on after EC reboots if
957 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
958 This method checks lid switch state and presses power button if
959 necessary.
960 """
961 if self.servo.get("lid_open") == "no":
962 time.sleep(self.SOFTWARE_SYNC_DELAY)
963 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +0800964
965
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800966 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
967 """Modify the kernel header magic in USB stick.
968
969 The kernel header magic is the first 8-byte of kernel partition.
970 We modify it to make it fail on kernel verification check.
971
972 Args:
973 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
974 from_magic: A string of magic which we change it from.
975 to_magic: A string of magic which we change it to.
976
977 Raises:
978 error.TestError: if failed to change magic.
979 """
980 assert len(from_magic) == 8
981 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +0800982 # USB image only contains one kernel.
983 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800984 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
985 current_magic = utils.system_output(read_cmd)
986 if current_magic == to_magic:
987 logging.info("The kernel magic is already %s." % current_magic)
988 return
989 if current_magic != from_magic:
990 raise error.TestError("Invalid kernel image on USB: wrong magic.")
991
992 logging.info('Modify the kernel magic in USB, from %s to %s.' %
993 (from_magic, to_magic))
994 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
995 " 2>/dev/null" % (to_magic, kernel_part))
996 utils.system(write_cmd)
997
998 if utils.system_output(read_cmd) != to_magic:
999 raise error.TestError("Failed to write new magic.")
1000
1001
1002 def corrupt_usb_kernel(self, usb_dev):
1003 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1004
1005 Args:
1006 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1007 """
1008 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1009 self.CORRUPTED_MAGIC)
1010
1011
1012 def restore_usb_kernel(self, usb_dev):
1013 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1014
1015 Args:
1016 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1017 """
1018 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1019 self.CHROMEOS_MAGIC)
1020
1021
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001022 def _call_action(self, action_tuple):
1023 """Call the action function with/without arguments.
1024
1025 Args:
1026 action_tuple: A function, or a tuple which consisted of a function
1027 and its arguments (if any).
1028
1029 Returns:
1030 The result value of the action function.
1031 """
1032 if isinstance(action_tuple, tuple):
1033 action = action_tuple[0]
1034 args = action_tuple[1:]
1035 if callable(action):
1036 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001037 str(action), str(action_tuple[1])))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001038 return action(*args)
1039 else:
1040 logging.info('action is not callable!')
1041 else:
1042 action = action_tuple
1043 if action is not None:
1044 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001045 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001046 return action()
1047 else:
1048 logging.info('action is not callable!')
1049
1050 return None
1051
1052
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001053 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1054 post_power_action=None):
1055 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1056
1057 Args:
1058 shutdown_action: a function which makes DUT shutdown, like pressing
1059 power key.
1060 pre_power_action: a function which is called before next power on.
1061 post_power_action: a function which is called after next power on.
1062
1063 Raises:
1064 error.TestFail: if the shutdown_action() failed to turn DUT off.
1065 """
1066 self._call_action(shutdown_action)
1067 logging.info('Wait to ensure DUT shut down...')
1068 try:
1069 self.wait_for_client()
1070 raise error.TestFail(
1071 'Should shut the device down after calling %s.' %
1072 str(shutdown_action))
1073 except AssertionError:
1074 logging.info(
1075 'DUT is surely shutdown. We are going to power it on again...')
1076
1077 if pre_power_action:
1078 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001079 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001080 if post_power_action:
1081 self._call_action(post_power_action)
1082
1083
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001084 def register_faft_template(self, template):
1085 """Register FAFT template, the default FAFT_STEP of each step.
1086
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001087 Any missing field falls back to the original faft_template.
1088
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001089 Args:
1090 template: A FAFT_STEP dict.
1091 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001092 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001093
1094
1095 def register_faft_sequence(self, sequence):
1096 """Register FAFT sequence.
1097
1098 Args:
1099 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1100 """
1101 self._faft_sequence = sequence
1102
1103
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001104 def run_faft_step(self, step, no_reboot=False):
1105 """Run a single FAFT step.
1106
1107 Any missing field falls back to faft_template. An empty step means
1108 running the default faft_template.
1109
1110 Args:
1111 step: A FAFT_STEP dict.
1112 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001113
1114 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001115 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001116 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001117 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001118 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1119 'firmware_action', 'install_deps_after_boot')
1120
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001121 test = {}
1122 test.update(self._faft_template)
1123 test.update(step)
1124
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001125 for key in test:
1126 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001127 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001128
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001129 if test['state_checker']:
1130 if not self._call_action(test['state_checker']):
1131 raise error.TestFail('State checker failed!')
1132
1133 self._call_action(test['userspace_action'])
1134
1135 # Don't run reboot_action and firmware_action if no_reboot is True.
1136 if not no_reboot:
1137 self._call_action(test['reboot_action'])
1138 self.wait_for_client_offline()
1139 self._call_action(test['firmware_action'])
1140
1141 if 'install_deps_after_boot' in test:
1142 self.wait_for_client(
1143 install_deps=test['install_deps_after_boot'])
1144 else:
1145 self.wait_for_client()
1146
1147
1148 def run_faft_sequence(self):
1149 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001150 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001151 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001152 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001153 logging.info('======== Running FAFT sequence step %d ========' %
1154 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001155 # Don't reboot in the last step.
1156 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001157 index += 1