blob: 80677b798e75bf76daa4a4aca97e33dd49c14e4a [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
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +08005import ctypes
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08006import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08007import os
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08008import re
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +08009import subprocess
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080010import sys
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080011import time
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080013from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080014from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +080015from autotest_lib.server.cros import vboot_constants as vboot
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +080016from autotest_lib.server.cros.chrome_ec import ChromeEC
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 Tam08885ae2012-10-19 17:16:45 +080020from autotest_lib.site_utils.chromeos_test.common_util import ChromeOSTestError
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080021
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080022dirname = os.path.dirname(sys.modules[__name__].__file__)
23autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
24cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080025
26class FAFTSequence(ServoTest):
27 """
28 The base class of Fully Automated Firmware Test Sequence.
29
30 Many firmware tests require several reboot cycles and verify the resulted
31 system states. To do that, an Autotest test case should detailly handle
32 every action on each step. It makes the test case hard to read and many
33 duplicated code. The base class FAFTSequence is to solve this problem.
34
35 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
36 There are four functions in the FAFT_STEP dict:
37 state_checker: a function to check the current is valid or not,
38 returning True if valid, otherwise, False to break the whole
39 test sequence.
40 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080041 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080042 firmware_action: a function to describe the action ran after reboot.
43
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080044 And configurations:
45 install_deps_after_boot: if True, install the Autotest dependency after
46 boot; otherwise, do nothing. It is for the cases of recovery mode
47 test. The test boots a USB/SD image instead of an internal image.
48 The previous installed Autotest dependency on the internal image
49 is lost. So need to install it again.
50
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080051 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080052 userspace_action and firmware_action. Its reboot_action is a hardware
53 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080054 self.register_faft_template(FAFT_STEP).
55
56 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
57 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
58 fall back to default.
59
60 In the run_once(), it should register and run FAFT_SEQUENCE like:
61 def run_once(self):
62 self.register_faft_sequence(FAFT_SEQUENCE)
63 self.run_faft_sequnce()
64
65 Note that in the last step, we only run state_checker. The
66 userspace_action, reboot_action, and firmware_action are not executed.
67
68 Attributes:
69 _faft_template: The default FAFT_STEP of each step. The actions would
70 be over-written if the registered FAFT_SEQUENCE is valid.
71 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +080072 _customized_key_commands: The dict of the customized key commands,
73 including Ctrl-D, Ctrl-U, Enter, Space, and recovery reboot.
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +080074 _install_image_path: The URL or the path on the host to the Chrome OS
75 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 Tam4bb85e22012-10-25 14:35:24 +080078 _trapped_in_recovery_reason: Keep the recovery reason when the test is
79 trapped in the recovery screen.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080080 """
81 version = 1
82
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080083 # Mapping of partition number of kernel and rootfs.
84 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
85 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
86 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
87 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
88
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080089 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080090 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080091 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080092 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +080093 # Delay for waiting beep done.
94 BEEP_DELAY = 1
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080096 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080097 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080098 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080099 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800100 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +0800101 # Delay for waiting client to return before EC reboot
102 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800103 # Delay for waiting client to full power off
104 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800105 # Delay between EC reboot and pressing power button
106 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800107 # Delay of EC software sync hash calculating time
108 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800109 # Delay between EC boot and ChromeEC console functional
110 EC_BOOT_DELAY = 0.5
111 # Duration of holding cold_reset to reset device
112 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800113 # devserver startup time
114 DEVSERVER_DELAY = 10
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800115
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800116 # The developer screen timeouts fit our spec.
117 DEV_SCREEN_TIMEOUT = 30
118
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800119 CHROMEOS_MAGIC = "CHROMEOS"
120 CORRUPTED_MAGIC = "CORRUPTD"
121
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800122 _HTTP_PREFIX = 'http://'
123 _DEVSERVER_PORT = '8090'
124
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800125 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800126 _faft_sequence = ()
127
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800128 _customized_key_commands = {
129 'ctrl_d': None,
130 'ctrl_u': None,
131 'enter': None,
132 'rec_reboot': None,
133 'space': None,
134 }
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800135 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800136 _firmware_update = False
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +0800137 _trapped_in_recovery_reason = 0
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800138
ctchang38ae4922012-09-03 17:01:16 +0800139 _backup_firmware_sha = ()
140
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800141 # Class level variable, keep track the states of one time setup.
142 # This variable is preserved across tests which inherit this class.
143 _global_setup_done = {
144 'gbb_flags': False,
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800145 'reimage': False,
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800146 'usb_check': False,
147 }
Vic Yang54f70572012-10-19 17:05:26 +0800148
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800149 @classmethod
150 def check_setup_done(cls, label):
151 """Check if the given setup is done.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800152
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800153 Args:
154 label: The label of the setup.
155 """
156 return cls._global_setup_done[label]
157
158
159 @classmethod
160 def mark_setup_done(cls, label):
161 """Mark the given setup done.
162
163 Args:
164 label: The label of the setup.
165 """
166 cls._global_setup_done[label] = True
167
168
169 @classmethod
170 def unmark_setup_done(cls, label):
171 """Mark the given setup not done.
172
173 Args:
174 label: The label of the setup.
175 """
176 cls._global_setup_done[label] = False
Vic Yang54f70572012-10-19 17:05:26 +0800177
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800178
179 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
180 # Parse arguments from command line
181 args = {}
182 for arg in cmdline_args:
183 match = re.search("^(\w+)=(.+)", arg)
184 if match:
185 args[match.group(1)] = match.group(2)
186
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800187 # Keep the arguments which will be used later.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800188 for key in self._customized_key_commands:
189 key_cmd = key + '_cmd'
190 if key_cmd in args:
191 self._customized_key_commands[key] = args[key_cmd]
192 logging.info('Customized %s key command: %s' %
193 (key, args[key_cmd]))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800194 if 'image' in args:
195 self._install_image_path = args['image']
196 logging.info('Install Chrome OS test image path: %s' %
197 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800198 if 'firmware_update' in args and args['firmware_update'].lower() \
199 not in ('0', 'false', 'no'):
200 if self._install_image_path:
201 self._firmware_update = True
202 logging.info('Also update firmware after installing.')
203 else:
204 logging.warning('Firmware update will not not performed '
205 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800206
207 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
208 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800209 if use_faft:
210 self.client_attr = FAFTClientAttribute(
211 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800212
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800213 if self.client_attr.chrome_ec:
214 self.ec = ChromeEC(self.servo)
215
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700216 # Setting up key matrix mapping
217 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
218
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800219
220 def setup(self):
221 """Autotest setup function."""
222 super(FAFTSequence, self).setup()
223 if not self._remote_infos['faft']['used']:
224 raise error.TestError('The use_faft flag should be enabled.')
225 self.register_faft_template({
226 'state_checker': (None),
227 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800228 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800229 'firmware_action': (None)
230 })
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800231 self.install_test_image(self._install_image_path, self._firmware_update)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800232 self.setup_gbb_flags()
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800233
234
235 def cleanup(self):
236 """Autotest cleanup function."""
237 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800238 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800239 super(FAFTSequence, self).cleanup()
240
241
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800242 def invalidate_firmware_setup(self):
243 """Invalidate all firmware related setup state.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800244
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800245 This method is called when the firmware is re-flashed. It resets all
246 firmware related setup states so that the next test setup properly
247 again.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800248 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800249 self.unmark_setup_done('gbb_flags')
Vic Yangdbaba8f2012-10-17 16:05:35 +0800250
251
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800252 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800253 """Reset client, if necessary.
254
255 This method is called when the client is not responsive. It may be
256 caused by the following cases:
257 - network flaky (can be recovered by replugging the Ethernet);
258 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
259 - corrupted firmware;
260 - corrutped OS image.
261 """
262 # DUT works fine, done.
263 if self._ping_test(self._client.ip, timeout=5):
264 return
265
266 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
267 # first reset item.
268
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +0800269 # DUT may be trapped in the recovery screen. Try to boot into USB to
270 # retrieve the recovery reason.
271 logging.info('Try to retrieve recovery reason...')
272 if self.servo.get('usb_mux_sel1') == 'dut_sees_usbkey':
273 self.wait_fw_screen_and_plug_usb()
274 else:
275 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
276
277 try:
278 self.wait_for_client(install_deps=True)
279 lines = self.faft_client.run_shell_command_get_output(
280 'crossystem recovery_reason')
281 self._trapped_in_recovery_reason = int(lines[0])
282 logging.info('Got the recovery reason %d.' %
283 self._trapped_in_recovery_reason)
284 except AssertionError:
285 logging.info('Failed to get the recovery reason.')
286
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800287 # DUT may halt on a firmware screen. Try cold reboot.
288 logging.info('Try cold reboot...')
289 self.cold_reboot()
290 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800291 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800292 return
293 except AssertionError:
294 pass
295
296 # DUT may be broken by a corrupted firmware. Restore firmware.
297 # We assume the recovery boot still works fine. Since the recovery
298 # code is in RO region and all FAFT tests don't change the RO region
299 # except GBB.
300 if self.is_firmware_saved():
301 self.ensure_client_in_recovery()
302 logging.info('Try restore the original firmware...')
303 if self.is_firmware_changed():
304 try:
305 self.restore_firmware()
306 return
307 except AssertionError:
308 logging.info('Restoring firmware doesn\'t help.')
309
310 # DUT may be broken by a corrupted OS image. Restore OS image.
311 self.ensure_client_in_recovery()
312 logging.info('Try restore the OS image...')
313 self.faft_client.run_shell_command('chromeos-install --yes')
314 self.sync_and_warm_reboot()
315 self.wait_for_client_offline()
316 try:
317 self.wait_for_client(install_deps=True)
318 logging.info('Successfully restore OS image.')
319 return
320 except AssertionError:
321 logging.info('Restoring OS image doesn\'t help.')
322
323
324 def ensure_client_in_recovery(self):
325 """Ensure client in recovery boot; reboot into it if necessary.
326
327 Raises:
328 error.TestError: if failed to boot the USB image.
329 """
330 # DUT works fine and is already in recovery boot, done.
331 if self._ping_test(self._client.ip, timeout=5):
332 if self.crossystem_checker({'mainfw_type': 'recovery'}):
333 return
334
335 logging.info('Try boot into USB image...')
336 self.servo.enable_usb_hub(host=True)
337 self.enable_rec_mode_and_reboot()
338 self.wait_fw_screen_and_plug_usb()
339 try:
340 self.wait_for_client(install_deps=True)
341 except AssertionError:
342 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800343
344
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800345 def assert_test_image_in_path(self, image_path):
346 """Assert the image of image_path be a Chrome OS test image.
347
348 Args:
349 image_path: A path on the host to the test image.
350
351 Raises:
352 error.TestError: if the image is not a test image.
353 """
354 try:
355 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
356 image_path)
357 logging.info('Build of image: %s %s' % (build_ver, build_hash))
358 except ChromeOSTestError:
359 raise error.TestError(
360 'An USB disk containning a test image should be plugged '
361 'in the servo board.')
362
363
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800364 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800365 """Assert an USB disk plugged-in on servo and a test image inside.
366
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800367 Args:
368 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
369 If None, it is detected automatically.
370
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800371 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800372 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800373 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800374 if self.check_setup_done('usb_check'):
Vic Yang54f70572012-10-19 17:05:26 +0800375 return
376
Tom Wai-Hong Tam1c86c7a2012-10-22 10:08:24 +0800377 # TODO(waihong@chromium.org): We skip the check when servod runs in
378 # a different host since no easy way to access the servo host so far.
379 # Should find a way to work-around it.
380 if not self.servo.is_localhost():
381 logging.info('Skip checking Chrome OS test image in USB as servod '
382 'runs in a different host.')
383 return
384
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800385 if usb_dev:
386 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
387 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700388 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800389 usb_dev = self.servo.probe_host_usb_dev()
390 if not usb_dev:
391 raise error.TestError(
392 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800393 self.assert_test_image_in_path(usb_dev)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800394 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800395
396
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800397 def get_server_address(self):
398 """Get the server address seen from the client.
399
400 Returns:
401 A string of the server address.
402 """
403 r = self.faft_client.run_shell_command_get_output("echo $SSH_CLIENT")
404 return r[0].split()[0]
405
406
Simran Basi741b5d42012-05-18 11:27:15 -0700407 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800408 """Install the test image specied by the path onto the USB and DUT disk.
409
410 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500411 recovery mode. Then runs 'chromeos-install' (and possible
412 chromeos-firmwareupdate') to install it to DUT disk.
413
414 Sample command line:
415
416 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
417 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
418 server/site_tests/firmware_XXXX/control
419
420 This test requires an automated recovery to occur while simulating
421 inserting and removing the usb key from the servo. To allow this the
422 following hardware setup is required:
423 1. servo2 board connected via servoflex.
424 2. USB key inserted in the servo2.
425 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
426 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800427
428 Args:
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800429 image_path: An URL or a path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800430 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800431
432 Raises:
433 error.TestError: If devserver failed to start.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800434 """
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800435 if not image_path:
436 return
437
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800438 if self.check_setup_done('reimage'):
439 return
440
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800441 if image_path.startswith(self._HTTP_PREFIX):
442 # TODO(waihong@chromium.org): Add the check of the URL to ensure
443 # it is a test image.
444 devserver = None
445 image_url = image_path
Tom Wai-Hong Tam42f136d2012-10-26 11:11:23 +0800446 elif self.servo.is_localhost():
447 self.assert_test_image_in_path(image_path)
448 # If servod is localhost, i.e. both servod and FAFT see the same
449 # file system, do nothing.
450 devserver = None
451 image_url = image_path
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800452 else:
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800453 self.assert_test_image_in_path(image_path)
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800454 image_dir, image_base = os.path.split(image_path)
455 logging.info('Starting devserver to serve the image...')
456 # The following stdout and stderr arguments should not be None,
457 # even we don't use them. Otherwise, the socket of devserve is
458 # created as fd 1 (as no stdout) but it still thinks stdout is fd
459 # 1 and dump the log to the socket. Wrong HTTP protocol happens.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800460 devserver = subprocess.Popen(['/usr/lib/devserver/devserver.py',
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800461 '--archive_dir=%s' % image_dir,
462 '--port=%s' % self._DEVSERVER_PORT],
463 stdout=subprocess.PIPE,
464 stderr=subprocess.PIPE)
465 image_url = '%s%s:%s/static/archive/%s' % (
466 self._HTTP_PREFIX,
467 self.get_server_address(),
468 self._DEVSERVER_PORT,
469 image_base)
470
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800471 # Wait devserver startup completely
472 time.sleep(self.DEVSERVER_DELAY)
473 # devserver is a service running forever. If it is terminated,
474 # some error does happen.
475 if devserver.poll():
476 raise error.TestError('Starting devserver failed, '
477 'returning %d.' % devserver.returncode)
478
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800479 logging.info('Ask Servo to install the image from %s' % image_url)
480 self.servo.image_to_servo_usb(image_url)
481
482 if devserver and devserver.poll() is None:
483 logging.info('Shutting down devserver...')
484 devserver.terminate()
Mike Truty49153d82012-08-21 22:27:30 -0500485
486 # DUT is powered off while imaging servo USB.
487 # Now turn it on.
488 self.servo.power_short_press()
489 self.wait_for_client()
490 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
491
492 install_cmd = 'chromeos-install --yes'
493 if firmware_update:
494 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
495
496 self.register_faft_sequence((
497 { # Step 1, request recovery boot
498 'state_checker': (self.crossystem_checker, {
499 'mainfw_type': ('developer', 'normal'),
500 }),
501 'userspace_action': self.faft_client.request_recovery_boot,
502 'firmware_action': self.wait_fw_screen_and_plug_usb,
503 'install_deps_after_boot': True,
504 },
505 { # Step 2, expected recovery boot
506 'state_checker': (self.crossystem_checker, {
507 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800508 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500509 }),
510 'userspace_action': (self.faft_client.run_shell_command,
511 install_cmd),
512 'reboot_action': self.cold_reboot,
513 'install_deps_after_boot': True,
514 },
515 { # Step 3, expected normal or developer boot (not recovery)
516 'state_checker': (self.crossystem_checker, {
517 'mainfw_type': ('developer', 'normal')
518 }),
519 },
520 ))
521 self.run_faft_sequence()
522 # 'Unplug' any USB keys in the servo from the dut.
Tom Wai-Hong Tam953c7742012-10-16 21:09:31 +0800523 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam6668b762012-10-23 11:45:36 +0800524 # Mark usb_check done so it won't check a test image in USB anymore.
525 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800526 self.mark_setup_done('reimage')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800527
528
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800529 def clear_set_gbb_flags(self, clear_mask, set_mask):
530 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800531
532 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800533 clear_mask: A mask of flags to be cleared.
534 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800535 """
536 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800537 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
538
539 if (gbb_flags != new_flags):
540 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
541 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800542 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800543 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800544 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800545 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800546 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800547 self.run_faft_step({
548 'firmware_action': self.wait_fw_screen_and_ctrl_d,
549 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800550
551
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800552 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800553 """Check if current platform has required EC capabilities.
554
555 Args:
556 required_cap: A list containing required EC capabilities. Pass in
557 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800558 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800559
560 Returns:
561 True if requirements are met. Otherwise, False.
562 """
563 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800564 if not suppress_warning:
565 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800566 return False
567
568 for cap in required_cap:
569 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800570 if not suppress_warning:
571 logging.warn('Requires EC capability "%s" to run this '
572 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800573 return False
574
575 return True
576
577
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800578 def _parse_crossystem_output(self, lines):
579 """Parse the crossystem output into a dict.
580
581 Args:
582 lines: The list of crossystem output strings.
583
584 Returns:
585 A dict which contains the crossystem keys/values.
586
587 Raises:
588 error.TestError: If wrong format in crossystem output.
589
590 >>> seq = FAFTSequence()
591 >>> seq._parse_crossystem_output([ \
592 "arch = x86 # Platform architecture", \
593 "cros_debug = 1 # OS should allow debug", \
594 ])
595 {'cros_debug': '1', 'arch': 'x86'}
596 >>> seq._parse_crossystem_output([ \
597 "arch=x86", \
598 ])
599 Traceback (most recent call last):
600 ...
601 TestError: Failed to parse crossystem output: arch=x86
602 >>> seq._parse_crossystem_output([ \
603 "arch = x86 # Platform architecture", \
604 "arch = arm # Platform architecture", \
605 ])
606 Traceback (most recent call last):
607 ...
608 TestError: Duplicated crossystem key: arch
609 """
610 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
611 parsed_list = {}
612 for line in lines:
613 matched = re.match(pattern, line.strip())
614 if not matched:
615 raise error.TestError("Failed to parse crossystem output: %s"
616 % line)
617 (name, value) = (matched.group(1), matched.group(2))
618 if name in parsed_list:
619 raise error.TestError("Duplicated crossystem key: %s" % name)
620 parsed_list[name] = value
621 return parsed_list
622
623
624 def crossystem_checker(self, expected_dict):
625 """Check the crossystem values matched.
626
627 Given an expect_dict which describes the expected crossystem values,
628 this function check the current crossystem values are matched or not.
629
630 Args:
631 expected_dict: A dict which contains the expected values.
632
633 Returns:
634 True if the crossystem value matched; otherwise, False.
635 """
636 lines = self.faft_client.run_shell_command_get_output('crossystem')
637 got_dict = self._parse_crossystem_output(lines)
638 for key in expected_dict:
639 if key not in got_dict:
640 logging.info('Expected key "%s" not in crossystem result' % key)
641 return False
642 if isinstance(expected_dict[key], str):
643 if got_dict[key] != expected_dict[key]:
644 logging.info("Expected '%s' value '%s' but got '%s'" %
645 (key, expected_dict[key], got_dict[key]))
646 return False
647 elif isinstance(expected_dict[key], tuple):
648 # Expected value is a tuple of possible actual values.
649 if got_dict[key] not in expected_dict[key]:
650 logging.info("Expected '%s' values %s but got '%s'" %
651 (key, str(expected_dict[key]), got_dict[key]))
652 return False
653 else:
654 logging.info("The expected_dict is neither a str nor a dict.")
655 return False
656 return True
657
658
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800659 def vdat_flags_checker(self, mask, value):
660 """Check the flags from VbSharedData matched.
661
662 This function checks the masked flags from VbSharedData using crossystem
663 are matched the given value.
664
665 Args:
666 mask: A bitmask of flags to be matched.
667 value: An expected value.
668
669 Returns:
670 True if the flags matched; otherwise, False.
671 """
672 lines = self.faft_client.run_shell_command_get_output(
673 'crossystem vdat_flags')
674 vdat_flags = int(lines[0], 16)
675 if vdat_flags & mask != value:
676 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
677 (value, mask, vdat_flags))
678 return False
679 return True
680
681
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800682 def ro_normal_checker(self, expected_fw=None, twostop=False):
683 """Check the current boot uses RO boot.
684
685 Args:
686 expected_fw: A string of expected firmware, 'A', 'B', or
687 None if don't care.
688 twostop: True to expect a TwoStop boot; False to expect a RO boot.
689
690 Returns:
691 True if the currect boot firmware matched and used RO boot;
692 otherwise, False.
693 """
694 crossystem_dict = {'tried_fwb': '0'}
695 if expected_fw:
696 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800697 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800698 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
699
700 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800701 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
702 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800703 self.crossystem_checker(crossystem_dict))
704
705
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +0800706 def dev_boot_usb_checker(self, dev_boot_usb=True):
707 """Check the current boot is from a developer USB (Ctrl-U trigger).
708
709 Args:
710 dev_boot_usb: True to expect an USB boot;
711 False to expect an internal device boot.
712
713 Returns:
714 True if the currect boot device matched; otherwise, False.
715 """
716 return (self.crossystem_checker({'mainfw_type': 'developer'})
717 and self.faft_client.is_removable_device_boot() == dev_boot_usb)
718
719
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800720 def root_part_checker(self, expected_part):
721 """Check the partition number of the root device matched.
722
723 Args:
724 expected_part: A string containing the number of the expected root
725 partition.
726
727 Returns:
728 True if the currect root partition number matched; otherwise, False.
729 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800730 part = self.faft_client.get_root_part()[-1]
731 if self.ROOTFS_MAP[expected_part] != part:
732 logging.info("Expected root part %s but got %s" %
733 (self.ROOTFS_MAP[expected_part], part))
734 return False
735 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800736
737
Vic Yang59cac9c2012-05-21 15:28:42 +0800738 def ec_act_copy_checker(self, expected_copy):
739 """Check the EC running firmware copy matches.
740
741 Args:
742 expected_copy: A string containing 'RO', 'A', or 'B' indicating
743 the expected copy of EC running firmware.
744
745 Returns:
746 True if the current EC running copy matches; otherwise, False.
747 """
748 lines = self.faft_client.run_shell_command_get_output('ectool version')
749 pattern = re.compile("Firmware copy: (.*)")
750 for line in lines:
751 matched = pattern.match(line)
752 if matched and matched.group(1) == expected_copy:
753 return True
754 return False
755
756
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800757 def check_root_part_on_non_recovery(self, part):
758 """Check the partition number of root device and on normal/dev boot.
759
760 Returns:
761 True if the root device matched and on normal/dev boot;
762 otherwise, False.
763 """
764 return self.root_part_checker(part) and \
765 self.crossystem_checker({
766 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800767 })
768
769
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800770 def _join_part(self, dev, part):
771 """Return a concatenated string of device and partition number.
772
773 Args:
774 dev: A string of device, e.g.'/dev/sda'.
775 part: A string of partition number, e.g.'3'.
776
777 Returns:
778 A concatenated string of device and partition number, e.g.'/dev/sda3'.
779
780 >>> seq = FAFTSequence()
781 >>> seq._join_part('/dev/sda', '3')
782 '/dev/sda3'
783 >>> seq._join_part('/dev/mmcblk0', '2')
784 '/dev/mmcblk0p2'
785 """
786 if 'mmcblk' in dev:
787 return dev + 'p' + part
788 else:
789 return dev + part
790
791
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800792 def copy_kernel_and_rootfs(self, from_part, to_part):
793 """Copy kernel and rootfs from from_part to to_part.
794
795 Args:
796 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800797 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800798 """
799 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800800 logging.info('Copying kernel from %s to %s. Please wait...' %
801 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800802 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800803 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
804 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
805 logging.info('Copying rootfs from %s to %s. Please wait...' %
806 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800807 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800808 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
809 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800810
811
812 def ensure_kernel_boot(self, part):
813 """Ensure the request kernel boot.
814
815 If not, it duplicates the current kernel to the requested kernel
816 and sets the requested higher priority to ensure it boot.
817
818 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800819 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800820 """
821 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800822 if self.faft_client.diff_kernel_a_b():
823 self.copy_kernel_and_rootfs(
824 from_part=self.OTHER_KERNEL_MAP[part],
825 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800826 self.run_faft_step({
827 'userspace_action': (self.reset_and_prioritize_kernel, part),
828 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800829
830
Vic Yang416f2032012-08-28 10:18:03 +0800831 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800832 """Set hardware write protect pin.
833
834 Args:
835 enable: True if asserting write protect pin. Otherwise, False.
836 """
837 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
838 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800839 self.servo.set('fw_wp', 'on' if enabled else 'off')
840
841
842 def set_EC_write_protect_and_reboot(self, enabled):
843 """Set EC write protect status and reboot to take effect.
844
845 EC write protect is only activated if both hardware write protect pin
846 is asserted and software write protect flag is set. Also, a reboot is
847 required for write protect to take effect.
848
849 Since the software write protect flag cannot be unset if hardware write
850 protect pin is asserted, we need to deasserted the pin first if we are
851 deactivating write protect. Similarly, a reboot is required before we
852 can modify the software flag.
853
854 This method asserts/deasserts hardware write protect pin first, and
855 set corresponding EC software write protect flag.
856
857 Args:
858 enable: True if activating EC write protect. Otherwise, False.
859 """
860 self.set_hardware_write_protect(enabled)
861 if enabled:
862 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800863 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800864 self.sync_and_ec_reboot()
865 else:
866 # Reboot after deasserting hardware write protect pin to deactivate
867 # write protect. And then remove software write protect flag.
868 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800869 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800870
871
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800872 def send_ctrl_d_to_dut(self):
873 """Send Ctrl-D key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800874 if self._customized_key_commands['ctrl_d']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800875 logging.info('running the customized Ctrl-D key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800876 os.system(self._customized_key_commands['ctrl_d'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800877 else:
878 self.servo.ctrl_d()
879
880
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800881 def send_ctrl_u_to_dut(self):
882 """Send Ctrl-U key to DUT.
883
884 Raises:
885 error.TestError: if a non-Chrome EC device or no Ctrl-U command given
886 on a no-build-in-keyboard device.
887 """
888 if self._customized_key_commands['ctrl_u']:
889 logging.info('running the customized Ctrl-U key command')
890 os.system(self._customized_key_commands['ctrl_u'])
891 elif self.check_ec_capability(['keyboard'], suppress_warning=True):
892 self.ec.key_down('<ctrl_l>')
893 self.ec.key_down('u')
894 self.ec.key_up('u')
895 self.ec.key_up('<ctrl_l>')
896 elif self.client_attr.has_keyboard:
897 raise error.TestError(
898 "Can't send Ctrl-U to DUT without using Chrome EC.")
899 else:
900 raise error.TestError(
901 "Should specify the ctrl_u_cmd argument.")
902
903
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800904 def send_enter_to_dut(self):
905 """Send Enter key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800906 if self._customized_key_commands['enter']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800907 logging.info('running the customized Enter key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800908 os.system(self._customized_key_commands['enter'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800909 else:
910 self.servo.enter_key()
911
912
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800913 def send_space_to_dut(self):
914 """Send Space key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800915 if self._customized_key_commands['space']:
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800916 logging.info('running the customized Space key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800917 os.system(self._customized_key_commands['space'])
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800918 else:
919 # Send the alternative key combinaton of space key to servo.
920 self.servo.ctrl_refresh_key()
921
922
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800923 def wait_fw_screen_and_ctrl_d(self):
924 """Wait for firmware warning screen and press Ctrl-D."""
925 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800926 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800927
928
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800929 def wait_fw_screen_and_ctrl_u(self):
930 """Wait for firmware warning screen and press Ctrl-U."""
931 time.sleep(self.FIRMWARE_SCREEN_DELAY)
932 self.send_ctrl_u_to_dut()
933
934
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800935 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
936 """Wait for firmware warning screen and trigger recovery boot."""
937 time.sleep(self.FIRMWARE_SCREEN_DELAY)
938 self.send_enter_to_dut()
939
940 # For Alex/ZGB, there is a dev warning screen in text mode.
941 # Skip it by pressing Ctrl-D.
942 if need_dev_transition:
943 time.sleep(self.TEXT_SCREEN_DELAY)
944 self.send_ctrl_d_to_dut()
945
946
Mike Truty49153d82012-08-21 22:27:30 -0500947 def wait_fw_screen_and_unplug_usb(self):
948 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800949 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800950 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
951 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500952
953
954 def wait_fw_screen_and_plug_usb(self):
955 """Wait for firmware warning screen and then unplug and plug the USB."""
956 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800957 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
958
959
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800960 def wait_fw_screen_and_press_power(self):
961 """Wait for firmware warning screen and press power button."""
962 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800963 # While the firmware screen, the power button probing loop sleeps
964 # 0.25 second on every scan. Use the normal delay (1.2 second) for
965 # power press.
966 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800967
968
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800969 def wait_longer_fw_screen_and_press_power(self):
970 """Wait for firmware screen without timeout and press power button."""
971 time.sleep(self.DEV_SCREEN_TIMEOUT)
972 self.wait_fw_screen_and_press_power()
973
974
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800975 def wait_fw_screen_and_close_lid(self):
976 """Wait for firmware warning screen and close lid."""
977 time.sleep(self.FIRMWARE_SCREEN_DELAY)
978 self.servo.lid_close()
979
980
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800981 def wait_longer_fw_screen_and_close_lid(self):
982 """Wait for firmware screen without timeout and close lid."""
983 time.sleep(self.FIRMWARE_SCREEN_DELAY)
984 self.wait_fw_screen_and_close_lid()
985
986
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800987 def setup_gbb_flags(self):
988 """Setup the GBB flags for FAFT test."""
989 if self.check_setup_done('gbb_flags'):
990 return
991
992 logging.info('Set proper GBB flags for test.')
993 self.clear_set_gbb_flags(vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY |
994 vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
995 vboot.GBB_FLAG_FORCE_DEV_BOOT_USB |
996 vboot.GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK,
997 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
998 self.mark_setup_done('gbb_flags')
999
1000
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001001 def setup_tried_fwb(self, tried_fwb):
1002 """Setup for fw B tried state.
1003
1004 It makes sure the system in the requested fw B tried state. If not, it
1005 tries to do so.
1006
1007 Args:
1008 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
1009 """
1010 if tried_fwb:
1011 if not self.crossystem_checker({'tried_fwb': '1'}):
1012 logging.info(
1013 'Firmware is not booted with tried_fwb. Reboot into it.')
1014 self.run_faft_step({
1015 'userspace_action': self.faft_client.set_try_fw_b,
1016 })
1017 else:
1018 if not self.crossystem_checker({'tried_fwb': '0'}):
1019 logging.info(
1020 'Firmware is booted with tried_fwb. Reboot to clear.')
1021 self.run_faft_step({})
1022
1023
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001024 def enable_rec_mode_and_reboot(self):
1025 """Switch to rec mode and reboot.
1026
1027 This method emulates the behavior of the old physical recovery switch,
1028 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
1029 recovery mode, i.e. just press Power + Esc + Refresh.
1030 """
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +08001031 if self._customized_key_commands['rec_reboot']:
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001032 logging.info('running the customized rec reboot command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +08001033 os.system(self._customized_key_commands['rec_reboot'])
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001034 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +08001035 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +08001036 self.servo.set('cold_reset', 'on')
1037 time.sleep(self.COLD_RESET_DELAY)
1038 self.servo.set('cold_reset', 'off')
1039 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +08001040 self.ec.send_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +08001041 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +08001042 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +08001043 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001044 else:
1045 self.servo.enable_recovery_mode()
1046 self.cold_reboot()
1047 time.sleep(self.EC_REBOOT_DELAY)
1048 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001049
1050
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001051 def enable_dev_mode_and_reboot(self):
1052 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001053 if self.client_attr.keyboard_dev:
1054 self.enable_keyboard_dev_mode()
1055 else:
1056 self.servo.enable_development_mode()
1057 self.faft_client.run_shell_command(
1058 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001059
1060
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001061 def enable_normal_mode_and_reboot(self):
1062 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001063 if self.client_attr.keyboard_dev:
1064 self.disable_keyboard_dev_mode()
1065 else:
1066 self.servo.disable_development_mode()
1067 self.faft_client.run_shell_command(
1068 'chromeos-firmwareupdate --mode tonormal && reboot')
1069
1070
1071 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
1072 """Wait for firmware screen and then switch into or out of dev mode.
1073
1074 Args:
1075 dev: True if switching into dev mode. Otherwise, False.
1076 """
1077 time.sleep(self.FIRMWARE_SCREEN_DELAY)
1078 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001079 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001080 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001081 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +08001082 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001083 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001084
1085
1086 def enable_keyboard_dev_mode(self):
1087 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001088 # Plug out USB disk for preventing recovery boot without warning
1089 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001090 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001091 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001092 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001093 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001094
1095
1096 def disable_keyboard_dev_mode(self):
1097 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001098 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001099 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001100 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001101 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001102 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001103
1104
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001105 def setup_dev_mode(self, dev_mode):
1106 """Setup for development mode.
1107
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001108 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001109 tries to do so.
1110
1111 Args:
1112 dev_mode: True if requested in dev mode; False if normal mode.
1113 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001114 # Change the default firmware_action for dev mode passing the fw screen.
1115 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001116 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1117 else None),
1118 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001119 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001120 if (not self.client_attr.keyboard_dev and
1121 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001122 logging.info('Dev switch is not on. Now switch it on.')
1123 self.servo.enable_development_mode()
1124 if not self.crossystem_checker({'devsw_boot': '1',
1125 'mainfw_type': 'developer'}):
1126 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001127 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001128 'userspace_action': None if self.client_attr.keyboard_dev
1129 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001130 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001131 'reboot_action': self.enable_keyboard_dev_mode if
1132 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001133 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001134 else:
Vic Yange7553162012-06-20 16:20:47 +08001135 if (not self.client_attr.keyboard_dev and
1136 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001137 logging.info('Dev switch is not off. Now switch it off.')
1138 self.servo.disable_development_mode()
1139 if not self.crossystem_checker({'devsw_boot': '0',
1140 'mainfw_type': 'normal'}):
1141 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001142 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001143 'userspace_action': None if self.client_attr.keyboard_dev
1144 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001145 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001146 'reboot_action': self.disable_keyboard_dev_mode if
1147 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001148 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001149
1150
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001151 def setup_kernel(self, part):
1152 """Setup for kernel test.
1153
1154 It makes sure both kernel A and B bootable and the current boot is
1155 the requested kernel part.
1156
1157 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001158 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001159 """
1160 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001161 if self.faft_client.diff_kernel_a_b():
1162 self.copy_kernel_and_rootfs(from_part=part,
1163 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001164 self.reset_and_prioritize_kernel(part)
1165
1166
1167 def reset_and_prioritize_kernel(self, part):
1168 """Make the requested partition highest priority.
1169
1170 This function also reset kerenl A and B to bootable.
1171
1172 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001173 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001174 """
1175 root_dev = self.faft_client.get_root_dev()
1176 # Reset kernel A and B to bootable.
1177 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1178 (self.KERNEL_MAP['a'], root_dev))
1179 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1180 (self.KERNEL_MAP['b'], root_dev))
1181 # Set kernel part highest priority.
1182 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1183 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001184 # Safer to sync and wait until the cgpt status written to the disk.
1185 self.faft_client.run_shell_command('sync')
1186 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001187
1188
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001189 def warm_reboot(self):
1190 """Request a warm reboot.
1191
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001192 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001193 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001194 # Use cold reset if the warm reset is broken.
1195 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001196 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1197 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001198 else:
1199 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001200
1201
1202 def cold_reboot(self):
1203 """Request a cold reboot.
1204
1205 A wrapper for underlying servo cold reset.
1206 """
Gediminas Ramanauskasc6025692012-10-23 14:33:40 -07001207 if self.client_attr.broken_warm_reset:
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001208 self.servo.set('pwr_button', 'press')
1209 self.servo.set('cold_reset', 'on')
1210 self.servo.set('cold_reset', 'off')
1211 time.sleep(self.POWER_BTN_DELAY)
1212 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001213 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001214 # We don't use servo.cold_reset() here because software sync is
1215 # not yet finished, and device may or may not come up after cold
1216 # reset. Pressing power button before firmware comes up solves this.
1217 #
1218 # The correct behavior should be (not work now):
1219 # - If rebooting EC with rec mode on, power on AP and it boots
1220 # into recovery mode.
1221 # - If rebooting EC with rec mode off, power on AP for software
1222 # sync. Then AP checks if lid open or not. If lid open, continue;
1223 # otherwise, shut AP down and need servo for a power button
1224 # press.
1225 self.servo.set('cold_reset', 'on')
1226 self.servo.set('cold_reset', 'off')
1227 time.sleep(self.POWER_BTN_DELAY)
1228 self.servo.power_short_press()
1229 else:
1230 self.servo.cold_reset()
1231
1232
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001233 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001234 """Request the client sync and do a warm reboot.
1235
1236 This is the default reboot action on FAFT.
1237 """
1238 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001239 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001240 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001241
1242
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001243 def sync_and_cold_reboot(self):
1244 """Request the client sync and do a cold reboot.
1245
1246 This reboot action is used to reset EC for recovery mode.
1247 """
1248 self.faft_client.run_shell_command('sync')
1249 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001250 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001251
1252
Vic Yangaeb10392012-08-28 09:25:09 +08001253 def sync_and_ec_reboot(self, args=''):
1254 """Request the client sync and do a EC triggered reboot.
1255
1256 Args:
1257 args: Arguments passed to "ectool reboot_ec". Including:
1258 RO: jump to EC RO firmware.
1259 RW: jump to EC RW firmware.
1260 cold: Cold/hard reboot.
1261 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001262 self.faft_client.run_shell_command('sync')
1263 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001264 # Since EC reboot happens immediately, delay before actual reboot to
1265 # allow FAFT client returning.
1266 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1267 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001268 time.sleep(self.EC_REBOOT_DELAY)
1269 self.check_lid_and_power_on()
1270
1271
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001272 def full_power_off_and_on(self):
1273 """Shutdown the device by pressing power button and power on again."""
1274 # Press power button to trigger Chrome OS normal shutdown process.
1275 self.servo.power_normal_press()
1276 time.sleep(self.FULL_POWER_OFF_DELAY)
1277 # Short press power button to boot DUT again.
1278 self.servo.power_short_press()
1279
1280
Vic Yangf86728a2012-07-30 10:44:07 +08001281 def check_lid_and_power_on(self):
1282 """
1283 On devices with EC software sync, system powers on after EC reboots if
1284 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1285 This method checks lid switch state and presses power button if
1286 necessary.
1287 """
1288 if self.servo.get("lid_open") == "no":
1289 time.sleep(self.SOFTWARE_SYNC_DELAY)
1290 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001291
1292
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001293 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1294 """Modify the kernel header magic in USB stick.
1295
1296 The kernel header magic is the first 8-byte of kernel partition.
1297 We modify it to make it fail on kernel verification check.
1298
1299 Args:
1300 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1301 from_magic: A string of magic which we change it from.
1302 to_magic: A string of magic which we change it to.
1303
1304 Raises:
1305 error.TestError: if failed to change magic.
1306 """
1307 assert len(from_magic) == 8
1308 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001309 # USB image only contains one kernel.
1310 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001311 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1312 current_magic = utils.system_output(read_cmd)
1313 if current_magic == to_magic:
1314 logging.info("The kernel magic is already %s." % current_magic)
1315 return
1316 if current_magic != from_magic:
1317 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1318
1319 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1320 (from_magic, to_magic))
1321 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1322 " 2>/dev/null" % (to_magic, kernel_part))
1323 utils.system(write_cmd)
1324
1325 if utils.system_output(read_cmd) != to_magic:
1326 raise error.TestError("Failed to write new magic.")
1327
1328
1329 def corrupt_usb_kernel(self, usb_dev):
1330 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1331
1332 Args:
1333 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1334 """
1335 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1336 self.CORRUPTED_MAGIC)
1337
1338
1339 def restore_usb_kernel(self, usb_dev):
1340 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1341
1342 Args:
1343 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1344 """
1345 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1346 self.CHROMEOS_MAGIC)
1347
1348
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001349 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001350 """Call the action function with/without arguments.
1351
1352 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001353 action_tuple: A function, or a tuple (function, args, error_msg),
1354 in which, args and error_msg are optional. args is
1355 either a value or a tuple if multiple arguments.
1356 check_status: Check the return value of action function. If not
1357 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001358
1359 Returns:
1360 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001361
1362 Raises:
1363 error.TestError: An error when the action function is not callable.
1364 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001365 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001366 action = action_tuple
1367 args = ()
1368 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001369 if isinstance(action_tuple, tuple):
1370 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001371 if len(action_tuple) >= 2:
1372 args = action_tuple[1]
1373 if not isinstance(args, tuple):
1374 args = (args,)
1375 if len(action_tuple) >= 3:
Tom Wai-Hong Tamff560882012-10-15 16:50:06 +08001376 error_msg = action_tuple[2]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001377
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001378 if action is None:
1379 return
1380
1381 if not callable(action):
1382 raise error.TestError('action is not callable!')
1383
1384 info_msg = 'calling %s' % str(action)
1385 if args:
1386 info_msg += ' with args %s' % str(args)
1387 logging.info(info_msg)
1388 ret = action(*args)
1389
1390 if check_status and not ret:
1391 raise error.TestFail('%s: %s returning %s' %
1392 (error_msg, info_msg, str(ret)))
1393 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001394
1395
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001396 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1397 post_power_action=None):
1398 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1399
1400 Args:
1401 shutdown_action: a function which makes DUT shutdown, like pressing
1402 power key.
1403 pre_power_action: a function which is called before next power on.
1404 post_power_action: a function which is called after next power on.
1405
1406 Raises:
1407 error.TestFail: if the shutdown_action() failed to turn DUT off.
1408 """
1409 self._call_action(shutdown_action)
1410 logging.info('Wait to ensure DUT shut down...')
1411 try:
1412 self.wait_for_client()
1413 raise error.TestFail(
1414 'Should shut the device down after calling %s.' %
1415 str(shutdown_action))
1416 except AssertionError:
1417 logging.info(
1418 'DUT is surely shutdown. We are going to power it on again...')
1419
1420 if pre_power_action:
1421 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001422 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001423 if post_power_action:
1424 self._call_action(post_power_action)
1425
1426
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001427 def register_faft_template(self, template):
1428 """Register FAFT template, the default FAFT_STEP of each step.
1429
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001430 Any missing field falls back to the original faft_template.
1431
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001432 Args:
1433 template: A FAFT_STEP dict.
1434 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001435 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001436
1437
1438 def register_faft_sequence(self, sequence):
1439 """Register FAFT sequence.
1440
1441 Args:
1442 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1443 """
1444 self._faft_sequence = sequence
1445
1446
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001447 def run_faft_step(self, step, no_reboot=False):
1448 """Run a single FAFT step.
1449
1450 Any missing field falls back to faft_template. An empty step means
1451 running the default faft_template.
1452
1453 Args:
1454 step: A FAFT_STEP dict.
1455 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001456
1457 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001458 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001459 error.TestFail: Test failed in waiting DUT reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001460 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001461 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1462 'firmware_action', 'install_deps_after_boot')
1463
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001464 test = {}
1465 test.update(self._faft_template)
1466 test.update(step)
1467
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001468 for key in test:
1469 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001470 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001471
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001472 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001473 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001474
1475 self._call_action(test['userspace_action'])
1476
1477 # Don't run reboot_action and firmware_action if no_reboot is True.
1478 if not no_reboot:
1479 self._call_action(test['reboot_action'])
1480 self.wait_for_client_offline()
1481 self._call_action(test['firmware_action'])
1482
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001483 try:
1484 if 'install_deps_after_boot' in test:
1485 self.wait_for_client(
1486 install_deps=test['install_deps_after_boot'])
1487 else:
1488 self.wait_for_client()
1489 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001490 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001491 self.reset_client()
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001492 if self._trapped_in_recovery_reason:
1493 raise error.TestFail('Trapped in the recovery reason: %d' %
1494 self._trapped_in_recovery_reason)
1495 else:
1496 raise error.TestFail('Timed out waiting for DUT reboot.')
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001497
1498
1499 def run_faft_sequence(self):
1500 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001501 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001502 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001503 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001504 logging.info('======== Running FAFT sequence step %d ========' %
1505 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001506 # Don't reboot in the last step.
1507 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001508 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001509
1510
ctchang38ae4922012-09-03 17:01:16 +08001511 def get_current_firmware_sha(self):
1512 """Get current firmware sha of body and vblock.
1513
1514 Returns:
1515 Current firmware sha follows the order (
1516 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1517 """
1518 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1519 self.faft_client.get_firmware_sha('a'),
1520 self.faft_client.get_firmware_sig_sha('b'),
1521 self.faft_client.get_firmware_sha('b'))
1522 return current_firmware_sha
1523
1524
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001525 def is_firmware_changed(self):
1526 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001527
1528 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001529 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001530 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001531 # Device may not be rebooted after test.
1532 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001533
1534 current_sha = self.get_current_firmware_sha()
1535
1536 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001537 return False
ctchang38ae4922012-09-03 17:01:16 +08001538 else:
ctchang38ae4922012-09-03 17:01:16 +08001539 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1540 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1541 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1542 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001543 logging.info("Firmware changed:")
1544 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1545 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1546 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1547 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1548 return True
ctchang38ae4922012-09-03 17:01:16 +08001549
1550
1551 def backup_firmware(self, suffix='.original'):
1552 """Backup firmware to file, and then send it to host.
1553
1554 Args:
1555 suffix: a string appended to backup file name
1556 """
1557 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001558 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1559 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1560 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001561
1562 self._backup_firmware_sha = self.get_current_firmware_sha()
1563 logging.info('Backup firmware stored in %s with suffix %s' % (
1564 self.resultsdir, suffix))
1565
1566
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001567 def is_firmware_saved(self):
1568 """Check if a firmware saved (called backup_firmware before).
1569
1570 Returns:
1571 True if the firmware is backuped; otherwise False.
1572 """
1573 return self._backup_firmware_sha != ()
1574
1575
ctchang38ae4922012-09-03 17:01:16 +08001576 def restore_firmware(self, suffix='.original'):
1577 """Restore firmware from host in resultsdir.
1578
1579 Args:
1580 suffix: a string appended to backup file name
1581 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001582 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001583 return
1584
1585 # Backup current corrupted firmware.
1586 self.backup_firmware(suffix='.corrupt')
1587
1588 # Restore firmware.
1589 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001590 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1591 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001592
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001593 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001594 self.sync_and_warm_reboot()
1595 self.wait_for_client_offline()
1596 self.wait_for_client()
1597
ctchang38ae4922012-09-03 17:01:16 +08001598 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001599
1600
1601 def setup_firmwareupdate_shellball(self, shellball=None):
1602 """Deside a shellball to use in firmware update test.
1603
1604 Check if there is a given shellball, and it is a shell script. Then,
1605 send it to the remote host. Otherwise, use
1606 /usr/sbin/chromeos-firmwareupdate.
1607
1608 Args:
1609 shellball: path of a shellball or default to None.
1610
1611 Returns:
1612 Path of shellball in remote host.
1613 If use default shellball, reutrn None.
1614 """
1615 updater_path = None
1616 if shellball:
1617 # Determine the firmware file is a shellball or a raw binary.
1618 is_shellball = (utils.system_output("file %s" % shellball).find(
1619 "shell script") != -1)
1620 if is_shellball:
1621 logging.info('Device will update firmware with shellball %s'
1622 % shellball)
1623 temp_dir = self.faft_client.create_temp_dir('shellball_')
1624 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1625 self._client.send_file(shellball, temp_shellball)
1626 updater_path = temp_shellball
1627 else:
1628 raise error.TestFail(
1629 'The given shellball is not a shell script.')
1630 return updater_path