blob: 73dfd339cbee538a71a8b3fc29d32eb67fb7336e [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 Tam41738762012-10-29 14:32:39 +080018from autotest_lib.server.cros.faft_delay_constants import FAFTDelayConstants
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080019from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080020from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +080021from autotest_lib.site_utils.chromeos_test.common_util import ChromeOSTestError
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080022
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080023dirname = os.path.dirname(sys.modules[__name__].__file__)
24autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
25cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080026
27class FAFTSequence(ServoTest):
28 """
29 The base class of Fully Automated Firmware Test Sequence.
30
31 Many firmware tests require several reboot cycles and verify the resulted
32 system states. To do that, an Autotest test case should detailly handle
33 every action on each step. It makes the test case hard to read and many
34 duplicated code. The base class FAFTSequence is to solve this problem.
35
36 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
37 There are four functions in the FAFT_STEP dict:
38 state_checker: a function to check the current is valid or not,
39 returning True if valid, otherwise, False to break the whole
40 test sequence.
41 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080042 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080043 firmware_action: a function to describe the action ran after reboot.
44
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080045 And configurations:
46 install_deps_after_boot: if True, install the Autotest dependency after
47 boot; otherwise, do nothing. It is for the cases of recovery mode
48 test. The test boots a USB/SD image instead of an internal image.
49 The previous installed Autotest dependency on the internal image
50 is lost. So need to install it again.
51
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080052 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080053 userspace_action and firmware_action. Its reboot_action is a hardware
54 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080055 self.register_faft_template(FAFT_STEP).
56
57 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
58 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
59 fall back to default.
60
61 In the run_once(), it should register and run FAFT_SEQUENCE like:
62 def run_once(self):
63 self.register_faft_sequence(FAFT_SEQUENCE)
64 self.run_faft_sequnce()
65
66 Note that in the last step, we only run state_checker. The
67 userspace_action, reboot_action, and firmware_action are not executed.
68
69 Attributes:
70 _faft_template: The default FAFT_STEP of each step. The actions would
71 be over-written if the registered FAFT_SEQUENCE is valid.
72 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +080073 _install_image_path: The URL or the path on the host to the Chrome OS
74 test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080075 _firmware_update: Boolean. True if firmware update needed after
76 installing the image.
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +080077 _trapped_in_recovery_reason: Keep the recovery reason when the test is
78 trapped in the recovery screen.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080079 """
80 version = 1
81
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080082 # Mapping of partition number of kernel and rootfs.
83 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
84 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
85 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
86 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
87
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +080088 CHROMEOS_MAGIC = "CHROMEOS"
89 CORRUPTED_MAGIC = "CORRUPTD"
90
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +080091 _HTTP_PREFIX = 'http://'
92 _DEVSERVER_PORT = '8090'
93
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +080094 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080095 _faft_sequence = ()
96
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080097 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080098 _firmware_update = False
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +080099 _trapped_in_recovery_reason = 0
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800100
ctchang38ae4922012-09-03 17:01:16 +0800101 _backup_firmware_sha = ()
102
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800103 # Class level variable, keep track the states of one time setup.
104 # This variable is preserved across tests which inherit this class.
105 _global_setup_done = {
106 'gbb_flags': False,
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800107 'reimage': False,
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800108 'usb_check': False,
109 }
Vic Yang54f70572012-10-19 17:05:26 +0800110
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800111 @classmethod
112 def check_setup_done(cls, label):
113 """Check if the given setup is done.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800114
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800115 Args:
116 label: The label of the setup.
117 """
118 return cls._global_setup_done[label]
119
120
121 @classmethod
122 def mark_setup_done(cls, label):
123 """Mark the given setup done.
124
125 Args:
126 label: The label of the setup.
127 """
128 cls._global_setup_done[label] = True
129
130
131 @classmethod
132 def unmark_setup_done(cls, label):
133 """Mark the given setup not done.
134
135 Args:
136 label: The label of the setup.
137 """
138 cls._global_setup_done[label] = False
Vic Yang54f70572012-10-19 17:05:26 +0800139
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800140
141 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
142 # Parse arguments from command line
143 args = {}
144 for arg in cmdline_args:
145 match = re.search("^(\w+)=(.+)", arg)
146 if match:
147 args[match.group(1)] = match.group(2)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800148 if 'image' in args:
149 self._install_image_path = args['image']
150 logging.info('Install Chrome OS test image path: %s' %
151 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800152 if 'firmware_update' in args and args['firmware_update'].lower() \
153 not in ('0', 'false', 'no'):
154 if self._install_image_path:
155 self._firmware_update = True
156 logging.info('Also update firmware after installing.')
157 else:
158 logging.warning('Firmware update will not not performed '
159 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800160
161 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
162 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800163 if use_faft:
164 self.client_attr = FAFTClientAttribute(
165 self.faft_client.get_platform_name())
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800166 self.delay = FAFTDelayConstants(
167 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800168
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800169 if self.client_attr.chrome_ec:
170 self.ec = ChromeEC(self.servo)
171
Tom Wai-Hong Tam9c15b4b2012-10-29 17:59:26 +0800172 if not self.client_attr.has_keyboard:
173 # The environment variable USBKM232_UART_DEVICE should point
174 # to the USB-KM232 UART device.
175 if ('USBKM232_UART_DEVICE' not in os.environ or
176 not os.path.exists(os.environ['USBKM232_UART_DEVICE'])):
177 raise error.TestError('Must set a valid environment '
178 'variable USBKM232_UART_DEVICE.')
179
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700180 # Setting up key matrix mapping
181 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
182
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800183
184 def setup(self):
185 """Autotest setup function."""
186 super(FAFTSequence, self).setup()
187 if not self._remote_infos['faft']['used']:
188 raise error.TestError('The use_faft flag should be enabled.')
189 self.register_faft_template({
190 'state_checker': (None),
191 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800192 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800193 'firmware_action': (None)
194 })
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800195 self.install_test_image(self._install_image_path, self._firmware_update)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800196 self.setup_gbb_flags()
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800197
198
199 def cleanup(self):
200 """Autotest cleanup function."""
201 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800202 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800203 super(FAFTSequence, self).cleanup()
204
205
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800206 def invalidate_firmware_setup(self):
207 """Invalidate all firmware related setup state.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800208
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800209 This method is called when the firmware is re-flashed. It resets all
210 firmware related setup states so that the next test setup properly
211 again.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800212 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800213 self.unmark_setup_done('gbb_flags')
Vic Yangdbaba8f2012-10-17 16:05:35 +0800214
215
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800216 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800217 """Reset client, if necessary.
218
219 This method is called when the client is not responsive. It may be
220 caused by the following cases:
221 - network flaky (can be recovered by replugging the Ethernet);
222 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
223 - corrupted firmware;
224 - corrutped OS image.
225 """
226 # DUT works fine, done.
227 if self._ping_test(self._client.ip, timeout=5):
228 return
229
230 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
231 # first reset item.
232
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +0800233 # DUT may be trapped in the recovery screen. Try to boot into USB to
234 # retrieve the recovery reason.
235 logging.info('Try to retrieve recovery reason...')
236 if self.servo.get('usb_mux_sel1') == 'dut_sees_usbkey':
237 self.wait_fw_screen_and_plug_usb()
238 else:
239 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
240
241 try:
242 self.wait_for_client(install_deps=True)
243 lines = self.faft_client.run_shell_command_get_output(
244 'crossystem recovery_reason')
245 self._trapped_in_recovery_reason = int(lines[0])
246 logging.info('Got the recovery reason %d.' %
247 self._trapped_in_recovery_reason)
248 except AssertionError:
249 logging.info('Failed to get the recovery reason.')
250
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800251 # DUT may halt on a firmware screen. Try cold reboot.
252 logging.info('Try cold reboot...')
253 self.cold_reboot()
254 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800255 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800256 return
257 except AssertionError:
258 pass
259
260 # DUT may be broken by a corrupted firmware. Restore firmware.
261 # We assume the recovery boot still works fine. Since the recovery
262 # code is in RO region and all FAFT tests don't change the RO region
263 # except GBB.
264 if self.is_firmware_saved():
265 self.ensure_client_in_recovery()
266 logging.info('Try restore the original firmware...')
267 if self.is_firmware_changed():
268 try:
269 self.restore_firmware()
270 return
271 except AssertionError:
272 logging.info('Restoring firmware doesn\'t help.')
273
274 # DUT may be broken by a corrupted OS image. Restore OS image.
275 self.ensure_client_in_recovery()
276 logging.info('Try restore the OS image...')
277 self.faft_client.run_shell_command('chromeos-install --yes')
278 self.sync_and_warm_reboot()
279 self.wait_for_client_offline()
280 try:
281 self.wait_for_client(install_deps=True)
282 logging.info('Successfully restore OS image.')
283 return
284 except AssertionError:
285 logging.info('Restoring OS image doesn\'t help.')
286
287
288 def ensure_client_in_recovery(self):
289 """Ensure client in recovery boot; reboot into it if necessary.
290
291 Raises:
292 error.TestError: if failed to boot the USB image.
293 """
294 # DUT works fine and is already in recovery boot, done.
295 if self._ping_test(self._client.ip, timeout=5):
296 if self.crossystem_checker({'mainfw_type': 'recovery'}):
297 return
298
299 logging.info('Try boot into USB image...')
300 self.servo.enable_usb_hub(host=True)
301 self.enable_rec_mode_and_reboot()
302 self.wait_fw_screen_and_plug_usb()
303 try:
304 self.wait_for_client(install_deps=True)
305 except AssertionError:
306 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800307
308
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800309 def assert_test_image_in_path(self, image_path):
310 """Assert the image of image_path be a Chrome OS test image.
311
312 Args:
313 image_path: A path on the host to the test image.
314
315 Raises:
316 error.TestError: if the image is not a test image.
317 """
318 try:
319 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
320 image_path)
321 logging.info('Build of image: %s %s' % (build_ver, build_hash))
322 except ChromeOSTestError:
323 raise error.TestError(
324 'An USB disk containning a test image should be plugged '
325 'in the servo board.')
326
327
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800328 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800329 """Assert an USB disk plugged-in on servo and a test image inside.
330
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800331 Args:
332 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
333 If None, it is detected automatically.
334
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800335 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800336 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800337 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800338 if self.check_setup_done('usb_check'):
Vic Yang54f70572012-10-19 17:05:26 +0800339 return
340
Tom Wai-Hong Tam1c86c7a2012-10-22 10:08:24 +0800341 # TODO(waihong@chromium.org): We skip the check when servod runs in
342 # a different host since no easy way to access the servo host so far.
343 # Should find a way to work-around it.
344 if not self.servo.is_localhost():
345 logging.info('Skip checking Chrome OS test image in USB as servod '
346 'runs in a different host.')
347 return
348
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800349 if usb_dev:
350 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
351 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700352 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800353 usb_dev = self.servo.probe_host_usb_dev()
354 if not usb_dev:
355 raise error.TestError(
356 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800357 self.assert_test_image_in_path(usb_dev)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800358 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800359
360
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800361 def get_server_address(self):
362 """Get the server address seen from the client.
363
364 Returns:
365 A string of the server address.
366 """
367 r = self.faft_client.run_shell_command_get_output("echo $SSH_CLIENT")
368 return r[0].split()[0]
369
370
Simran Basi741b5d42012-05-18 11:27:15 -0700371 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800372 """Install the test image specied by the path onto the USB and DUT disk.
373
374 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500375 recovery mode. Then runs 'chromeos-install' (and possible
376 chromeos-firmwareupdate') to install it to DUT disk.
377
378 Sample command line:
379
380 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
381 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
382 server/site_tests/firmware_XXXX/control
383
384 This test requires an automated recovery to occur while simulating
385 inserting and removing the usb key from the servo. To allow this the
386 following hardware setup is required:
387 1. servo2 board connected via servoflex.
388 2. USB key inserted in the servo2.
389 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
390 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800391
392 Args:
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800393 image_path: An URL or a path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800394 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800395
396 Raises:
397 error.TestError: If devserver failed to start.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800398 """
Tom Wai-Hong Tam19ad9682012-10-24 09:33:42 +0800399 if not image_path:
400 return
401
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800402 if self.check_setup_done('reimage'):
403 return
404
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800405 if image_path.startswith(self._HTTP_PREFIX):
406 # TODO(waihong@chromium.org): Add the check of the URL to ensure
407 # it is a test image.
408 devserver = None
409 image_url = image_path
Tom Wai-Hong Tam42f136d2012-10-26 11:11:23 +0800410 elif self.servo.is_localhost():
411 self.assert_test_image_in_path(image_path)
412 # If servod is localhost, i.e. both servod and FAFT see the same
413 # file system, do nothing.
414 devserver = None
415 image_url = image_path
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800416 else:
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800417 self.assert_test_image_in_path(image_path)
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800418 image_dir, image_base = os.path.split(image_path)
419 logging.info('Starting devserver to serve the image...')
420 # The following stdout and stderr arguments should not be None,
421 # even we don't use them. Otherwise, the socket of devserve is
422 # created as fd 1 (as no stdout) but it still thinks stdout is fd
423 # 1 and dump the log to the socket. Wrong HTTP protocol happens.
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800424 devserver = subprocess.Popen(['/usr/lib/devserver/devserver.py',
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800425 '--archive_dir=%s' % image_dir,
426 '--port=%s' % self._DEVSERVER_PORT],
427 stdout=subprocess.PIPE,
428 stderr=subprocess.PIPE)
429 image_url = '%s%s:%s/static/archive/%s' % (
430 self._HTTP_PREFIX,
431 self.get_server_address(),
432 self._DEVSERVER_PORT,
433 image_base)
434
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800435 # Wait devserver startup completely
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800436 time.sleep(self.delay.devserver)
Tom Wai-Hong Tam71818d82012-10-24 14:57:43 +0800437 # devserver is a service running forever. If it is terminated,
438 # some error does happen.
439 if devserver.poll():
440 raise error.TestError('Starting devserver failed, '
441 'returning %d.' % devserver.returncode)
442
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800443 logging.info('Ask Servo to install the image from %s' % image_url)
444 self.servo.image_to_servo_usb(image_url)
445
446 if devserver and devserver.poll() is None:
447 logging.info('Shutting down devserver...')
448 devserver.terminate()
Mike Truty49153d82012-08-21 22:27:30 -0500449
450 # DUT is powered off while imaging servo USB.
451 # Now turn it on.
452 self.servo.power_short_press()
453 self.wait_for_client()
454 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
455
456 install_cmd = 'chromeos-install --yes'
457 if firmware_update:
458 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
459
460 self.register_faft_sequence((
461 { # Step 1, request recovery boot
462 'state_checker': (self.crossystem_checker, {
463 'mainfw_type': ('developer', 'normal'),
464 }),
465 'userspace_action': self.faft_client.request_recovery_boot,
466 'firmware_action': self.wait_fw_screen_and_plug_usb,
467 'install_deps_after_boot': True,
468 },
469 { # Step 2, expected recovery boot
470 'state_checker': (self.crossystem_checker, {
471 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800472 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500473 }),
474 'userspace_action': (self.faft_client.run_shell_command,
475 install_cmd),
476 'reboot_action': self.cold_reboot,
477 'install_deps_after_boot': True,
478 },
479 { # Step 3, expected normal or developer boot (not recovery)
480 'state_checker': (self.crossystem_checker, {
481 'mainfw_type': ('developer', 'normal')
482 }),
483 },
484 ))
485 self.run_faft_sequence()
486 # 'Unplug' any USB keys in the servo from the dut.
Tom Wai-Hong Tam953c7742012-10-16 21:09:31 +0800487 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam6668b762012-10-23 11:45:36 +0800488 # Mark usb_check done so it won't check a test image in USB anymore.
489 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800490 self.mark_setup_done('reimage')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800491
492
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800493 def clear_set_gbb_flags(self, clear_mask, set_mask):
494 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800495
496 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800497 clear_mask: A mask of flags to be cleared.
498 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800499 """
500 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800501 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
502
503 if (gbb_flags != new_flags):
504 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
505 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800506 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800507 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800508 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800509 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800510 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800511 self.run_faft_step({
512 'firmware_action': self.wait_fw_screen_and_ctrl_d,
513 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800514
515
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800516 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800517 """Check if current platform has required EC capabilities.
518
519 Args:
520 required_cap: A list containing required EC capabilities. Pass in
521 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800522 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800523
524 Returns:
525 True if requirements are met. Otherwise, False.
526 """
527 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800528 if not suppress_warning:
529 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800530 return False
531
532 for cap in required_cap:
533 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800534 if not suppress_warning:
535 logging.warn('Requires EC capability "%s" to run this '
536 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800537 return False
538
539 return True
540
541
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800542 def _parse_crossystem_output(self, lines):
543 """Parse the crossystem output into a dict.
544
545 Args:
546 lines: The list of crossystem output strings.
547
548 Returns:
549 A dict which contains the crossystem keys/values.
550
551 Raises:
552 error.TestError: If wrong format in crossystem output.
553
554 >>> seq = FAFTSequence()
555 >>> seq._parse_crossystem_output([ \
556 "arch = x86 # Platform architecture", \
557 "cros_debug = 1 # OS should allow debug", \
558 ])
559 {'cros_debug': '1', 'arch': 'x86'}
560 >>> seq._parse_crossystem_output([ \
561 "arch=x86", \
562 ])
563 Traceback (most recent call last):
564 ...
565 TestError: Failed to parse crossystem output: arch=x86
566 >>> seq._parse_crossystem_output([ \
567 "arch = x86 # Platform architecture", \
568 "arch = arm # Platform architecture", \
569 ])
570 Traceback (most recent call last):
571 ...
572 TestError: Duplicated crossystem key: arch
573 """
574 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
575 parsed_list = {}
576 for line in lines:
577 matched = re.match(pattern, line.strip())
578 if not matched:
579 raise error.TestError("Failed to parse crossystem output: %s"
580 % line)
581 (name, value) = (matched.group(1), matched.group(2))
582 if name in parsed_list:
583 raise error.TestError("Duplicated crossystem key: %s" % name)
584 parsed_list[name] = value
585 return parsed_list
586
587
588 def crossystem_checker(self, expected_dict):
589 """Check the crossystem values matched.
590
591 Given an expect_dict which describes the expected crossystem values,
592 this function check the current crossystem values are matched or not.
593
594 Args:
595 expected_dict: A dict which contains the expected values.
596
597 Returns:
598 True if the crossystem value matched; otherwise, False.
599 """
600 lines = self.faft_client.run_shell_command_get_output('crossystem')
601 got_dict = self._parse_crossystem_output(lines)
602 for key in expected_dict:
603 if key not in got_dict:
604 logging.info('Expected key "%s" not in crossystem result' % key)
605 return False
606 if isinstance(expected_dict[key], str):
607 if got_dict[key] != expected_dict[key]:
608 logging.info("Expected '%s' value '%s' but got '%s'" %
609 (key, expected_dict[key], got_dict[key]))
610 return False
611 elif isinstance(expected_dict[key], tuple):
612 # Expected value is a tuple of possible actual values.
613 if got_dict[key] not in expected_dict[key]:
614 logging.info("Expected '%s' values %s but got '%s'" %
615 (key, str(expected_dict[key]), got_dict[key]))
616 return False
617 else:
618 logging.info("The expected_dict is neither a str nor a dict.")
619 return False
620 return True
621
622
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800623 def vdat_flags_checker(self, mask, value):
624 """Check the flags from VbSharedData matched.
625
626 This function checks the masked flags from VbSharedData using crossystem
627 are matched the given value.
628
629 Args:
630 mask: A bitmask of flags to be matched.
631 value: An expected value.
632
633 Returns:
634 True if the flags matched; otherwise, False.
635 """
636 lines = self.faft_client.run_shell_command_get_output(
637 'crossystem vdat_flags')
638 vdat_flags = int(lines[0], 16)
639 if vdat_flags & mask != value:
640 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
641 (value, mask, vdat_flags))
642 return False
643 return True
644
645
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800646 def ro_normal_checker(self, expected_fw=None, twostop=False):
647 """Check the current boot uses RO boot.
648
649 Args:
650 expected_fw: A string of expected firmware, 'A', 'B', or
651 None if don't care.
652 twostop: True to expect a TwoStop boot; False to expect a RO boot.
653
654 Returns:
655 True if the currect boot firmware matched and used RO boot;
656 otherwise, False.
657 """
658 crossystem_dict = {'tried_fwb': '0'}
659 if expected_fw:
660 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800661 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800662 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
663
664 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800665 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
666 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800667 self.crossystem_checker(crossystem_dict))
668
669
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +0800670 def dev_boot_usb_checker(self, dev_boot_usb=True):
671 """Check the current boot is from a developer USB (Ctrl-U trigger).
672
673 Args:
674 dev_boot_usb: True to expect an USB boot;
675 False to expect an internal device boot.
676
677 Returns:
678 True if the currect boot device matched; otherwise, False.
679 """
680 return (self.crossystem_checker({'mainfw_type': 'developer'})
681 and self.faft_client.is_removable_device_boot() == dev_boot_usb)
682
683
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800684 def root_part_checker(self, expected_part):
685 """Check the partition number of the root device matched.
686
687 Args:
688 expected_part: A string containing the number of the expected root
689 partition.
690
691 Returns:
692 True if the currect root partition number matched; otherwise, False.
693 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800694 part = self.faft_client.get_root_part()[-1]
695 if self.ROOTFS_MAP[expected_part] != part:
696 logging.info("Expected root part %s but got %s" %
697 (self.ROOTFS_MAP[expected_part], part))
698 return False
699 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800700
701
Vic Yang59cac9c2012-05-21 15:28:42 +0800702 def ec_act_copy_checker(self, expected_copy):
703 """Check the EC running firmware copy matches.
704
705 Args:
706 expected_copy: A string containing 'RO', 'A', or 'B' indicating
707 the expected copy of EC running firmware.
708
709 Returns:
710 True if the current EC running copy matches; otherwise, False.
711 """
712 lines = self.faft_client.run_shell_command_get_output('ectool version')
713 pattern = re.compile("Firmware copy: (.*)")
714 for line in lines:
715 matched = pattern.match(line)
716 if matched and matched.group(1) == expected_copy:
717 return True
718 return False
719
720
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800721 def check_root_part_on_non_recovery(self, part):
722 """Check the partition number of root device and on normal/dev boot.
723
724 Returns:
725 True if the root device matched and on normal/dev boot;
726 otherwise, False.
727 """
728 return self.root_part_checker(part) and \
729 self.crossystem_checker({
730 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800731 })
732
733
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800734 def _join_part(self, dev, part):
735 """Return a concatenated string of device and partition number.
736
737 Args:
738 dev: A string of device, e.g.'/dev/sda'.
739 part: A string of partition number, e.g.'3'.
740
741 Returns:
742 A concatenated string of device and partition number, e.g.'/dev/sda3'.
743
744 >>> seq = FAFTSequence()
745 >>> seq._join_part('/dev/sda', '3')
746 '/dev/sda3'
747 >>> seq._join_part('/dev/mmcblk0', '2')
748 '/dev/mmcblk0p2'
749 """
750 if 'mmcblk' in dev:
751 return dev + 'p' + part
752 else:
753 return dev + part
754
755
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800756 def copy_kernel_and_rootfs(self, from_part, to_part):
757 """Copy kernel and rootfs from from_part to to_part.
758
759 Args:
760 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800761 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800762 """
763 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800764 logging.info('Copying kernel from %s to %s. Please wait...' %
765 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800766 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800767 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
768 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
769 logging.info('Copying rootfs from %s to %s. Please wait...' %
770 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800771 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800772 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
773 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800774
775
776 def ensure_kernel_boot(self, part):
777 """Ensure the request kernel boot.
778
779 If not, it duplicates the current kernel to the requested kernel
780 and sets the requested higher priority to ensure it boot.
781
782 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800783 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800784 """
785 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800786 if self.faft_client.diff_kernel_a_b():
787 self.copy_kernel_and_rootfs(
788 from_part=self.OTHER_KERNEL_MAP[part],
789 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800790 self.run_faft_step({
791 'userspace_action': (self.reset_and_prioritize_kernel, part),
792 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800793
794
Vic Yang416f2032012-08-28 10:18:03 +0800795 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800796 """Set hardware write protect pin.
797
798 Args:
799 enable: True if asserting write protect pin. Otherwise, False.
800 """
801 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
802 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800803 self.servo.set('fw_wp', 'on' if enabled else 'off')
804
805
806 def set_EC_write_protect_and_reboot(self, enabled):
807 """Set EC write protect status and reboot to take effect.
808
809 EC write protect is only activated if both hardware write protect pin
810 is asserted and software write protect flag is set. Also, a reboot is
811 required for write protect to take effect.
812
813 Since the software write protect flag cannot be unset if hardware write
814 protect pin is asserted, we need to deasserted the pin first if we are
815 deactivating write protect. Similarly, a reboot is required before we
816 can modify the software flag.
817
818 This method asserts/deasserts hardware write protect pin first, and
819 set corresponding EC software write protect flag.
820
821 Args:
822 enable: True if activating EC write protect. Otherwise, False.
823 """
824 self.set_hardware_write_protect(enabled)
825 if enabled:
826 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800827 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800828 self.sync_and_ec_reboot()
829 else:
830 # Reboot after deasserting hardware write protect pin to deactivate
831 # write protect. And then remove software write protect flag.
832 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800833 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800834
835
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800836 def press_ctrl_d(self):
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800837 """Send Ctrl-D key to DUT."""
Tom Wai-Hong Tam9c15b4b2012-10-29 17:59:26 +0800838 if not self.client_attr.has_keyboard:
839 logging.info('Running usbkm232-ctrld...')
840 os.system('usbkm232-ctrld')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800841 else:
842 self.servo.ctrl_d()
843
844
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800845 def press_ctrl_u(self):
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800846 """Send Ctrl-U key to DUT.
847
848 Raises:
849 error.TestError: if a non-Chrome EC device or no Ctrl-U command given
850 on a no-build-in-keyboard device.
851 """
Tom Wai-Hong Tam9c15b4b2012-10-29 17:59:26 +0800852 if not self.client_attr.has_keyboard:
853 logging.info('Running usbkm232-ctrlu...')
854 os.system('usbkm232-ctrlu')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800855 elif self.check_ec_capability(['keyboard'], suppress_warning=True):
856 self.ec.key_down('<ctrl_l>')
857 self.ec.key_down('u')
858 self.ec.key_up('u')
859 self.ec.key_up('<ctrl_l>')
860 elif self.client_attr.has_keyboard:
861 raise error.TestError(
862 "Can't send Ctrl-U to DUT without using Chrome EC.")
863 else:
864 raise error.TestError(
865 "Should specify the ctrl_u_cmd argument.")
866
867
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800868 def press_enter(self):
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800869 """Send Enter key to DUT."""
Tom Wai-Hong Tam9c15b4b2012-10-29 17:59:26 +0800870 if not self.client_attr.has_keyboard:
871 logging.info('Running usbkm232-enter...')
872 os.system('usbkm232-enter')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800873 else:
874 self.servo.enter_key()
875
876
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800877 def wait_fw_screen_and_ctrl_d(self):
878 """Wait for firmware warning screen and press Ctrl-D."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800879 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800880 self.press_ctrl_d()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800881
882
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800883 def wait_fw_screen_and_ctrl_u(self):
884 """Wait for firmware warning screen and press Ctrl-U."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800885 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800886 self.press_ctrl_u()
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800887
888
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800889 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
890 """Wait for firmware warning screen and trigger recovery boot."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800891 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800892 self.press_enter()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800893
894 # For Alex/ZGB, there is a dev warning screen in text mode.
895 # Skip it by pressing Ctrl-D.
896 if need_dev_transition:
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800897 time.sleep(self.delay.legacy_text_screen)
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +0800898 self.press_ctrl_d()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800899
900
Mike Truty49153d82012-08-21 22:27:30 -0500901 def wait_fw_screen_and_unplug_usb(self):
902 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800903 time.sleep(self.delay.load_usb)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800904 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800905 time.sleep(self.delay.between_usb_plug)
Mike Truty49153d82012-08-21 22:27:30 -0500906
907
908 def wait_fw_screen_and_plug_usb(self):
909 """Wait for firmware warning screen and then unplug and plug the USB."""
910 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800911 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
912
913
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800914 def wait_fw_screen_and_press_power(self):
915 """Wait for firmware warning screen and press power button."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800916 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800917 # While the firmware screen, the power button probing loop sleeps
918 # 0.25 second on every scan. Use the normal delay (1.2 second) for
919 # power press.
920 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800921
922
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800923 def wait_longer_fw_screen_and_press_power(self):
924 """Wait for firmware screen without timeout and press power button."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800925 time.sleep(self.delay.dev_screen_timeout)
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800926 self.wait_fw_screen_and_press_power()
927
928
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800929 def wait_fw_screen_and_close_lid(self):
930 """Wait for firmware warning screen and close lid."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800931 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800932 self.servo.lid_close()
933
934
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800935 def wait_longer_fw_screen_and_close_lid(self):
936 """Wait for firmware screen without timeout and close lid."""
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800937 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800938 self.wait_fw_screen_and_close_lid()
939
940
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800941 def setup_gbb_flags(self):
942 """Setup the GBB flags for FAFT test."""
943 if self.check_setup_done('gbb_flags'):
944 return
945
946 logging.info('Set proper GBB flags for test.')
947 self.clear_set_gbb_flags(vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY |
948 vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
949 vboot.GBB_FLAG_FORCE_DEV_BOOT_USB |
950 vboot.GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK,
951 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
952 self.mark_setup_done('gbb_flags')
953
954
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800955 def setup_tried_fwb(self, tried_fwb):
956 """Setup for fw B tried state.
957
958 It makes sure the system in the requested fw B tried state. If not, it
959 tries to do so.
960
961 Args:
962 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
963 """
964 if tried_fwb:
965 if not self.crossystem_checker({'tried_fwb': '1'}):
966 logging.info(
967 'Firmware is not booted with tried_fwb. Reboot into it.')
968 self.run_faft_step({
969 'userspace_action': self.faft_client.set_try_fw_b,
970 })
971 else:
972 if not self.crossystem_checker({'tried_fwb': '0'}):
973 logging.info(
974 'Firmware is booted with tried_fwb. Reboot to clear.')
975 self.run_faft_step({})
976
977
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800978 def enable_rec_mode_and_reboot(self):
979 """Switch to rec mode and reboot.
980
981 This method emulates the behavior of the old physical recovery switch,
982 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
983 recovery mode, i.e. just press Power + Esc + Refresh.
984 """
Tom Wai-Hong Tam80419a82012-10-30 09:10:00 +0800985 if self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800986 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800987 self.servo.set('cold_reset', 'on')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800988 time.sleep(self.delay.hold_cold_reset)
Vic Yanga7250662012-08-31 04:00:08 +0800989 self.servo.set('cold_reset', 'off')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800990 time.sleep(self.delay.ec_boot_to_console)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800991 self.ec.send_command("reboot ap-off")
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800992 time.sleep(self.delay.ec_boot_to_console)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800993 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +0800994 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800995 else:
996 self.servo.enable_recovery_mode()
997 self.cold_reboot()
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +0800998 time.sleep(self.delay.ec_reboot_cmd)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800999 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001000
1001
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001002 def enable_dev_mode_and_reboot(self):
1003 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001004 if self.client_attr.keyboard_dev:
1005 self.enable_keyboard_dev_mode()
1006 else:
1007 self.servo.enable_development_mode()
1008 self.faft_client.run_shell_command(
1009 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001010
1011
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001012 def enable_normal_mode_and_reboot(self):
1013 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001014 if self.client_attr.keyboard_dev:
1015 self.disable_keyboard_dev_mode()
1016 else:
1017 self.servo.disable_development_mode()
1018 self.faft_client.run_shell_command(
1019 'chromeos-firmwareupdate --mode tonormal && reboot')
1020
1021
1022 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
1023 """Wait for firmware screen and then switch into or out of dev mode.
1024
1025 Args:
1026 dev: True if switching into dev mode. Otherwise, False.
1027 """
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001028 time.sleep(self.delay.firmware_screen)
Vic Yange7553162012-06-20 16:20:47 +08001029 if dev:
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +08001030 self.press_ctrl_d()
Vic Yange7553162012-06-20 16:20:47 +08001031 else:
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +08001032 self.press_enter()
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001033 time.sleep(self.delay.firmware_screen)
Tom Wai-Hong Tam91612bc2012-10-29 16:04:21 +08001034 self.press_enter()
Vic Yange7553162012-06-20 16:20:47 +08001035
1036
1037 def enable_keyboard_dev_mode(self):
1038 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001039 # Plug out USB disk for preventing recovery boot without warning
1040 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001041 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001042 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001043 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001044 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001045
1046
1047 def disable_keyboard_dev_mode(self):
1048 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001049 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001050 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001051 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001052 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001053 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001054
1055
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001056 def setup_dev_mode(self, dev_mode):
1057 """Setup for development mode.
1058
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001059 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001060 tries to do so.
1061
1062 Args:
1063 dev_mode: True if requested in dev mode; False if normal mode.
1064 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001065 # Change the default firmware_action for dev mode passing the fw screen.
1066 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001067 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1068 else None),
1069 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001070 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001071 if (not self.client_attr.keyboard_dev and
1072 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001073 logging.info('Dev switch is not on. Now switch it on.')
1074 self.servo.enable_development_mode()
1075 if not self.crossystem_checker({'devsw_boot': '1',
1076 'mainfw_type': 'developer'}):
1077 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001078 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001079 'userspace_action': None if self.client_attr.keyboard_dev
1080 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001081 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001082 'reboot_action': self.enable_keyboard_dev_mode if
1083 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001084 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001085 else:
Vic Yange7553162012-06-20 16:20:47 +08001086 if (not self.client_attr.keyboard_dev and
1087 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001088 logging.info('Dev switch is not off. Now switch it off.')
1089 self.servo.disable_development_mode()
1090 if not self.crossystem_checker({'devsw_boot': '0',
1091 'mainfw_type': 'normal'}):
1092 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001093 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001094 'userspace_action': None if self.client_attr.keyboard_dev
1095 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001096 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001097 'reboot_action': self.disable_keyboard_dev_mode if
1098 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001099 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001100
1101
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001102 def setup_kernel(self, part):
1103 """Setup for kernel test.
1104
1105 It makes sure both kernel A and B bootable and the current boot is
1106 the requested kernel part.
1107
1108 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001109 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001110 """
1111 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001112 if self.faft_client.diff_kernel_a_b():
1113 self.copy_kernel_and_rootfs(from_part=part,
1114 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001115 self.reset_and_prioritize_kernel(part)
1116
1117
1118 def reset_and_prioritize_kernel(self, part):
1119 """Make the requested partition highest priority.
1120
1121 This function also reset kerenl A and B to bootable.
1122
1123 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001124 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001125 """
1126 root_dev = self.faft_client.get_root_dev()
1127 # Reset kernel A and B to bootable.
1128 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1129 (self.KERNEL_MAP['a'], root_dev))
1130 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1131 (self.KERNEL_MAP['b'], root_dev))
1132 # Set kernel part highest priority.
1133 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1134 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001135 # Safer to sync and wait until the cgpt status written to the disk.
1136 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001137 time.sleep(self.delay.sync)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001138
1139
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001140 def warm_reboot(self):
1141 """Request a warm reboot.
1142
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001143 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001144 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001145 # Use cold reset if the warm reset is broken.
1146 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001147 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1148 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001149 else:
1150 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001151
1152
1153 def cold_reboot(self):
1154 """Request a cold reboot.
1155
1156 A wrapper for underlying servo cold reset.
1157 """
Gediminas Ramanauskasc6025692012-10-23 14:33:40 -07001158 if self.client_attr.broken_warm_reset:
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001159 self.servo.set('pwr_button', 'press')
1160 self.servo.set('cold_reset', 'on')
1161 self.servo.set('cold_reset', 'off')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001162 time.sleep(self.delay.ec_boot_to_pwr_button)
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001163 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001164 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001165 # We don't use servo.cold_reset() here because software sync is
1166 # not yet finished, and device may or may not come up after cold
1167 # reset. Pressing power button before firmware comes up solves this.
1168 #
1169 # The correct behavior should be (not work now):
1170 # - If rebooting EC with rec mode on, power on AP and it boots
1171 # into recovery mode.
1172 # - If rebooting EC with rec mode off, power on AP for software
1173 # sync. Then AP checks if lid open or not. If lid open, continue;
1174 # otherwise, shut AP down and need servo for a power button
1175 # press.
1176 self.servo.set('cold_reset', 'on')
1177 self.servo.set('cold_reset', 'off')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001178 time.sleep(self.delay.ec_boot_to_pwr_button)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001179 self.servo.power_short_press()
1180 else:
1181 self.servo.cold_reset()
1182
1183
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001184 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001185 """Request the client sync and do a warm reboot.
1186
1187 This is the default reboot action on FAFT.
1188 """
1189 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001190 time.sleep(self.delay.sync)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001191 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001192
1193
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001194 def sync_and_cold_reboot(self):
1195 """Request the client sync and do a cold reboot.
1196
1197 This reboot action is used to reset EC for recovery mode.
1198 """
1199 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001200 time.sleep(self.delay.sync)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001201 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001202
1203
Vic Yangaeb10392012-08-28 09:25:09 +08001204 def sync_and_ec_reboot(self, args=''):
1205 """Request the client sync and do a EC triggered reboot.
1206
1207 Args:
1208 args: Arguments passed to "ectool reboot_ec". Including:
1209 RO: jump to EC RO firmware.
1210 RW: jump to EC RW firmware.
1211 cold: Cold/hard reboot.
1212 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001213 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001214 time.sleep(self.delay.sync)
Vic Yangaeb10392012-08-28 09:25:09 +08001215 # Since EC reboot happens immediately, delay before actual reboot to
1216 # allow FAFT client returning.
1217 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001218 (self.delay.ec_reboot_cmd, args))
1219 time.sleep(self.delay.ec_reboot_cmd)
Vic Yangf86728a2012-07-30 10:44:07 +08001220 self.check_lid_and_power_on()
1221
1222
Chun-ting Changa4f65532012-10-17 16:57:28 +08001223 def sync_and_reboot_with_factory_install_shim(self):
1224 """Request the client sync and do a warm reboot to recovery mode.
1225
1226 After reboot, the client will use factory install shim to reset TPM
1227 values. The client ignore TPM rollback, so here forces it to recovery
1228 mode.
1229 """
1230 is_dev = self.crossystem_checker({'devsw_boot': '1'})
1231 if not is_dev:
1232 self.enable_dev_mode_and_reboot()
1233 time.sleep(self.SYNC_DELAY)
1234 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001235 time.sleep(self.delay.install_shim_done)
Chun-ting Changa4f65532012-10-17 16:57:28 +08001236 self.warm_reboot()
1237
1238
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001239 def full_power_off_and_on(self):
1240 """Shutdown the device by pressing power button and power on again."""
1241 # Press power button to trigger Chrome OS normal shutdown process.
1242 self.servo.power_normal_press()
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001243 time.sleep(self.delay.shutdown)
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001244 # Short press power button to boot DUT again.
1245 self.servo.power_short_press()
1246
1247
Vic Yangf86728a2012-07-30 10:44:07 +08001248 def check_lid_and_power_on(self):
1249 """
1250 On devices with EC software sync, system powers on after EC reboots if
1251 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1252 This method checks lid switch state and presses power button if
1253 necessary.
1254 """
1255 if self.servo.get("lid_open") == "no":
Tom Wai-Hong Tam41738762012-10-29 14:32:39 +08001256 time.sleep(self.delay.software_sync)
Vic Yangf86728a2012-07-30 10:44:07 +08001257 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001258
1259
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001260 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1261 """Modify the kernel header magic in USB stick.
1262
1263 The kernel header magic is the first 8-byte of kernel partition.
1264 We modify it to make it fail on kernel verification check.
1265
1266 Args:
1267 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1268 from_magic: A string of magic which we change it from.
1269 to_magic: A string of magic which we change it to.
1270
1271 Raises:
1272 error.TestError: if failed to change magic.
1273 """
1274 assert len(from_magic) == 8
1275 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001276 # USB image only contains one kernel.
1277 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001278 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1279 current_magic = utils.system_output(read_cmd)
1280 if current_magic == to_magic:
1281 logging.info("The kernel magic is already %s." % current_magic)
1282 return
1283 if current_magic != from_magic:
1284 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1285
1286 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1287 (from_magic, to_magic))
1288 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1289 " 2>/dev/null" % (to_magic, kernel_part))
1290 utils.system(write_cmd)
1291
1292 if utils.system_output(read_cmd) != to_magic:
1293 raise error.TestError("Failed to write new magic.")
1294
1295
1296 def corrupt_usb_kernel(self, usb_dev):
1297 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1298
1299 Args:
1300 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1301 """
1302 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1303 self.CORRUPTED_MAGIC)
1304
1305
1306 def restore_usb_kernel(self, usb_dev):
1307 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1308
1309 Args:
1310 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1311 """
1312 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1313 self.CHROMEOS_MAGIC)
1314
1315
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001316 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001317 """Call the action function with/without arguments.
1318
1319 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001320 action_tuple: A function, or a tuple (function, args, error_msg),
1321 in which, args and error_msg are optional. args is
1322 either a value or a tuple if multiple arguments.
1323 check_status: Check the return value of action function. If not
1324 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001325
1326 Returns:
1327 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001328
1329 Raises:
1330 error.TestError: An error when the action function is not callable.
1331 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001332 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001333 action = action_tuple
1334 args = ()
1335 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001336 if isinstance(action_tuple, tuple):
1337 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001338 if len(action_tuple) >= 2:
1339 args = action_tuple[1]
1340 if not isinstance(args, tuple):
1341 args = (args,)
1342 if len(action_tuple) >= 3:
Tom Wai-Hong Tamff560882012-10-15 16:50:06 +08001343 error_msg = action_tuple[2]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001344
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001345 if action is None:
1346 return
1347
1348 if not callable(action):
1349 raise error.TestError('action is not callable!')
1350
1351 info_msg = 'calling %s' % str(action)
1352 if args:
1353 info_msg += ' with args %s' % str(args)
1354 logging.info(info_msg)
1355 ret = action(*args)
1356
1357 if check_status and not ret:
1358 raise error.TestFail('%s: %s returning %s' %
1359 (error_msg, info_msg, str(ret)))
1360 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001361
1362
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001363 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1364 post_power_action=None):
1365 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1366
1367 Args:
1368 shutdown_action: a function which makes DUT shutdown, like pressing
1369 power key.
1370 pre_power_action: a function which is called before next power on.
1371 post_power_action: a function which is called after next power on.
1372
1373 Raises:
1374 error.TestFail: if the shutdown_action() failed to turn DUT off.
1375 """
1376 self._call_action(shutdown_action)
1377 logging.info('Wait to ensure DUT shut down...')
1378 try:
1379 self.wait_for_client()
1380 raise error.TestFail(
1381 'Should shut the device down after calling %s.' %
1382 str(shutdown_action))
1383 except AssertionError:
1384 logging.info(
1385 'DUT is surely shutdown. We are going to power it on again...')
1386
1387 if pre_power_action:
1388 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001389 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001390 if post_power_action:
1391 self._call_action(post_power_action)
1392
1393
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001394 def register_faft_template(self, template):
1395 """Register FAFT template, the default FAFT_STEP of each step.
1396
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001397 Any missing field falls back to the original faft_template.
1398
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001399 Args:
1400 template: A FAFT_STEP dict.
1401 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001402 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001403
1404
1405 def register_faft_sequence(self, sequence):
1406 """Register FAFT sequence.
1407
1408 Args:
1409 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1410 """
1411 self._faft_sequence = sequence
1412
1413
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001414 def run_faft_step(self, step, no_reboot=False):
1415 """Run a single FAFT step.
1416
1417 Any missing field falls back to faft_template. An empty step means
1418 running the default faft_template.
1419
1420 Args:
1421 step: A FAFT_STEP dict.
1422 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001423
1424 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001425 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001426 error.TestFail: Test failed in waiting DUT reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001427 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001428 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1429 'firmware_action', 'install_deps_after_boot')
1430
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001431 test = {}
1432 test.update(self._faft_template)
1433 test.update(step)
1434
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001435 for key in test:
1436 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001437 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001438
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001439 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001440 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001441
1442 self._call_action(test['userspace_action'])
1443
1444 # Don't run reboot_action and firmware_action if no_reboot is True.
1445 if not no_reboot:
1446 self._call_action(test['reboot_action'])
1447 self.wait_for_client_offline()
1448 self._call_action(test['firmware_action'])
1449
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001450 try:
1451 if 'install_deps_after_boot' in test:
1452 self.wait_for_client(
1453 install_deps=test['install_deps_after_boot'])
1454 else:
1455 self.wait_for_client()
1456 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001457 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001458 self.reset_client()
Tom Wai-Hong Tam4bb85e22012-10-25 14:35:24 +08001459 if self._trapped_in_recovery_reason:
1460 raise error.TestFail('Trapped in the recovery reason: %d' %
1461 self._trapped_in_recovery_reason)
1462 else:
1463 raise error.TestFail('Timed out waiting for DUT reboot.')
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001464
1465
1466 def run_faft_sequence(self):
1467 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001468 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001469 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001470 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001471 logging.info('======== Running FAFT sequence step %d ========' %
1472 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001473 # Don't reboot in the last step.
1474 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001475 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001476
1477
ctchang38ae4922012-09-03 17:01:16 +08001478 def get_current_firmware_sha(self):
1479 """Get current firmware sha of body and vblock.
1480
1481 Returns:
1482 Current firmware sha follows the order (
1483 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1484 """
1485 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1486 self.faft_client.get_firmware_sha('a'),
1487 self.faft_client.get_firmware_sig_sha('b'),
1488 self.faft_client.get_firmware_sha('b'))
1489 return current_firmware_sha
1490
1491
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001492 def is_firmware_changed(self):
1493 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001494
1495 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001496 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001497 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001498 # Device may not be rebooted after test.
1499 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001500
1501 current_sha = self.get_current_firmware_sha()
1502
1503 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001504 return False
ctchang38ae4922012-09-03 17:01:16 +08001505 else:
ctchang38ae4922012-09-03 17:01:16 +08001506 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1507 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1508 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1509 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001510 logging.info("Firmware changed:")
1511 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1512 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1513 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1514 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1515 return True
ctchang38ae4922012-09-03 17:01:16 +08001516
1517
1518 def backup_firmware(self, suffix='.original'):
1519 """Backup firmware to file, and then send it to host.
1520
1521 Args:
1522 suffix: a string appended to backup file name
1523 """
1524 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001525 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1526 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1527 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001528
1529 self._backup_firmware_sha = self.get_current_firmware_sha()
1530 logging.info('Backup firmware stored in %s with suffix %s' % (
1531 self.resultsdir, suffix))
1532
1533
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001534 def is_firmware_saved(self):
1535 """Check if a firmware saved (called backup_firmware before).
1536
1537 Returns:
1538 True if the firmware is backuped; otherwise False.
1539 """
1540 return self._backup_firmware_sha != ()
1541
1542
ctchang38ae4922012-09-03 17:01:16 +08001543 def restore_firmware(self, suffix='.original'):
1544 """Restore firmware from host in resultsdir.
1545
1546 Args:
1547 suffix: a string appended to backup file name
1548 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001549 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001550 return
1551
1552 # Backup current corrupted firmware.
1553 self.backup_firmware(suffix='.corrupt')
1554
1555 # Restore firmware.
1556 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001557 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1558 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001559
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001560 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001561 self.sync_and_warm_reboot()
1562 self.wait_for_client_offline()
1563 self.wait_for_client()
1564
ctchang38ae4922012-09-03 17:01:16 +08001565 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001566
1567
1568 def setup_firmwareupdate_shellball(self, shellball=None):
1569 """Deside a shellball to use in firmware update test.
1570
1571 Check if there is a given shellball, and it is a shell script. Then,
1572 send it to the remote host. Otherwise, use
1573 /usr/sbin/chromeos-firmwareupdate.
1574
1575 Args:
1576 shellball: path of a shellball or default to None.
1577
1578 Returns:
1579 Path of shellball in remote host.
1580 If use default shellball, reutrn None.
1581 """
1582 updater_path = None
1583 if shellball:
1584 # Determine the firmware file is a shellball or a raw binary.
1585 is_shellball = (utils.system_output("file %s" % shellball).find(
1586 "shell script") != -1)
1587 if is_shellball:
1588 logging.info('Device will update firmware with shellball %s'
1589 % shellball)
1590 temp_dir = self.faft_client.create_temp_dir('shellball_')
1591 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1592 self._client.send_file(shellball, temp_shellball)
1593 updater_path = temp_shellball
1594 else:
1595 raise error.TestFail(
1596 'The given shellball is not a shell script.')
1597 return updater_path