blob: 60c2ead2b461253938b259298ff90fdc634e1e57 [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
Chun-ting Changa4f65532012-10-17 16:57:28 +0800115 # Delay of reseting TPM with factory install shim
116 RESET_TPM_WITH_INSTALL_SHIM_DELAY = 120
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800117
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800118 # The developer screen timeouts fit our spec.
119 DEV_SCREEN_TIMEOUT = 30
120
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800121 CHROMEOS_MAGIC = "CHROMEOS"
122 CORRUPTED_MAGIC = "CORRUPTD"
123
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800124 _HTTP_PREFIX = 'http://'
125 _DEVSERVER_PORT = '8090'
126
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800127 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800128 _faft_sequence = ()
129
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800130 _customized_key_commands = {
131 'ctrl_d': None,
132 'ctrl_u': None,
133 'enter': None,
134 'rec_reboot': None,
135 'space': None,
136 }
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800137 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800138 _firmware_update = False
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +0800139 _trapped_in_recovery_reason = 0
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800140
ctchang38ae4922012-09-03 17:01:16 +0800141 _backup_firmware_sha = ()
142
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800143 # Class level variable, keep track the states of one time setup.
144 # This variable is preserved across tests which inherit this class.
145 _global_setup_done = {
146 'gbb_flags': False,
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800147 'reimage': False,
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800148 'usb_check': False,
149 }
Vic Yang54f70572012-10-19 17:05:26 +0800150
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800151 @classmethod
152 def check_setup_done(cls, label):
153 """Check if the given setup is done.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800154
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800155 Args:
156 label: The label of the setup.
157 """
158 return cls._global_setup_done[label]
159
160
161 @classmethod
162 def mark_setup_done(cls, label):
163 """Mark the given setup done.
164
165 Args:
166 label: The label of the setup.
167 """
168 cls._global_setup_done[label] = True
169
170
171 @classmethod
172 def unmark_setup_done(cls, label):
173 """Mark the given setup not done.
174
175 Args:
176 label: The label of the setup.
177 """
178 cls._global_setup_done[label] = False
Vic Yang54f70572012-10-19 17:05:26 +0800179
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800180
181 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
182 # Parse arguments from command line
183 args = {}
184 for arg in cmdline_args:
185 match = re.search("^(\w+)=(.+)", arg)
186 if match:
187 args[match.group(1)] = match.group(2)
188
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800189 # Keep the arguments which will be used later.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800190 for key in self._customized_key_commands:
191 key_cmd = key + '_cmd'
192 if key_cmd in args:
193 self._customized_key_commands[key] = args[key_cmd]
194 logging.info('Customized %s key command: %s' %
195 (key, args[key_cmd]))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800196 if 'image' in args:
197 self._install_image_path = args['image']
198 logging.info('Install Chrome OS test image path: %s' %
199 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800200 if 'firmware_update' in args and args['firmware_update'].lower() \
201 not in ('0', 'false', 'no'):
202 if self._install_image_path:
203 self._firmware_update = True
204 logging.info('Also update firmware after installing.')
205 else:
206 logging.warning('Firmware update will not not performed '
207 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800208
209 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
210 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800211 if use_faft:
212 self.client_attr = FAFTClientAttribute(
213 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800214
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800215 if self.client_attr.chrome_ec:
216 self.ec = ChromeEC(self.servo)
217
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700218 # Setting up key matrix mapping
219 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
220
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800221
222 def setup(self):
223 """Autotest setup function."""
224 super(FAFTSequence, self).setup()
225 if not self._remote_infos['faft']['used']:
226 raise error.TestError('The use_faft flag should be enabled.')
227 self.register_faft_template({
228 'state_checker': (None),
229 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800230 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800231 'firmware_action': (None)
232 })
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800233 self.install_test_image(self._install_image_path, self._firmware_update)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800234 self.setup_gbb_flags()
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800235
236
237 def cleanup(self):
238 """Autotest cleanup function."""
239 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800240 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800241 super(FAFTSequence, self).cleanup()
242
243
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800244 def invalidate_firmware_setup(self):
245 """Invalidate all firmware related setup state.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800246
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800247 This method is called when the firmware is re-flashed. It resets all
248 firmware related setup states so that the next test setup properly
249 again.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800250 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800251 self.unmark_setup_done('gbb_flags')
Vic Yangdbaba8f2012-10-17 16:05:35 +0800252
253
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800254 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800255 """Reset client, if necessary.
256
257 This method is called when the client is not responsive. It may be
258 caused by the following cases:
259 - network flaky (can be recovered by replugging the Ethernet);
260 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
261 - corrupted firmware;
262 - corrutped OS image.
263 """
264 # DUT works fine, done.
265 if self._ping_test(self._client.ip, timeout=5):
266 return
267
268 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
269 # first reset item.
270
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +0800271 # DUT may be trapped in the recovery screen. Try to boot into USB to
272 # retrieve the recovery reason.
273 logging.info('Try to retrieve recovery reason...')
274 if self.servo.get('usb_mux_sel1') == 'dut_sees_usbkey':
275 self.wait_fw_screen_and_plug_usb()
276 else:
277 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
278
279 try:
280 self.wait_for_client(install_deps=True)
281 lines = self.faft_client.run_shell_command_get_output(
282 'crossystem recovery_reason')
283 self._trapped_in_recovery_reason = int(lines[0])
284 logging.info('Got the recovery reason %d.' %
285 self._trapped_in_recovery_reason)
286 except AssertionError:
287 logging.info('Failed to get the recovery reason.')
288
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800289 # DUT may halt on a firmware screen. Try cold reboot.
290 logging.info('Try cold reboot...')
291 self.cold_reboot()
292 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800293 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800294 return
295 except AssertionError:
296 pass
297
298 # DUT may be broken by a corrupted firmware. Restore firmware.
299 # We assume the recovery boot still works fine. Since the recovery
300 # code is in RO region and all FAFT tests don't change the RO region
301 # except GBB.
302 if self.is_firmware_saved():
303 self.ensure_client_in_recovery()
304 logging.info('Try restore the original firmware...')
305 if self.is_firmware_changed():
306 try:
307 self.restore_firmware()
308 return
309 except AssertionError:
310 logging.info('Restoring firmware doesn\'t help.')
311
312 # DUT may be broken by a corrupted OS image. Restore OS image.
313 self.ensure_client_in_recovery()
314 logging.info('Try restore the OS image...')
315 self.faft_client.run_shell_command('chromeos-install --yes')
316 self.sync_and_warm_reboot()
317 self.wait_for_client_offline()
318 try:
319 self.wait_for_client(install_deps=True)
320 logging.info('Successfully restore OS image.')
321 return
322 except AssertionError:
323 logging.info('Restoring OS image doesn\'t help.')
324
325
326 def ensure_client_in_recovery(self):
327 """Ensure client in recovery boot; reboot into it if necessary.
328
329 Raises:
330 error.TestError: if failed to boot the USB image.
331 """
332 # DUT works fine and is already in recovery boot, done.
333 if self._ping_test(self._client.ip, timeout=5):
334 if self.crossystem_checker({'mainfw_type': 'recovery'}):
335 return
336
337 logging.info('Try boot into USB image...')
338 self.servo.enable_usb_hub(host=True)
339 self.enable_rec_mode_and_reboot()
340 self.wait_fw_screen_and_plug_usb()
341 try:
342 self.wait_for_client(install_deps=True)
343 except AssertionError:
344 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800345
346
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800347 def assert_test_image_in_path(self, image_path):
348 """Assert the image of image_path be a Chrome OS test image.
349
350 Args:
351 image_path: A path on the host to the test image.
352
353 Raises:
354 error.TestError: if the image is not a test image.
355 """
356 try:
357 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
358 image_path)
359 logging.info('Build of image: %s %s' % (build_ver, build_hash))
360 except ChromeOSTestError:
361 raise error.TestError(
362 'An USB disk containning a test image should be plugged '
363 'in the servo board.')
364
365
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800366 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800367 """Assert an USB disk plugged-in on servo and a test image inside.
368
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800369 Args:
370 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
371 If None, it is detected automatically.
372
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800373 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800374 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800375 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800376 if self.check_setup_done('usb_check'):
Vic Yang54f70572012-10-19 17:05:26 +0800377 return
378
Tom Wai-Hong Tam1c86c7a2012-10-22 10:08:24 +0800379 # TODO(waihong@chromium.org): We skip the check when servod runs in
380 # a different host since no easy way to access the servo host so far.
381 # Should find a way to work-around it.
382 if not self.servo.is_localhost():
383 logging.info('Skip checking Chrome OS test image in USB as servod '
384 'runs in a different host.')
385 return
386
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800387 if usb_dev:
388 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
389 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700390 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800391 usb_dev = self.servo.probe_host_usb_dev()
392 if not usb_dev:
393 raise error.TestError(
394 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800395 self.assert_test_image_in_path(usb_dev)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800396 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800397
398
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800399 def get_server_address(self):
400 """Get the server address seen from the client.
401
402 Returns:
403 A string of the server address.
404 """
405 r = self.faft_client.run_shell_command_get_output("echo $SSH_CLIENT")
406 return r[0].split()[0]
407
408
Simran Basi741b5d42012-05-18 11:27:15 -0700409 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800410 """Install the test image specied by the path onto the USB and DUT disk.
411
412 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500413 recovery mode. Then runs 'chromeos-install' (and possible
414 chromeos-firmwareupdate') to install it to DUT disk.
415
416 Sample command line:
417
418 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
419 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
420 server/site_tests/firmware_XXXX/control
421
422 This test requires an automated recovery to occur while simulating
423 inserting and removing the usb key from the servo. To allow this the
424 following hardware setup is required:
425 1. servo2 board connected via servoflex.
426 2. USB key inserted in the servo2.
427 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
428 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800429
430 Args:
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800431 image_path: An URL or a path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800432 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800433
434 Raises:
435 error.TestError: If devserver failed to start.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800436 """
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800437 if not image_path:
438 return
439
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800440 if self.check_setup_done('reimage'):
441 return
442
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800443 if image_path.startswith(self._HTTP_PREFIX):
444 # TODO(waihong@chromium.org): Add the check of the URL to ensure
445 # it is a test image.
446 devserver = None
447 image_url = image_path
Tom Wai-Hong Tam42f136d2012-10-26 11:11:23 +0800448 elif self.servo.is_localhost():
449 self.assert_test_image_in_path(image_path)
450 # If servod is localhost, i.e. both servod and FAFT see the same
451 # file system, do nothing.
452 devserver = None
453 image_url = image_path
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800454 else:
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800455 self.assert_test_image_in_path(image_path)
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800456 image_dir, image_base = os.path.split(image_path)
457 logging.info('Starting devserver to serve the image...')
458 # The following stdout and stderr arguments should not be None,
459 # even we don't use them. Otherwise, the socket of devserve is
460 # created as fd 1 (as no stdout) but it still thinks stdout is fd
461 # 1 and dump the log to the socket. Wrong HTTP protocol happens.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800462 devserver = subprocess.Popen(['/usr/lib/devserver/devserver.py',
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800463 '--archive_dir=%s' % image_dir,
464 '--port=%s' % self._DEVSERVER_PORT],
465 stdout=subprocess.PIPE,
466 stderr=subprocess.PIPE)
467 image_url = '%s%s:%s/static/archive/%s' % (
468 self._HTTP_PREFIX,
469 self.get_server_address(),
470 self._DEVSERVER_PORT,
471 image_base)
472
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800473 # Wait devserver startup completely
474 time.sleep(self.DEVSERVER_DELAY)
475 # devserver is a service running forever. If it is terminated,
476 # some error does happen.
477 if devserver.poll():
478 raise error.TestError('Starting devserver failed, '
479 'returning %d.' % devserver.returncode)
480
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800481 logging.info('Ask Servo to install the image from %s' % image_url)
482 self.servo.image_to_servo_usb(image_url)
483
484 if devserver and devserver.poll() is None:
485 logging.info('Shutting down devserver...')
486 devserver.terminate()
Mike Truty49153d82012-08-21 22:27:30 -0500487
488 # DUT is powered off while imaging servo USB.
489 # Now turn it on.
490 self.servo.power_short_press()
491 self.wait_for_client()
492 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
493
494 install_cmd = 'chromeos-install --yes'
495 if firmware_update:
496 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
497
498 self.register_faft_sequence((
499 { # Step 1, request recovery boot
500 'state_checker': (self.crossystem_checker, {
501 'mainfw_type': ('developer', 'normal'),
502 }),
503 'userspace_action': self.faft_client.request_recovery_boot,
504 'firmware_action': self.wait_fw_screen_and_plug_usb,
505 'install_deps_after_boot': True,
506 },
507 { # Step 2, expected recovery boot
508 'state_checker': (self.crossystem_checker, {
509 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800510 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500511 }),
512 'userspace_action': (self.faft_client.run_shell_command,
513 install_cmd),
514 'reboot_action': self.cold_reboot,
515 'install_deps_after_boot': True,
516 },
517 { # Step 3, expected normal or developer boot (not recovery)
518 'state_checker': (self.crossystem_checker, {
519 'mainfw_type': ('developer', 'normal')
520 }),
521 },
522 ))
523 self.run_faft_sequence()
524 # 'Unplug' any USB keys in the servo from the dut.
Tom Wai-Hong Tam953c7742012-10-16 21:09:31 +0800525 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam6668b762012-10-23 11:45:36 +0800526 # Mark usb_check done so it won't check a test image in USB anymore.
527 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800528 self.mark_setup_done('reimage')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800529
530
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800531 def clear_set_gbb_flags(self, clear_mask, set_mask):
532 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800533
534 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800535 clear_mask: A mask of flags to be cleared.
536 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800537 """
538 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800539 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
540
541 if (gbb_flags != new_flags):
542 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
543 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800544 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800545 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800546 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800547 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800548 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800549 self.run_faft_step({
550 'firmware_action': self.wait_fw_screen_and_ctrl_d,
551 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800552
553
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800554 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800555 """Check if current platform has required EC capabilities.
556
557 Args:
558 required_cap: A list containing required EC capabilities. Pass in
559 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800560 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800561
562 Returns:
563 True if requirements are met. Otherwise, False.
564 """
565 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800566 if not suppress_warning:
567 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800568 return False
569
570 for cap in required_cap:
571 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800572 if not suppress_warning:
573 logging.warn('Requires EC capability "%s" to run this '
574 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800575 return False
576
577 return True
578
579
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800580 def _parse_crossystem_output(self, lines):
581 """Parse the crossystem output into a dict.
582
583 Args:
584 lines: The list of crossystem output strings.
585
586 Returns:
587 A dict which contains the crossystem keys/values.
588
589 Raises:
590 error.TestError: If wrong format in crossystem output.
591
592 >>> seq = FAFTSequence()
593 >>> seq._parse_crossystem_output([ \
594 "arch = x86 # Platform architecture", \
595 "cros_debug = 1 # OS should allow debug", \
596 ])
597 {'cros_debug': '1', 'arch': 'x86'}
598 >>> seq._parse_crossystem_output([ \
599 "arch=x86", \
600 ])
601 Traceback (most recent call last):
602 ...
603 TestError: Failed to parse crossystem output: arch=x86
604 >>> seq._parse_crossystem_output([ \
605 "arch = x86 # Platform architecture", \
606 "arch = arm # Platform architecture", \
607 ])
608 Traceback (most recent call last):
609 ...
610 TestError: Duplicated crossystem key: arch
611 """
612 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
613 parsed_list = {}
614 for line in lines:
615 matched = re.match(pattern, line.strip())
616 if not matched:
617 raise error.TestError("Failed to parse crossystem output: %s"
618 % line)
619 (name, value) = (matched.group(1), matched.group(2))
620 if name in parsed_list:
621 raise error.TestError("Duplicated crossystem key: %s" % name)
622 parsed_list[name] = value
623 return parsed_list
624
625
626 def crossystem_checker(self, expected_dict):
627 """Check the crossystem values matched.
628
629 Given an expect_dict which describes the expected crossystem values,
630 this function check the current crossystem values are matched or not.
631
632 Args:
633 expected_dict: A dict which contains the expected values.
634
635 Returns:
636 True if the crossystem value matched; otherwise, False.
637 """
638 lines = self.faft_client.run_shell_command_get_output('crossystem')
639 got_dict = self._parse_crossystem_output(lines)
640 for key in expected_dict:
641 if key not in got_dict:
642 logging.info('Expected key "%s" not in crossystem result' % key)
643 return False
644 if isinstance(expected_dict[key], str):
645 if got_dict[key] != expected_dict[key]:
646 logging.info("Expected '%s' value '%s' but got '%s'" %
647 (key, expected_dict[key], got_dict[key]))
648 return False
649 elif isinstance(expected_dict[key], tuple):
650 # Expected value is a tuple of possible actual values.
651 if got_dict[key] not in expected_dict[key]:
652 logging.info("Expected '%s' values %s but got '%s'" %
653 (key, str(expected_dict[key]), got_dict[key]))
654 return False
655 else:
656 logging.info("The expected_dict is neither a str nor a dict.")
657 return False
658 return True
659
660
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800661 def vdat_flags_checker(self, mask, value):
662 """Check the flags from VbSharedData matched.
663
664 This function checks the masked flags from VbSharedData using crossystem
665 are matched the given value.
666
667 Args:
668 mask: A bitmask of flags to be matched.
669 value: An expected value.
670
671 Returns:
672 True if the flags matched; otherwise, False.
673 """
674 lines = self.faft_client.run_shell_command_get_output(
675 'crossystem vdat_flags')
676 vdat_flags = int(lines[0], 16)
677 if vdat_flags & mask != value:
678 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
679 (value, mask, vdat_flags))
680 return False
681 return True
682
683
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800684 def ro_normal_checker(self, expected_fw=None, twostop=False):
685 """Check the current boot uses RO boot.
686
687 Args:
688 expected_fw: A string of expected firmware, 'A', 'B', or
689 None if don't care.
690 twostop: True to expect a TwoStop boot; False to expect a RO boot.
691
692 Returns:
693 True if the currect boot firmware matched and used RO boot;
694 otherwise, False.
695 """
696 crossystem_dict = {'tried_fwb': '0'}
697 if expected_fw:
698 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800699 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800700 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
701
702 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800703 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
704 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800705 self.crossystem_checker(crossystem_dict))
706
707
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +0800708 def dev_boot_usb_checker(self, dev_boot_usb=True):
709 """Check the current boot is from a developer USB (Ctrl-U trigger).
710
711 Args:
712 dev_boot_usb: True to expect an USB boot;
713 False to expect an internal device boot.
714
715 Returns:
716 True if the currect boot device matched; otherwise, False.
717 """
718 return (self.crossystem_checker({'mainfw_type': 'developer'})
719 and self.faft_client.is_removable_device_boot() == dev_boot_usb)
720
721
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800722 def root_part_checker(self, expected_part):
723 """Check the partition number of the root device matched.
724
725 Args:
726 expected_part: A string containing the number of the expected root
727 partition.
728
729 Returns:
730 True if the currect root partition number matched; otherwise, False.
731 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800732 part = self.faft_client.get_root_part()[-1]
733 if self.ROOTFS_MAP[expected_part] != part:
734 logging.info("Expected root part %s but got %s" %
735 (self.ROOTFS_MAP[expected_part], part))
736 return False
737 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800738
739
Vic Yang59cac9c2012-05-21 15:28:42 +0800740 def ec_act_copy_checker(self, expected_copy):
741 """Check the EC running firmware copy matches.
742
743 Args:
744 expected_copy: A string containing 'RO', 'A', or 'B' indicating
745 the expected copy of EC running firmware.
746
747 Returns:
748 True if the current EC running copy matches; otherwise, False.
749 """
750 lines = self.faft_client.run_shell_command_get_output('ectool version')
751 pattern = re.compile("Firmware copy: (.*)")
752 for line in lines:
753 matched = pattern.match(line)
754 if matched and matched.group(1) == expected_copy:
755 return True
756 return False
757
758
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800759 def check_root_part_on_non_recovery(self, part):
760 """Check the partition number of root device and on normal/dev boot.
761
762 Returns:
763 True if the root device matched and on normal/dev boot;
764 otherwise, False.
765 """
766 return self.root_part_checker(part) and \
767 self.crossystem_checker({
768 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800769 })
770
771
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800772 def _join_part(self, dev, part):
773 """Return a concatenated string of device and partition number.
774
775 Args:
776 dev: A string of device, e.g.'/dev/sda'.
777 part: A string of partition number, e.g.'3'.
778
779 Returns:
780 A concatenated string of device and partition number, e.g.'/dev/sda3'.
781
782 >>> seq = FAFTSequence()
783 >>> seq._join_part('/dev/sda', '3')
784 '/dev/sda3'
785 >>> seq._join_part('/dev/mmcblk0', '2')
786 '/dev/mmcblk0p2'
787 """
788 if 'mmcblk' in dev:
789 return dev + 'p' + part
790 else:
791 return dev + part
792
793
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800794 def copy_kernel_and_rootfs(self, from_part, to_part):
795 """Copy kernel and rootfs from from_part to to_part.
796
797 Args:
798 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800799 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800800 """
801 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800802 logging.info('Copying kernel from %s to %s. Please wait...' %
803 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800804 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800805 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
806 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
807 logging.info('Copying rootfs from %s to %s. Please wait...' %
808 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800809 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800810 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
811 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800812
813
814 def ensure_kernel_boot(self, part):
815 """Ensure the request kernel boot.
816
817 If not, it duplicates the current kernel to the requested kernel
818 and sets the requested higher priority to ensure it boot.
819
820 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800821 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800822 """
823 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800824 if self.faft_client.diff_kernel_a_b():
825 self.copy_kernel_and_rootfs(
826 from_part=self.OTHER_KERNEL_MAP[part],
827 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800828 self.run_faft_step({
829 'userspace_action': (self.reset_and_prioritize_kernel, part),
830 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800831
832
Vic Yang416f2032012-08-28 10:18:03 +0800833 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800834 """Set hardware write protect pin.
835
836 Args:
837 enable: True if asserting write protect pin. Otherwise, False.
838 """
839 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
840 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800841 self.servo.set('fw_wp', 'on' if enabled else 'off')
842
843
844 def set_EC_write_protect_and_reboot(self, enabled):
845 """Set EC write protect status and reboot to take effect.
846
847 EC write protect is only activated if both hardware write protect pin
848 is asserted and software write protect flag is set. Also, a reboot is
849 required for write protect to take effect.
850
851 Since the software write protect flag cannot be unset if hardware write
852 protect pin is asserted, we need to deasserted the pin first if we are
853 deactivating write protect. Similarly, a reboot is required before we
854 can modify the software flag.
855
856 This method asserts/deasserts hardware write protect pin first, and
857 set corresponding EC software write protect flag.
858
859 Args:
860 enable: True if activating EC write protect. Otherwise, False.
861 """
862 self.set_hardware_write_protect(enabled)
863 if enabled:
864 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800865 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800866 self.sync_and_ec_reboot()
867 else:
868 # Reboot after deasserting hardware write protect pin to deactivate
869 # write protect. And then remove software write protect flag.
870 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800871 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800872
873
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800874 def send_ctrl_d_to_dut(self):
875 """Send Ctrl-D key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800876 if self._customized_key_commands['ctrl_d']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800877 logging.info('running the customized Ctrl-D key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800878 os.system(self._customized_key_commands['ctrl_d'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800879 else:
880 self.servo.ctrl_d()
881
882
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800883 def send_ctrl_u_to_dut(self):
884 """Send Ctrl-U key to DUT.
885
886 Raises:
887 error.TestError: if a non-Chrome EC device or no Ctrl-U command given
888 on a no-build-in-keyboard device.
889 """
890 if self._customized_key_commands['ctrl_u']:
891 logging.info('running the customized Ctrl-U key command')
892 os.system(self._customized_key_commands['ctrl_u'])
893 elif self.check_ec_capability(['keyboard'], suppress_warning=True):
894 self.ec.key_down('<ctrl_l>')
895 self.ec.key_down('u')
896 self.ec.key_up('u')
897 self.ec.key_up('<ctrl_l>')
898 elif self.client_attr.has_keyboard:
899 raise error.TestError(
900 "Can't send Ctrl-U to DUT without using Chrome EC.")
901 else:
902 raise error.TestError(
903 "Should specify the ctrl_u_cmd argument.")
904
905
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800906 def send_enter_to_dut(self):
907 """Send Enter key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800908 if self._customized_key_commands['enter']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800909 logging.info('running the customized Enter key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800910 os.system(self._customized_key_commands['enter'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800911 else:
912 self.servo.enter_key()
913
914
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800915 def send_space_to_dut(self):
916 """Send Space key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800917 if self._customized_key_commands['space']:
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800918 logging.info('running the customized Space key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800919 os.system(self._customized_key_commands['space'])
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800920 else:
921 # Send the alternative key combinaton of space key to servo.
922 self.servo.ctrl_refresh_key()
923
924
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800925 def wait_fw_screen_and_ctrl_d(self):
926 """Wait for firmware warning screen and press Ctrl-D."""
927 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800928 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800929
930
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800931 def wait_fw_screen_and_ctrl_u(self):
932 """Wait for firmware warning screen and press Ctrl-U."""
933 time.sleep(self.FIRMWARE_SCREEN_DELAY)
934 self.send_ctrl_u_to_dut()
935
936
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800937 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
938 """Wait for firmware warning screen and trigger recovery boot."""
939 time.sleep(self.FIRMWARE_SCREEN_DELAY)
940 self.send_enter_to_dut()
941
942 # For Alex/ZGB, there is a dev warning screen in text mode.
943 # Skip it by pressing Ctrl-D.
944 if need_dev_transition:
945 time.sleep(self.TEXT_SCREEN_DELAY)
946 self.send_ctrl_d_to_dut()
947
948
Mike Truty49153d82012-08-21 22:27:30 -0500949 def wait_fw_screen_and_unplug_usb(self):
950 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800951 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800952 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
953 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500954
955
956 def wait_fw_screen_and_plug_usb(self):
957 """Wait for firmware warning screen and then unplug and plug the USB."""
958 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800959 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
960
961
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800962 def wait_fw_screen_and_press_power(self):
963 """Wait for firmware warning screen and press power button."""
964 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800965 # While the firmware screen, the power button probing loop sleeps
966 # 0.25 second on every scan. Use the normal delay (1.2 second) for
967 # power press.
968 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800969
970
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800971 def wait_longer_fw_screen_and_press_power(self):
972 """Wait for firmware screen without timeout and press power button."""
973 time.sleep(self.DEV_SCREEN_TIMEOUT)
974 self.wait_fw_screen_and_press_power()
975
976
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800977 def wait_fw_screen_and_close_lid(self):
978 """Wait for firmware warning screen and close lid."""
979 time.sleep(self.FIRMWARE_SCREEN_DELAY)
980 self.servo.lid_close()
981
982
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800983 def wait_longer_fw_screen_and_close_lid(self):
984 """Wait for firmware screen without timeout and close lid."""
985 time.sleep(self.FIRMWARE_SCREEN_DELAY)
986 self.wait_fw_screen_and_close_lid()
987
988
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800989 def setup_gbb_flags(self):
990 """Setup the GBB flags for FAFT test."""
991 if self.check_setup_done('gbb_flags'):
992 return
993
994 logging.info('Set proper GBB flags for test.')
995 self.clear_set_gbb_flags(vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY |
996 vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
997 vboot.GBB_FLAG_FORCE_DEV_BOOT_USB |
998 vboot.GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK,
999 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
1000 self.mark_setup_done('gbb_flags')
1001
1002
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001003 def setup_tried_fwb(self, tried_fwb):
1004 """Setup for fw B tried state.
1005
1006 It makes sure the system in the requested fw B tried state. If not, it
1007 tries to do so.
1008
1009 Args:
1010 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
1011 """
1012 if tried_fwb:
1013 if not self.crossystem_checker({'tried_fwb': '1'}):
1014 logging.info(
1015 'Firmware is not booted with tried_fwb. Reboot into it.')
1016 self.run_faft_step({
1017 'userspace_action': self.faft_client.set_try_fw_b,
1018 })
1019 else:
1020 if not self.crossystem_checker({'tried_fwb': '0'}):
1021 logging.info(
1022 'Firmware is booted with tried_fwb. Reboot to clear.')
1023 self.run_faft_step({})
1024
1025
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001026 def enable_rec_mode_and_reboot(self):
1027 """Switch to rec mode and reboot.
1028
1029 This method emulates the behavior of the old physical recovery switch,
1030 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
1031 recovery mode, i.e. just press Power + Esc + Refresh.
1032 """
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +08001033 if self._customized_key_commands['rec_reboot']:
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001034 logging.info('running the customized rec reboot command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +08001035 os.system(self._customized_key_commands['rec_reboot'])
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001036 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +08001037 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +08001038 self.servo.set('cold_reset', 'on')
1039 time.sleep(self.COLD_RESET_DELAY)
1040 self.servo.set('cold_reset', 'off')
1041 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +08001042 self.ec.send_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +08001043 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +08001044 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +08001045 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001046 else:
1047 self.servo.enable_recovery_mode()
1048 self.cold_reboot()
1049 time.sleep(self.EC_REBOOT_DELAY)
1050 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001051
1052
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001053 def enable_dev_mode_and_reboot(self):
1054 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001055 if self.client_attr.keyboard_dev:
1056 self.enable_keyboard_dev_mode()
1057 else:
1058 self.servo.enable_development_mode()
1059 self.faft_client.run_shell_command(
1060 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001061
1062
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001063 def enable_normal_mode_and_reboot(self):
1064 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001065 if self.client_attr.keyboard_dev:
1066 self.disable_keyboard_dev_mode()
1067 else:
1068 self.servo.disable_development_mode()
1069 self.faft_client.run_shell_command(
1070 'chromeos-firmwareupdate --mode tonormal && reboot')
1071
1072
1073 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
1074 """Wait for firmware screen and then switch into or out of dev mode.
1075
1076 Args:
1077 dev: True if switching into dev mode. Otherwise, False.
1078 """
1079 time.sleep(self.FIRMWARE_SCREEN_DELAY)
1080 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001081 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001082 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001083 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +08001084 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001085 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001086
1087
1088 def enable_keyboard_dev_mode(self):
1089 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001090 # Plug out USB disk for preventing recovery boot without warning
1091 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001092 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001093 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001094 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001095 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001096
1097
1098 def disable_keyboard_dev_mode(self):
1099 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001100 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001101 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001102 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001103 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001104 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001105
1106
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001107 def setup_dev_mode(self, dev_mode):
1108 """Setup for development mode.
1109
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001110 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001111 tries to do so.
1112
1113 Args:
1114 dev_mode: True if requested in dev mode; False if normal mode.
1115 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001116 # Change the default firmware_action for dev mode passing the fw screen.
1117 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001118 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1119 else None),
1120 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001121 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001122 if (not self.client_attr.keyboard_dev and
1123 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001124 logging.info('Dev switch is not on. Now switch it on.')
1125 self.servo.enable_development_mode()
1126 if not self.crossystem_checker({'devsw_boot': '1',
1127 'mainfw_type': 'developer'}):
1128 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001129 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001130 'userspace_action': None if self.client_attr.keyboard_dev
1131 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001132 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001133 'reboot_action': self.enable_keyboard_dev_mode if
1134 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001135 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001136 else:
Vic Yange7553162012-06-20 16:20:47 +08001137 if (not self.client_attr.keyboard_dev and
1138 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001139 logging.info('Dev switch is not off. Now switch it off.')
1140 self.servo.disable_development_mode()
1141 if not self.crossystem_checker({'devsw_boot': '0',
1142 'mainfw_type': 'normal'}):
1143 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001144 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001145 'userspace_action': None if self.client_attr.keyboard_dev
1146 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001147 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001148 'reboot_action': self.disable_keyboard_dev_mode if
1149 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001150 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001151
1152
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001153 def setup_kernel(self, part):
1154 """Setup for kernel test.
1155
1156 It makes sure both kernel A and B bootable and the current boot is
1157 the requested kernel part.
1158
1159 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001160 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001161 """
1162 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001163 if self.faft_client.diff_kernel_a_b():
1164 self.copy_kernel_and_rootfs(from_part=part,
1165 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001166 self.reset_and_prioritize_kernel(part)
1167
1168
1169 def reset_and_prioritize_kernel(self, part):
1170 """Make the requested partition highest priority.
1171
1172 This function also reset kerenl A and B to bootable.
1173
1174 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001175 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001176 """
1177 root_dev = self.faft_client.get_root_dev()
1178 # Reset kernel A and B to bootable.
1179 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1180 (self.KERNEL_MAP['a'], root_dev))
1181 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1182 (self.KERNEL_MAP['b'], root_dev))
1183 # Set kernel part highest priority.
1184 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1185 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001186 # Safer to sync and wait until the cgpt status written to the disk.
1187 self.faft_client.run_shell_command('sync')
1188 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001189
1190
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001191 def warm_reboot(self):
1192 """Request a warm reboot.
1193
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001194 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001195 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001196 # Use cold reset if the warm reset is broken.
1197 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001198 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1199 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001200 else:
1201 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001202
1203
1204 def cold_reboot(self):
1205 """Request a cold reboot.
1206
1207 A wrapper for underlying servo cold reset.
1208 """
Gediminas Ramanauskasc6025692012-10-23 14:33:40 -07001209 if self.client_attr.broken_warm_reset:
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001210 self.servo.set('pwr_button', 'press')
1211 self.servo.set('cold_reset', 'on')
1212 self.servo.set('cold_reset', 'off')
1213 time.sleep(self.POWER_BTN_DELAY)
1214 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001215 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001216 # We don't use servo.cold_reset() here because software sync is
1217 # not yet finished, and device may or may not come up after cold
1218 # reset. Pressing power button before firmware comes up solves this.
1219 #
1220 # The correct behavior should be (not work now):
1221 # - If rebooting EC with rec mode on, power on AP and it boots
1222 # into recovery mode.
1223 # - If rebooting EC with rec mode off, power on AP for software
1224 # sync. Then AP checks if lid open or not. If lid open, continue;
1225 # otherwise, shut AP down and need servo for a power button
1226 # press.
1227 self.servo.set('cold_reset', 'on')
1228 self.servo.set('cold_reset', 'off')
1229 time.sleep(self.POWER_BTN_DELAY)
1230 self.servo.power_short_press()
1231 else:
1232 self.servo.cold_reset()
1233
1234
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001235 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001236 """Request the client sync and do a warm reboot.
1237
1238 This is the default reboot action on FAFT.
1239 """
1240 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001241 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001242 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001243
1244
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001245 def sync_and_cold_reboot(self):
1246 """Request the client sync and do a cold reboot.
1247
1248 This reboot action is used to reset EC for recovery mode.
1249 """
1250 self.faft_client.run_shell_command('sync')
1251 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001252 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001253
1254
Vic Yangaeb10392012-08-28 09:25:09 +08001255 def sync_and_ec_reboot(self, args=''):
1256 """Request the client sync and do a EC triggered reboot.
1257
1258 Args:
1259 args: Arguments passed to "ectool reboot_ec". Including:
1260 RO: jump to EC RO firmware.
1261 RW: jump to EC RW firmware.
1262 cold: Cold/hard reboot.
1263 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001264 self.faft_client.run_shell_command('sync')
1265 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001266 # Since EC reboot happens immediately, delay before actual reboot to
1267 # allow FAFT client returning.
1268 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1269 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001270 time.sleep(self.EC_REBOOT_DELAY)
1271 self.check_lid_and_power_on()
1272
1273
Chun-ting Changa4f65532012-10-17 16:57:28 +08001274 def sync_and_reboot_with_factory_install_shim(self):
1275 """Request the client sync and do a warm reboot to recovery mode.
1276
1277 After reboot, the client will use factory install shim to reset TPM
1278 values. The client ignore TPM rollback, so here forces it to recovery
1279 mode.
1280 """
1281 is_dev = self.crossystem_checker({'devsw_boot': '1'})
1282 if not is_dev:
1283 self.enable_dev_mode_and_reboot()
1284 time.sleep(self.SYNC_DELAY)
1285 self.enable_rec_mode_and_reboot()
1286 time.sleep(self.RESET_TPM_WITH_INSTALL_SHIM_DELAY)
1287 self.warm_reboot()
1288
1289
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001290 def full_power_off_and_on(self):
1291 """Shutdown the device by pressing power button and power on again."""
1292 # Press power button to trigger Chrome OS normal shutdown process.
1293 self.servo.power_normal_press()
1294 time.sleep(self.FULL_POWER_OFF_DELAY)
1295 # Short press power button to boot DUT again.
1296 self.servo.power_short_press()
1297
1298
Vic Yangf86728a2012-07-30 10:44:07 +08001299 def check_lid_and_power_on(self):
1300 """
1301 On devices with EC software sync, system powers on after EC reboots if
1302 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1303 This method checks lid switch state and presses power button if
1304 necessary.
1305 """
1306 if self.servo.get("lid_open") == "no":
1307 time.sleep(self.SOFTWARE_SYNC_DELAY)
1308 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001309
1310
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001311 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1312 """Modify the kernel header magic in USB stick.
1313
1314 The kernel header magic is the first 8-byte of kernel partition.
1315 We modify it to make it fail on kernel verification check.
1316
1317 Args:
1318 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1319 from_magic: A string of magic which we change it from.
1320 to_magic: A string of magic which we change it to.
1321
1322 Raises:
1323 error.TestError: if failed to change magic.
1324 """
1325 assert len(from_magic) == 8
1326 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001327 # USB image only contains one kernel.
1328 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001329 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1330 current_magic = utils.system_output(read_cmd)
1331 if current_magic == to_magic:
1332 logging.info("The kernel magic is already %s." % current_magic)
1333 return
1334 if current_magic != from_magic:
1335 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1336
1337 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1338 (from_magic, to_magic))
1339 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1340 " 2>/dev/null" % (to_magic, kernel_part))
1341 utils.system(write_cmd)
1342
1343 if utils.system_output(read_cmd) != to_magic:
1344 raise error.TestError("Failed to write new magic.")
1345
1346
1347 def corrupt_usb_kernel(self, usb_dev):
1348 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1349
1350 Args:
1351 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1352 """
1353 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1354 self.CORRUPTED_MAGIC)
1355
1356
1357 def restore_usb_kernel(self, usb_dev):
1358 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1359
1360 Args:
1361 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1362 """
1363 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1364 self.CHROMEOS_MAGIC)
1365
1366
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001367 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001368 """Call the action function with/without arguments.
1369
1370 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001371 action_tuple: A function, or a tuple (function, args, error_msg),
1372 in which, args and error_msg are optional. args is
1373 either a value or a tuple if multiple arguments.
1374 check_status: Check the return value of action function. If not
1375 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001376
1377 Returns:
1378 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001379
1380 Raises:
1381 error.TestError: An error when the action function is not callable.
1382 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001383 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001384 action = action_tuple
1385 args = ()
1386 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001387 if isinstance(action_tuple, tuple):
1388 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001389 if len(action_tuple) >= 2:
1390 args = action_tuple[1]
1391 if not isinstance(args, tuple):
1392 args = (args,)
1393 if len(action_tuple) >= 3:
Tom Wai-Hong Tamff560882012-10-15 16:50:06 +08001394 error_msg = action_tuple[2]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001395
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001396 if action is None:
1397 return
1398
1399 if not callable(action):
1400 raise error.TestError('action is not callable!')
1401
1402 info_msg = 'calling %s' % str(action)
1403 if args:
1404 info_msg += ' with args %s' % str(args)
1405 logging.info(info_msg)
1406 ret = action(*args)
1407
1408 if check_status and not ret:
1409 raise error.TestFail('%s: %s returning %s' %
1410 (error_msg, info_msg, str(ret)))
1411 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001412
1413
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001414 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1415 post_power_action=None):
1416 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1417
1418 Args:
1419 shutdown_action: a function which makes DUT shutdown, like pressing
1420 power key.
1421 pre_power_action: a function which is called before next power on.
1422 post_power_action: a function which is called after next power on.
1423
1424 Raises:
1425 error.TestFail: if the shutdown_action() failed to turn DUT off.
1426 """
1427 self._call_action(shutdown_action)
1428 logging.info('Wait to ensure DUT shut down...')
1429 try:
1430 self.wait_for_client()
1431 raise error.TestFail(
1432 'Should shut the device down after calling %s.' %
1433 str(shutdown_action))
1434 except AssertionError:
1435 logging.info(
1436 'DUT is surely shutdown. We are going to power it on again...')
1437
1438 if pre_power_action:
1439 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001440 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001441 if post_power_action:
1442 self._call_action(post_power_action)
1443
1444
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001445 def register_faft_template(self, template):
1446 """Register FAFT template, the default FAFT_STEP of each step.
1447
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001448 Any missing field falls back to the original faft_template.
1449
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001450 Args:
1451 template: A FAFT_STEP dict.
1452 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001453 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001454
1455
1456 def register_faft_sequence(self, sequence):
1457 """Register FAFT sequence.
1458
1459 Args:
1460 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1461 """
1462 self._faft_sequence = sequence
1463
1464
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001465 def run_faft_step(self, step, no_reboot=False):
1466 """Run a single FAFT step.
1467
1468 Any missing field falls back to faft_template. An empty step means
1469 running the default faft_template.
1470
1471 Args:
1472 step: A FAFT_STEP dict.
1473 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001474
1475 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001476 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001477 error.TestFail: Test failed in waiting DUT reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001478 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001479 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1480 'firmware_action', 'install_deps_after_boot')
1481
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001482 test = {}
1483 test.update(self._faft_template)
1484 test.update(step)
1485
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001486 for key in test:
1487 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001488 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001489
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001490 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001491 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001492
1493 self._call_action(test['userspace_action'])
1494
1495 # Don't run reboot_action and firmware_action if no_reboot is True.
1496 if not no_reboot:
1497 self._call_action(test['reboot_action'])
1498 self.wait_for_client_offline()
1499 self._call_action(test['firmware_action'])
1500
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001501 try:
1502 if 'install_deps_after_boot' in test:
1503 self.wait_for_client(
1504 install_deps=test['install_deps_after_boot'])
1505 else:
1506 self.wait_for_client()
1507 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001508 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001509 self.reset_client()
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001510 if self._trapped_in_recovery_reason:
1511 raise error.TestFail('Trapped in the recovery reason: %d' %
1512 self._trapped_in_recovery_reason)
1513 else:
1514 raise error.TestFail('Timed out waiting for DUT reboot.')
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001515
1516
1517 def run_faft_sequence(self):
1518 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001519 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001520 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001521 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001522 logging.info('======== Running FAFT sequence step %d ========' %
1523 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001524 # Don't reboot in the last step.
1525 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001526 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001527
1528
ctchang38ae4922012-09-03 17:01:16 +08001529 def get_current_firmware_sha(self):
1530 """Get current firmware sha of body and vblock.
1531
1532 Returns:
1533 Current firmware sha follows the order (
1534 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1535 """
1536 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1537 self.faft_client.get_firmware_sha('a'),
1538 self.faft_client.get_firmware_sig_sha('b'),
1539 self.faft_client.get_firmware_sha('b'))
1540 return current_firmware_sha
1541
1542
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001543 def is_firmware_changed(self):
1544 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001545
1546 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001547 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001548 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001549 # Device may not be rebooted after test.
1550 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001551
1552 current_sha = self.get_current_firmware_sha()
1553
1554 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001555 return False
ctchang38ae4922012-09-03 17:01:16 +08001556 else:
ctchang38ae4922012-09-03 17:01:16 +08001557 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1558 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1559 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1560 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001561 logging.info("Firmware changed:")
1562 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1563 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1564 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1565 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1566 return True
ctchang38ae4922012-09-03 17:01:16 +08001567
1568
1569 def backup_firmware(self, suffix='.original'):
1570 """Backup firmware to file, and then send it to host.
1571
1572 Args:
1573 suffix: a string appended to backup file name
1574 """
1575 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001576 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1577 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1578 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001579
1580 self._backup_firmware_sha = self.get_current_firmware_sha()
1581 logging.info('Backup firmware stored in %s with suffix %s' % (
1582 self.resultsdir, suffix))
1583
1584
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001585 def is_firmware_saved(self):
1586 """Check if a firmware saved (called backup_firmware before).
1587
1588 Returns:
1589 True if the firmware is backuped; otherwise False.
1590 """
1591 return self._backup_firmware_sha != ()
1592
1593
ctchang38ae4922012-09-03 17:01:16 +08001594 def restore_firmware(self, suffix='.original'):
1595 """Restore firmware from host in resultsdir.
1596
1597 Args:
1598 suffix: a string appended to backup file name
1599 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001600 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001601 return
1602
1603 # Backup current corrupted firmware.
1604 self.backup_firmware(suffix='.corrupt')
1605
1606 # Restore firmware.
1607 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001608 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1609 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001610
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001611 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001612 self.sync_and_warm_reboot()
1613 self.wait_for_client_offline()
1614 self.wait_for_client()
1615
ctchang38ae4922012-09-03 17:01:16 +08001616 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001617
1618
1619 def setup_firmwareupdate_shellball(self, shellball=None):
1620 """Deside a shellball to use in firmware update test.
1621
1622 Check if there is a given shellball, and it is a shell script. Then,
1623 send it to the remote host. Otherwise, use
1624 /usr/sbin/chromeos-firmwareupdate.
1625
1626 Args:
1627 shellball: path of a shellball or default to None.
1628
1629 Returns:
1630 Path of shellball in remote host.
1631 If use default shellball, reutrn None.
1632 """
1633 updater_path = None
1634 if shellball:
1635 # Determine the firmware file is a shellball or a raw binary.
1636 is_shellball = (utils.system_output("file %s" % shellball).find(
1637 "shell script") != -1)
1638 if is_shellball:
1639 logging.info('Device will update firmware with shellball %s'
1640 % shellball)
1641 temp_dir = self.faft_client.create_temp_dir('shellball_')
1642 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1643 self._client.send_file(shellball, temp_shellball)
1644 updater_path = temp_shellball
1645 else:
1646 raise error.TestFail(
1647 'The given shellball is not a shell script.')
1648 return updater_path