blob: 78b7026571400ff3a5ab3bdb4ba46657709e9b78 [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 Tam76c75072011-10-25 18:00:12 +080011import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012import time
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080013
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080014from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080015from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +080016from autotest_lib.server.cros import vboot_constants as vboot
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +080017from autotest_lib.server.cros.chrome_ec import ChromeEC
Vic Yangebd6de62012-06-26 14:25:57 +080018from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
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 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 Tama70f0fe2011-09-02 18:28:47 +080078 """
79 version = 1
80
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080081 # Mapping of partition number of kernel and rootfs.
82 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
83 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
84 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
85 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
86
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080087 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080088 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080089 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080090 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +080091 # Delay for waiting beep done.
92 BEEP_DELAY = 1
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080093 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080094 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080096 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080097 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080098 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080099 # Delay for waiting client to return before EC reboot
100 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800101 # Delay for waiting client to full power off
102 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800103 # Delay between EC reboot and pressing power button
104 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800105 # Delay of EC software sync hash calculating time
106 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800107 # Delay between EC boot and ChromeEC console functional
108 EC_BOOT_DELAY = 0.5
109 # Duration of holding cold_reset to reset device
110 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800111
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800112 # The developer screen timeouts fit our spec.
113 DEV_SCREEN_TIMEOUT = 30
114
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800115 CHROMEOS_MAGIC = "CHROMEOS"
116 CORRUPTED_MAGIC = "CORRUPTD"
117
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800118 _HTTP_PREFIX = 'http://'
119 _DEVSERVER_PORT = '8090'
120
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800121 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800122 _faft_sequence = ()
123
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800124 _customized_key_commands = {
125 'ctrl_d': None,
126 'ctrl_u': None,
127 'enter': None,
128 'rec_reboot': None,
129 'space': None,
130 }
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800131 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800132 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800133
ctchang38ae4922012-09-03 17:01:16 +0800134 _backup_firmware_sha = ()
135
Vic Yangdbaba8f2012-10-17 16:05:35 +0800136 # True if this is the first test in the same run
137 _first_test = True
138 _setup_invalidated = False
139
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)
148
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800149 # Keep the arguments which will be used later.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800150 for key in self._customized_key_commands:
151 key_cmd = key + '_cmd'
152 if key_cmd in args:
153 self._customized_key_commands[key] = args[key_cmd]
154 logging.info('Customized %s key command: %s' %
155 (key, args[key_cmd]))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800156 if 'image' in args:
157 self._install_image_path = args['image']
158 logging.info('Install Chrome OS test image path: %s' %
159 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800160 if 'firmware_update' in args and args['firmware_update'].lower() \
161 not in ('0', 'false', 'no'):
162 if self._install_image_path:
163 self._firmware_update = True
164 logging.info('Also update firmware after installing.')
165 else:
166 logging.warning('Firmware update will not not performed '
167 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800168
169 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
170 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800171 if use_faft:
172 self.client_attr = FAFTClientAttribute(
173 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800174
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800175 if self.client_attr.chrome_ec:
176 self.ec = ChromeEC(self.servo)
177
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700178 # Setting up key matrix mapping
179 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
180
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800181
182 def setup(self):
183 """Autotest setup function."""
184 super(FAFTSequence, self).setup()
185 if not self._remote_infos['faft']['used']:
186 raise error.TestError('The use_faft flag should be enabled.')
187 self.register_faft_template({
188 'state_checker': (None),
189 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800190 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800191 'firmware_action': (None)
192 })
Vic Yangdbaba8f2012-10-17 16:05:35 +0800193 if FAFTSequence._first_test:
194 logging.info('Running first test. Set proper GBB flags.')
195 self.clear_set_gbb_flags(vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY |
196 vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
197 vboot.GBB_FLAG_FORCE_DEV_BOOT_USB |
198 vboot.GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK,
199 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800200 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800201 self.install_test_image(self._install_image_path,
202 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800203
204
205 def cleanup(self):
206 """Autotest cleanup function."""
207 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800208 self._faft_template = {}
Vic Yangdbaba8f2012-10-17 16:05:35 +0800209 FAFTSequence._first_test = self._setup_invalidated
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800210 super(FAFTSequence, self).cleanup()
211
212
Vic Yangdbaba8f2012-10-17 16:05:35 +0800213 def invalidate_setup(self):
214 """Invalidate current setup flag.
215
216 This reset the first test flag so that the next test setup
217 properly again.
218 """
219 self._setup_invalidated = True
220
221
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800222 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800223 """Reset client, if necessary.
224
225 This method is called when the client is not responsive. It may be
226 caused by the following cases:
227 - network flaky (can be recovered by replugging the Ethernet);
228 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
229 - corrupted firmware;
230 - corrutped OS image.
231 """
232 # DUT works fine, done.
233 if self._ping_test(self._client.ip, timeout=5):
234 return
235
236 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
237 # first reset item.
238
239 # DUT may halt on a firmware screen. Try cold reboot.
240 logging.info('Try cold reboot...')
241 self.cold_reboot()
242 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800243 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800244 return
245 except AssertionError:
246 pass
247
248 # DUT may be broken by a corrupted firmware. Restore firmware.
249 # We assume the recovery boot still works fine. Since the recovery
250 # code is in RO region and all FAFT tests don't change the RO region
251 # except GBB.
252 if self.is_firmware_saved():
253 self.ensure_client_in_recovery()
254 logging.info('Try restore the original firmware...')
255 if self.is_firmware_changed():
256 try:
257 self.restore_firmware()
258 return
259 except AssertionError:
260 logging.info('Restoring firmware doesn\'t help.')
261
262 # DUT may be broken by a corrupted OS image. Restore OS image.
263 self.ensure_client_in_recovery()
264 logging.info('Try restore the OS image...')
265 self.faft_client.run_shell_command('chromeos-install --yes')
266 self.sync_and_warm_reboot()
267 self.wait_for_client_offline()
268 try:
269 self.wait_for_client(install_deps=True)
270 logging.info('Successfully restore OS image.')
271 return
272 except AssertionError:
273 logging.info('Restoring OS image doesn\'t help.')
274
275
276 def ensure_client_in_recovery(self):
277 """Ensure client in recovery boot; reboot into it if necessary.
278
279 Raises:
280 error.TestError: if failed to boot the USB image.
281 """
282 # DUT works fine and is already in recovery boot, done.
283 if self._ping_test(self._client.ip, timeout=5):
284 if self.crossystem_checker({'mainfw_type': 'recovery'}):
285 return
286
287 logging.info('Try boot into USB image...')
288 self.servo.enable_usb_hub(host=True)
289 self.enable_rec_mode_and_reboot()
290 self.wait_fw_screen_and_plug_usb()
291 try:
292 self.wait_for_client(install_deps=True)
293 except AssertionError:
294 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800295
296
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800297 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800298 """Assert an USB disk plugged-in on servo and a test image inside.
299
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800300 Args:
301 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
302 If None, it is detected automatically.
303
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800304 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800305 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800306 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800307 if usb_dev:
308 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
309 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700310 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800311 usb_dev = self.servo.probe_host_usb_dev()
312 if not usb_dev:
313 raise error.TestError(
314 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800315
316 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800317 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800318 code = utils.system(
319 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
320 tmp_dir, ignore_status=True)
Yusuf Mohsinally6d9aa582012-10-19 09:49:53 -0700321 utils.system('sudo umount -l %s' % tmp_dir)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800322 os.removedirs(tmp_dir)
323 if code != 0:
324 raise error.TestError(
325 'The image in the USB disk should be a test image.')
326
327
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800328 def get_server_address(self):
329 """Get the server address seen from the client.
330
331 Returns:
332 A string of the server address.
333 """
334 r = self.faft_client.run_shell_command_get_output("echo $SSH_CLIENT")
335 return r[0].split()[0]
336
337
Simran Basi741b5d42012-05-18 11:27:15 -0700338 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800339 """Install the test image specied by the path onto the USB and DUT disk.
340
341 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500342 recovery mode. Then runs 'chromeos-install' (and possible
343 chromeos-firmwareupdate') to install it to DUT disk.
344
345 Sample command line:
346
347 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
348 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
349 server/site_tests/firmware_XXXX/control
350
351 This test requires an automated recovery to occur while simulating
352 inserting and removing the usb key from the servo. To allow this the
353 following hardware setup is required:
354 1. servo2 board connected via servoflex.
355 2. USB key inserted in the servo2.
356 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
357 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800358
359 Args:
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800360 image_path: An URL or a path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800361 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800362 """
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800363 if image_path.startswith(self._HTTP_PREFIX):
364 # TODO(waihong@chromium.org): Add the check of the URL to ensure
365 # it is a test image.
366 devserver = None
367 image_url = image_path
368 else:
369 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
370 image_path)
371 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800372
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800373 image_dir, image_base = os.path.split(image_path)
374 logging.info('Starting devserver to serve the image...')
375 # The following stdout and stderr arguments should not be None,
376 # even we don't use them. Otherwise, the socket of devserve is
377 # created as fd 1 (as no stdout) but it still thinks stdout is fd
378 # 1 and dump the log to the socket. Wrong HTTP protocol happens.
379 devserver = subprocess.Popen(['start_devserver',
380 '--archive_dir=%s' % image_dir,
381 '--port=%s' % self._DEVSERVER_PORT],
382 stdout=subprocess.PIPE,
383 stderr=subprocess.PIPE)
384 image_url = '%s%s:%s/static/archive/%s' % (
385 self._HTTP_PREFIX,
386 self.get_server_address(),
387 self._DEVSERVER_PORT,
388 image_base)
389
390 logging.info('Ask Servo to install the image from %s' % image_url)
391 self.servo.image_to_servo_usb(image_url)
392
393 if devserver and devserver.poll() is None:
394 logging.info('Shutting down devserver...')
395 devserver.terminate()
Mike Truty49153d82012-08-21 22:27:30 -0500396
397 # DUT is powered off while imaging servo USB.
398 # Now turn it on.
399 self.servo.power_short_press()
400 self.wait_for_client()
401 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
402
403 install_cmd = 'chromeos-install --yes'
404 if firmware_update:
405 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
406
407 self.register_faft_sequence((
408 { # Step 1, request recovery boot
409 'state_checker': (self.crossystem_checker, {
410 'mainfw_type': ('developer', 'normal'),
411 }),
412 'userspace_action': self.faft_client.request_recovery_boot,
413 'firmware_action': self.wait_fw_screen_and_plug_usb,
414 'install_deps_after_boot': True,
415 },
416 { # Step 2, expected recovery boot
417 'state_checker': (self.crossystem_checker, {
418 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800419 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500420 }),
421 'userspace_action': (self.faft_client.run_shell_command,
422 install_cmd),
423 'reboot_action': self.cold_reboot,
424 'install_deps_after_boot': True,
425 },
426 { # Step 3, expected normal or developer boot (not recovery)
427 'state_checker': (self.crossystem_checker, {
428 'mainfw_type': ('developer', 'normal')
429 }),
430 },
431 ))
432 self.run_faft_sequence()
433 # 'Unplug' any USB keys in the servo from the dut.
Tom Wai-Hong Tam953c7742012-10-16 21:09:31 +0800434 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800435
436
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800437 def clear_set_gbb_flags(self, clear_mask, set_mask):
438 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800439
440 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800441 clear_mask: A mask of flags to be cleared.
442 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800443 """
444 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800445 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
446
447 if (gbb_flags != new_flags):
448 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
449 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800450 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800451 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800452 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800453 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800454 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800455 self.run_faft_step({
456 'firmware_action': self.wait_fw_screen_and_ctrl_d,
457 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800458
459
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800460 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800461 """Check if current platform has required EC capabilities.
462
463 Args:
464 required_cap: A list containing required EC capabilities. Pass in
465 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800466 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800467
468 Returns:
469 True if requirements are met. Otherwise, False.
470 """
471 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800472 if not suppress_warning:
473 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800474 return False
475
476 for cap in required_cap:
477 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800478 if not suppress_warning:
479 logging.warn('Requires EC capability "%s" to run this '
480 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800481 return False
482
483 return True
484
485
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800486 def _parse_crossystem_output(self, lines):
487 """Parse the crossystem output into a dict.
488
489 Args:
490 lines: The list of crossystem output strings.
491
492 Returns:
493 A dict which contains the crossystem keys/values.
494
495 Raises:
496 error.TestError: If wrong format in crossystem output.
497
498 >>> seq = FAFTSequence()
499 >>> seq._parse_crossystem_output([ \
500 "arch = x86 # Platform architecture", \
501 "cros_debug = 1 # OS should allow debug", \
502 ])
503 {'cros_debug': '1', 'arch': 'x86'}
504 >>> seq._parse_crossystem_output([ \
505 "arch=x86", \
506 ])
507 Traceback (most recent call last):
508 ...
509 TestError: Failed to parse crossystem output: arch=x86
510 >>> seq._parse_crossystem_output([ \
511 "arch = x86 # Platform architecture", \
512 "arch = arm # Platform architecture", \
513 ])
514 Traceback (most recent call last):
515 ...
516 TestError: Duplicated crossystem key: arch
517 """
518 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
519 parsed_list = {}
520 for line in lines:
521 matched = re.match(pattern, line.strip())
522 if not matched:
523 raise error.TestError("Failed to parse crossystem output: %s"
524 % line)
525 (name, value) = (matched.group(1), matched.group(2))
526 if name in parsed_list:
527 raise error.TestError("Duplicated crossystem key: %s" % name)
528 parsed_list[name] = value
529 return parsed_list
530
531
532 def crossystem_checker(self, expected_dict):
533 """Check the crossystem values matched.
534
535 Given an expect_dict which describes the expected crossystem values,
536 this function check the current crossystem values are matched or not.
537
538 Args:
539 expected_dict: A dict which contains the expected values.
540
541 Returns:
542 True if the crossystem value matched; otherwise, False.
543 """
544 lines = self.faft_client.run_shell_command_get_output('crossystem')
545 got_dict = self._parse_crossystem_output(lines)
546 for key in expected_dict:
547 if key not in got_dict:
548 logging.info('Expected key "%s" not in crossystem result' % key)
549 return False
550 if isinstance(expected_dict[key], str):
551 if got_dict[key] != expected_dict[key]:
552 logging.info("Expected '%s' value '%s' but got '%s'" %
553 (key, expected_dict[key], got_dict[key]))
554 return False
555 elif isinstance(expected_dict[key], tuple):
556 # Expected value is a tuple of possible actual values.
557 if got_dict[key] not in expected_dict[key]:
558 logging.info("Expected '%s' values %s but got '%s'" %
559 (key, str(expected_dict[key]), got_dict[key]))
560 return False
561 else:
562 logging.info("The expected_dict is neither a str nor a dict.")
563 return False
564 return True
565
566
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800567 def vdat_flags_checker(self, mask, value):
568 """Check the flags from VbSharedData matched.
569
570 This function checks the masked flags from VbSharedData using crossystem
571 are matched the given value.
572
573 Args:
574 mask: A bitmask of flags to be matched.
575 value: An expected value.
576
577 Returns:
578 True if the flags matched; otherwise, False.
579 """
580 lines = self.faft_client.run_shell_command_get_output(
581 'crossystem vdat_flags')
582 vdat_flags = int(lines[0], 16)
583 if vdat_flags & mask != value:
584 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
585 (value, mask, vdat_flags))
586 return False
587 return True
588
589
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800590 def ro_normal_checker(self, expected_fw=None, twostop=False):
591 """Check the current boot uses RO boot.
592
593 Args:
594 expected_fw: A string of expected firmware, 'A', 'B', or
595 None if don't care.
596 twostop: True to expect a TwoStop boot; False to expect a RO boot.
597
598 Returns:
599 True if the currect boot firmware matched and used RO boot;
600 otherwise, False.
601 """
602 crossystem_dict = {'tried_fwb': '0'}
603 if expected_fw:
604 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800605 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800606 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
607
608 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800609 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
610 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800611 self.crossystem_checker(crossystem_dict))
612
613
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +0800614 def dev_boot_usb_checker(self, dev_boot_usb=True):
615 """Check the current boot is from a developer USB (Ctrl-U trigger).
616
617 Args:
618 dev_boot_usb: True to expect an USB boot;
619 False to expect an internal device boot.
620
621 Returns:
622 True if the currect boot device matched; otherwise, False.
623 """
624 return (self.crossystem_checker({'mainfw_type': 'developer'})
625 and self.faft_client.is_removable_device_boot() == dev_boot_usb)
626
627
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800628 def root_part_checker(self, expected_part):
629 """Check the partition number of the root device matched.
630
631 Args:
632 expected_part: A string containing the number of the expected root
633 partition.
634
635 Returns:
636 True if the currect root partition number matched; otherwise, False.
637 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800638 part = self.faft_client.get_root_part()[-1]
639 if self.ROOTFS_MAP[expected_part] != part:
640 logging.info("Expected root part %s but got %s" %
641 (self.ROOTFS_MAP[expected_part], part))
642 return False
643 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800644
645
Vic Yang59cac9c2012-05-21 15:28:42 +0800646 def ec_act_copy_checker(self, expected_copy):
647 """Check the EC running firmware copy matches.
648
649 Args:
650 expected_copy: A string containing 'RO', 'A', or 'B' indicating
651 the expected copy of EC running firmware.
652
653 Returns:
654 True if the current EC running copy matches; otherwise, False.
655 """
656 lines = self.faft_client.run_shell_command_get_output('ectool version')
657 pattern = re.compile("Firmware copy: (.*)")
658 for line in lines:
659 matched = pattern.match(line)
660 if matched and matched.group(1) == expected_copy:
661 return True
662 return False
663
664
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800665 def check_root_part_on_non_recovery(self, part):
666 """Check the partition number of root device and on normal/dev boot.
667
668 Returns:
669 True if the root device matched and on normal/dev boot;
670 otherwise, False.
671 """
672 return self.root_part_checker(part) and \
673 self.crossystem_checker({
674 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800675 })
676
677
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800678 def _join_part(self, dev, part):
679 """Return a concatenated string of device and partition number.
680
681 Args:
682 dev: A string of device, e.g.'/dev/sda'.
683 part: A string of partition number, e.g.'3'.
684
685 Returns:
686 A concatenated string of device and partition number, e.g.'/dev/sda3'.
687
688 >>> seq = FAFTSequence()
689 >>> seq._join_part('/dev/sda', '3')
690 '/dev/sda3'
691 >>> seq._join_part('/dev/mmcblk0', '2')
692 '/dev/mmcblk0p2'
693 """
694 if 'mmcblk' in dev:
695 return dev + 'p' + part
696 else:
697 return dev + part
698
699
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800700 def copy_kernel_and_rootfs(self, from_part, to_part):
701 """Copy kernel and rootfs from from_part to to_part.
702
703 Args:
704 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800705 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800706 """
707 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800708 logging.info('Copying kernel from %s to %s. Please wait...' %
709 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800710 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800711 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
712 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
713 logging.info('Copying rootfs from %s to %s. Please wait...' %
714 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800715 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800716 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
717 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800718
719
720 def ensure_kernel_boot(self, part):
721 """Ensure the request kernel boot.
722
723 If not, it duplicates the current kernel to the requested kernel
724 and sets the requested higher priority to ensure it boot.
725
726 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800727 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800728 """
729 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800730 if self.faft_client.diff_kernel_a_b():
731 self.copy_kernel_and_rootfs(
732 from_part=self.OTHER_KERNEL_MAP[part],
733 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800734 self.run_faft_step({
735 'userspace_action': (self.reset_and_prioritize_kernel, part),
736 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800737
738
Vic Yang416f2032012-08-28 10:18:03 +0800739 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800740 """Set hardware write protect pin.
741
742 Args:
743 enable: True if asserting write protect pin. Otherwise, False.
744 """
745 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
746 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800747 self.servo.set('fw_wp', 'on' if enabled else 'off')
748
749
750 def set_EC_write_protect_and_reboot(self, enabled):
751 """Set EC write protect status and reboot to take effect.
752
753 EC write protect is only activated if both hardware write protect pin
754 is asserted and software write protect flag is set. Also, a reboot is
755 required for write protect to take effect.
756
757 Since the software write protect flag cannot be unset if hardware write
758 protect pin is asserted, we need to deasserted the pin first if we are
759 deactivating write protect. Similarly, a reboot is required before we
760 can modify the software flag.
761
762 This method asserts/deasserts hardware write protect pin first, and
763 set corresponding EC software write protect flag.
764
765 Args:
766 enable: True if activating EC write protect. Otherwise, False.
767 """
768 self.set_hardware_write_protect(enabled)
769 if enabled:
770 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800771 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800772 self.sync_and_ec_reboot()
773 else:
774 # Reboot after deasserting hardware write protect pin to deactivate
775 # write protect. And then remove software write protect flag.
776 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800777 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800778
779
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800780 def send_ctrl_d_to_dut(self):
781 """Send Ctrl-D key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800782 if self._customized_key_commands['ctrl_d']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800783 logging.info('running the customized Ctrl-D key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800784 os.system(self._customized_key_commands['ctrl_d'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800785 else:
786 self.servo.ctrl_d()
787
788
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800789 def send_ctrl_u_to_dut(self):
790 """Send Ctrl-U key to DUT.
791
792 Raises:
793 error.TestError: if a non-Chrome EC device or no Ctrl-U command given
794 on a no-build-in-keyboard device.
795 """
796 if self._customized_key_commands['ctrl_u']:
797 logging.info('running the customized Ctrl-U key command')
798 os.system(self._customized_key_commands['ctrl_u'])
799 elif self.check_ec_capability(['keyboard'], suppress_warning=True):
800 self.ec.key_down('<ctrl_l>')
801 self.ec.key_down('u')
802 self.ec.key_up('u')
803 self.ec.key_up('<ctrl_l>')
804 elif self.client_attr.has_keyboard:
805 raise error.TestError(
806 "Can't send Ctrl-U to DUT without using Chrome EC.")
807 else:
808 raise error.TestError(
809 "Should specify the ctrl_u_cmd argument.")
810
811
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800812 def send_enter_to_dut(self):
813 """Send Enter key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800814 if self._customized_key_commands['enter']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800815 logging.info('running the customized Enter key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800816 os.system(self._customized_key_commands['enter'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800817 else:
818 self.servo.enter_key()
819
820
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800821 def send_space_to_dut(self):
822 """Send Space key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800823 if self._customized_key_commands['space']:
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800824 logging.info('running the customized Space key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800825 os.system(self._customized_key_commands['space'])
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800826 else:
827 # Send the alternative key combinaton of space key to servo.
828 self.servo.ctrl_refresh_key()
829
830
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800831 def wait_fw_screen_and_ctrl_d(self):
832 """Wait for firmware warning screen and press Ctrl-D."""
833 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800834 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800835
836
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800837 def wait_fw_screen_and_ctrl_u(self):
838 """Wait for firmware warning screen and press Ctrl-U."""
839 time.sleep(self.FIRMWARE_SCREEN_DELAY)
840 self.send_ctrl_u_to_dut()
841
842
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800843 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
844 """Wait for firmware warning screen and trigger recovery boot."""
845 time.sleep(self.FIRMWARE_SCREEN_DELAY)
846 self.send_enter_to_dut()
847
848 # For Alex/ZGB, there is a dev warning screen in text mode.
849 # Skip it by pressing Ctrl-D.
850 if need_dev_transition:
851 time.sleep(self.TEXT_SCREEN_DELAY)
852 self.send_ctrl_d_to_dut()
853
854
Mike Truty49153d82012-08-21 22:27:30 -0500855 def wait_fw_screen_and_unplug_usb(self):
856 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800857 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800858 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
859 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500860
861
862 def wait_fw_screen_and_plug_usb(self):
863 """Wait for firmware warning screen and then unplug and plug the USB."""
864 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800865 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
866
867
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800868 def wait_fw_screen_and_press_power(self):
869 """Wait for firmware warning screen and press power button."""
870 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800871 # While the firmware screen, the power button probing loop sleeps
872 # 0.25 second on every scan. Use the normal delay (1.2 second) for
873 # power press.
874 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800875
876
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800877 def wait_longer_fw_screen_and_press_power(self):
878 """Wait for firmware screen without timeout and press power button."""
879 time.sleep(self.DEV_SCREEN_TIMEOUT)
880 self.wait_fw_screen_and_press_power()
881
882
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800883 def wait_fw_screen_and_close_lid(self):
884 """Wait for firmware warning screen and close lid."""
885 time.sleep(self.FIRMWARE_SCREEN_DELAY)
886 self.servo.lid_close()
887
888
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800889 def wait_longer_fw_screen_and_close_lid(self):
890 """Wait for firmware screen without timeout and close lid."""
891 time.sleep(self.FIRMWARE_SCREEN_DELAY)
892 self.wait_fw_screen_and_close_lid()
893
894
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800895 def setup_tried_fwb(self, tried_fwb):
896 """Setup for fw B tried state.
897
898 It makes sure the system in the requested fw B tried state. If not, it
899 tries to do so.
900
901 Args:
902 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
903 """
904 if tried_fwb:
905 if not self.crossystem_checker({'tried_fwb': '1'}):
906 logging.info(
907 'Firmware is not booted with tried_fwb. Reboot into it.')
908 self.run_faft_step({
909 'userspace_action': self.faft_client.set_try_fw_b,
910 })
911 else:
912 if not self.crossystem_checker({'tried_fwb': '0'}):
913 logging.info(
914 'Firmware is booted with tried_fwb. Reboot to clear.')
915 self.run_faft_step({})
916
917
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800918 def enable_rec_mode_and_reboot(self):
919 """Switch to rec mode and reboot.
920
921 This method emulates the behavior of the old physical recovery switch,
922 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
923 recovery mode, i.e. just press Power + Esc + Refresh.
924 """
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800925 if self._customized_key_commands['rec_reboot']:
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800926 logging.info('running the customized rec reboot command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800927 os.system(self._customized_key_commands['rec_reboot'])
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800928 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800929 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800930 self.servo.set('cold_reset', 'on')
931 time.sleep(self.COLD_RESET_DELAY)
932 self.servo.set('cold_reset', 'off')
933 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800934 self.ec.send_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800935 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800936 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +0800937 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800938 else:
939 self.servo.enable_recovery_mode()
940 self.cold_reboot()
941 time.sleep(self.EC_REBOOT_DELAY)
942 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800943
944
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800945 def enable_dev_mode_and_reboot(self):
946 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800947 if self.client_attr.keyboard_dev:
948 self.enable_keyboard_dev_mode()
949 else:
950 self.servo.enable_development_mode()
951 self.faft_client.run_shell_command(
952 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800953
954
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800955 def enable_normal_mode_and_reboot(self):
956 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800957 if self.client_attr.keyboard_dev:
958 self.disable_keyboard_dev_mode()
959 else:
960 self.servo.disable_development_mode()
961 self.faft_client.run_shell_command(
962 'chromeos-firmwareupdate --mode tonormal && reboot')
963
964
965 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
966 """Wait for firmware screen and then switch into or out of dev mode.
967
968 Args:
969 dev: True if switching into dev mode. Otherwise, False.
970 """
971 time.sleep(self.FIRMWARE_SCREEN_DELAY)
972 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800973 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800974 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800975 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800976 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800977 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800978
979
980 def enable_keyboard_dev_mode(self):
981 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800982 # Plug out USB disk for preventing recovery boot without warning
983 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800984 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800985 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800986 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800987 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800988
989
990 def disable_keyboard_dev_mode(self):
991 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800992 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800993 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800994 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800995 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800996 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800997
998
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800999 def setup_dev_mode(self, dev_mode):
1000 """Setup for development mode.
1001
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001002 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001003 tries to do so.
1004
1005 Args:
1006 dev_mode: True if requested in dev mode; False if normal mode.
1007 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001008 # Change the default firmware_action for dev mode passing the fw screen.
1009 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001010 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1011 else None),
1012 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001013 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001014 if (not self.client_attr.keyboard_dev and
1015 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001016 logging.info('Dev switch is not on. Now switch it on.')
1017 self.servo.enable_development_mode()
1018 if not self.crossystem_checker({'devsw_boot': '1',
1019 'mainfw_type': 'developer'}):
1020 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001021 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001022 'userspace_action': None if self.client_attr.keyboard_dev
1023 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001024 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001025 'reboot_action': self.enable_keyboard_dev_mode if
1026 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001027 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001028 else:
Vic Yange7553162012-06-20 16:20:47 +08001029 if (not self.client_attr.keyboard_dev and
1030 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001031 logging.info('Dev switch is not off. Now switch it off.')
1032 self.servo.disable_development_mode()
1033 if not self.crossystem_checker({'devsw_boot': '0',
1034 'mainfw_type': 'normal'}):
1035 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001036 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001037 'userspace_action': None if self.client_attr.keyboard_dev
1038 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001039 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001040 'reboot_action': self.disable_keyboard_dev_mode if
1041 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001042 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001043
1044
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001045 def setup_kernel(self, part):
1046 """Setup for kernel test.
1047
1048 It makes sure both kernel A and B bootable and the current boot is
1049 the requested kernel part.
1050
1051 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001052 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001053 """
1054 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001055 if self.faft_client.diff_kernel_a_b():
1056 self.copy_kernel_and_rootfs(from_part=part,
1057 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001058 self.reset_and_prioritize_kernel(part)
1059
1060
1061 def reset_and_prioritize_kernel(self, part):
1062 """Make the requested partition highest priority.
1063
1064 This function also reset kerenl A and B to bootable.
1065
1066 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001067 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001068 """
1069 root_dev = self.faft_client.get_root_dev()
1070 # Reset kernel A and B to bootable.
1071 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1072 (self.KERNEL_MAP['a'], root_dev))
1073 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1074 (self.KERNEL_MAP['b'], root_dev))
1075 # Set kernel part highest priority.
1076 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1077 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001078 # Safer to sync and wait until the cgpt status written to the disk.
1079 self.faft_client.run_shell_command('sync')
1080 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001081
1082
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001083 def warm_reboot(self):
1084 """Request a warm reboot.
1085
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001086 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001087 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001088 # Use cold reset if the warm reset is broken.
1089 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001090 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1091 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001092 else:
1093 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001094
1095
1096 def cold_reboot(self):
1097 """Request a cold reboot.
1098
1099 A wrapper for underlying servo cold reset.
1100 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001101 if self.client_attr.platform == 'Parrot':
1102 self.servo.set('pwr_button', 'press')
1103 self.servo.set('cold_reset', 'on')
1104 self.servo.set('cold_reset', 'off')
1105 time.sleep(self.POWER_BTN_DELAY)
1106 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001107 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001108 # We don't use servo.cold_reset() here because software sync is
1109 # not yet finished, and device may or may not come up after cold
1110 # reset. Pressing power button before firmware comes up solves this.
1111 #
1112 # The correct behavior should be (not work now):
1113 # - If rebooting EC with rec mode on, power on AP and it boots
1114 # into recovery mode.
1115 # - If rebooting EC with rec mode off, power on AP for software
1116 # sync. Then AP checks if lid open or not. If lid open, continue;
1117 # otherwise, shut AP down and need servo for a power button
1118 # press.
1119 self.servo.set('cold_reset', 'on')
1120 self.servo.set('cold_reset', 'off')
1121 time.sleep(self.POWER_BTN_DELAY)
1122 self.servo.power_short_press()
1123 else:
1124 self.servo.cold_reset()
1125
1126
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001127 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001128 """Request the client sync and do a warm reboot.
1129
1130 This is the default reboot action on FAFT.
1131 """
1132 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001133 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001134 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001135
1136
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001137 def sync_and_cold_reboot(self):
1138 """Request the client sync and do a cold reboot.
1139
1140 This reboot action is used to reset EC for recovery mode.
1141 """
1142 self.faft_client.run_shell_command('sync')
1143 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001144 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001145
1146
Vic Yangaeb10392012-08-28 09:25:09 +08001147 def sync_and_ec_reboot(self, args=''):
1148 """Request the client sync and do a EC triggered reboot.
1149
1150 Args:
1151 args: Arguments passed to "ectool reboot_ec". Including:
1152 RO: jump to EC RO firmware.
1153 RW: jump to EC RW firmware.
1154 cold: Cold/hard reboot.
1155 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001156 self.faft_client.run_shell_command('sync')
1157 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001158 # Since EC reboot happens immediately, delay before actual reboot to
1159 # allow FAFT client returning.
1160 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1161 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001162 time.sleep(self.EC_REBOOT_DELAY)
1163 self.check_lid_and_power_on()
1164
1165
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001166 def full_power_off_and_on(self):
1167 """Shutdown the device by pressing power button and power on again."""
1168 # Press power button to trigger Chrome OS normal shutdown process.
1169 self.servo.power_normal_press()
1170 time.sleep(self.FULL_POWER_OFF_DELAY)
1171 # Short press power button to boot DUT again.
1172 self.servo.power_short_press()
1173
1174
Vic Yangf86728a2012-07-30 10:44:07 +08001175 def check_lid_and_power_on(self):
1176 """
1177 On devices with EC software sync, system powers on after EC reboots if
1178 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1179 This method checks lid switch state and presses power button if
1180 necessary.
1181 """
1182 if self.servo.get("lid_open") == "no":
1183 time.sleep(self.SOFTWARE_SYNC_DELAY)
1184 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001185
1186
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001187 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1188 """Modify the kernel header magic in USB stick.
1189
1190 The kernel header magic is the first 8-byte of kernel partition.
1191 We modify it to make it fail on kernel verification check.
1192
1193 Args:
1194 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1195 from_magic: A string of magic which we change it from.
1196 to_magic: A string of magic which we change it to.
1197
1198 Raises:
1199 error.TestError: if failed to change magic.
1200 """
1201 assert len(from_magic) == 8
1202 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001203 # USB image only contains one kernel.
1204 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001205 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1206 current_magic = utils.system_output(read_cmd)
1207 if current_magic == to_magic:
1208 logging.info("The kernel magic is already %s." % current_magic)
1209 return
1210 if current_magic != from_magic:
1211 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1212
1213 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1214 (from_magic, to_magic))
1215 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1216 " 2>/dev/null" % (to_magic, kernel_part))
1217 utils.system(write_cmd)
1218
1219 if utils.system_output(read_cmd) != to_magic:
1220 raise error.TestError("Failed to write new magic.")
1221
1222
1223 def corrupt_usb_kernel(self, usb_dev):
1224 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1225
1226 Args:
1227 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1228 """
1229 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1230 self.CORRUPTED_MAGIC)
1231
1232
1233 def restore_usb_kernel(self, usb_dev):
1234 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1235
1236 Args:
1237 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1238 """
1239 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1240 self.CHROMEOS_MAGIC)
1241
1242
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001243 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001244 """Call the action function with/without arguments.
1245
1246 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001247 action_tuple: A function, or a tuple (function, args, error_msg),
1248 in which, args and error_msg are optional. args is
1249 either a value or a tuple if multiple arguments.
1250 check_status: Check the return value of action function. If not
1251 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001252
1253 Returns:
1254 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001255
1256 Raises:
1257 error.TestError: An error when the action function is not callable.
1258 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001259 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001260 action = action_tuple
1261 args = ()
1262 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001263 if isinstance(action_tuple, tuple):
1264 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001265 if len(action_tuple) >= 2:
1266 args = action_tuple[1]
1267 if not isinstance(args, tuple):
1268 args = (args,)
1269 if len(action_tuple) >= 3:
Tom Wai-Hong Tamff560882012-10-15 16:50:06 +08001270 error_msg = action_tuple[2]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001271
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001272 if action is None:
1273 return
1274
1275 if not callable(action):
1276 raise error.TestError('action is not callable!')
1277
1278 info_msg = 'calling %s' % str(action)
1279 if args:
1280 info_msg += ' with args %s' % str(args)
1281 logging.info(info_msg)
1282 ret = action(*args)
1283
1284 if check_status and not ret:
1285 raise error.TestFail('%s: %s returning %s' %
1286 (error_msg, info_msg, str(ret)))
1287 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001288
1289
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001290 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1291 post_power_action=None):
1292 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1293
1294 Args:
1295 shutdown_action: a function which makes DUT shutdown, like pressing
1296 power key.
1297 pre_power_action: a function which is called before next power on.
1298 post_power_action: a function which is called after next power on.
1299
1300 Raises:
1301 error.TestFail: if the shutdown_action() failed to turn DUT off.
1302 """
1303 self._call_action(shutdown_action)
1304 logging.info('Wait to ensure DUT shut down...')
1305 try:
1306 self.wait_for_client()
1307 raise error.TestFail(
1308 'Should shut the device down after calling %s.' %
1309 str(shutdown_action))
1310 except AssertionError:
1311 logging.info(
1312 'DUT is surely shutdown. We are going to power it on again...')
1313
1314 if pre_power_action:
1315 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001316 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001317 if post_power_action:
1318 self._call_action(post_power_action)
1319
1320
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001321 def register_faft_template(self, template):
1322 """Register FAFT template, the default FAFT_STEP of each step.
1323
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001324 Any missing field falls back to the original faft_template.
1325
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001326 Args:
1327 template: A FAFT_STEP dict.
1328 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001329 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001330
1331
1332 def register_faft_sequence(self, sequence):
1333 """Register FAFT sequence.
1334
1335 Args:
1336 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1337 """
1338 self._faft_sequence = sequence
1339
1340
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001341 def run_faft_step(self, step, no_reboot=False):
1342 """Run a single FAFT step.
1343
1344 Any missing field falls back to faft_template. An empty step means
1345 running the default faft_template.
1346
1347 Args:
1348 step: A FAFT_STEP dict.
1349 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001350
1351 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001352 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001353 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001354 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1355 'firmware_action', 'install_deps_after_boot')
1356
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001357 test = {}
1358 test.update(self._faft_template)
1359 test.update(step)
1360
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001361 for key in test:
1362 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001363 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001364
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001365 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001366 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001367
1368 self._call_action(test['userspace_action'])
1369
1370 # Don't run reboot_action and firmware_action if no_reboot is True.
1371 if not no_reboot:
1372 self._call_action(test['reboot_action'])
1373 self.wait_for_client_offline()
1374 self._call_action(test['firmware_action'])
1375
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001376 try:
1377 if 'install_deps_after_boot' in test:
1378 self.wait_for_client(
1379 install_deps=test['install_deps_after_boot'])
1380 else:
1381 self.wait_for_client()
1382 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001383 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001384 self.reset_client()
1385 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001386
1387
1388 def run_faft_sequence(self):
1389 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001390 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001391 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001392 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001393 logging.info('======== Running FAFT sequence step %d ========' %
1394 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001395 # Don't reboot in the last step.
1396 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001397 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001398
1399
ctchang38ae4922012-09-03 17:01:16 +08001400 def get_current_firmware_sha(self):
1401 """Get current firmware sha of body and vblock.
1402
1403 Returns:
1404 Current firmware sha follows the order (
1405 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1406 """
1407 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1408 self.faft_client.get_firmware_sha('a'),
1409 self.faft_client.get_firmware_sig_sha('b'),
1410 self.faft_client.get_firmware_sha('b'))
1411 return current_firmware_sha
1412
1413
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001414 def is_firmware_changed(self):
1415 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001416
1417 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001418 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001419 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001420 # Device may not be rebooted after test.
1421 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001422
1423 current_sha = self.get_current_firmware_sha()
1424
1425 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001426 return False
ctchang38ae4922012-09-03 17:01:16 +08001427 else:
ctchang38ae4922012-09-03 17:01:16 +08001428 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1429 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1430 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1431 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001432 logging.info("Firmware changed:")
1433 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1434 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1435 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1436 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1437 return True
ctchang38ae4922012-09-03 17:01:16 +08001438
1439
1440 def backup_firmware(self, suffix='.original'):
1441 """Backup firmware to file, and then send it to host.
1442
1443 Args:
1444 suffix: a string appended to backup file name
1445 """
1446 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001447 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1448 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1449 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001450
1451 self._backup_firmware_sha = self.get_current_firmware_sha()
1452 logging.info('Backup firmware stored in %s with suffix %s' % (
1453 self.resultsdir, suffix))
1454
1455
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001456 def is_firmware_saved(self):
1457 """Check if a firmware saved (called backup_firmware before).
1458
1459 Returns:
1460 True if the firmware is backuped; otherwise False.
1461 """
1462 return self._backup_firmware_sha != ()
1463
1464
ctchang38ae4922012-09-03 17:01:16 +08001465 def restore_firmware(self, suffix='.original'):
1466 """Restore firmware from host in resultsdir.
1467
1468 Args:
1469 suffix: a string appended to backup file name
1470 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001471 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001472 return
1473
1474 # Backup current corrupted firmware.
1475 self.backup_firmware(suffix='.corrupt')
1476
1477 # Restore firmware.
1478 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001479 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1480 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001481
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001482 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001483 self.sync_and_warm_reboot()
1484 self.wait_for_client_offline()
1485 self.wait_for_client()
1486
ctchang38ae4922012-09-03 17:01:16 +08001487 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001488
1489
1490 def setup_firmwareupdate_shellball(self, shellball=None):
1491 """Deside a shellball to use in firmware update test.
1492
1493 Check if there is a given shellball, and it is a shell script. Then,
1494 send it to the remote host. Otherwise, use
1495 /usr/sbin/chromeos-firmwareupdate.
1496
1497 Args:
1498 shellball: path of a shellball or default to None.
1499
1500 Returns:
1501 Path of shellball in remote host.
1502 If use default shellball, reutrn None.
1503 """
1504 updater_path = None
1505 if shellball:
1506 # Determine the firmware file is a shellball or a raw binary.
1507 is_shellball = (utils.system_output("file %s" % shellball).find(
1508 "shell script") != -1)
1509 if is_shellball:
1510 logging.info('Device will update firmware with shellball %s'
1511 % shellball)
1512 temp_dir = self.faft_client.create_temp_dir('shellball_')
1513 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1514 self._client.send_file(shellball, temp_shellball)
1515 updater_path = temp_shellball
1516 else:
1517 raise error.TestFail(
1518 'The given shellball is not a shell script.')
1519 return updater_path