blob: 57637e11a2627e44d0be989bdc3279419e2625d6 [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 Tamc1163f32012-10-04 15:25:10 +08005import ast
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +08006import ctypes
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08007import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08008import os
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08009import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080010import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080011import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012import time
13import xmlrpclib
14
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080015from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080016from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +080017from autotest_lib.server.cros import vboot_constants as vboot
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 Tam40fd9472012-01-09 17:11:02 +080072 _customized_ctrl_d_key_command: The customized Ctrl-D key command
73 instead of sending key via servo board.
74 _customized_enter_key_command: The customized Enter key command instead
75 of sending key via servo board.
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +080076 _customized_space_key_command: The customized Space key command instead
77 of sending key via servo board.
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +080078 _customized_rec_reboot_command: The customized recovery reboot command
79 instead of sending key combination of Power + Esc + F3 for
80 triggering recovery reboot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080081 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080082 _firmware_update: Boolean. True if firmware update needed after
83 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080084 """
85 version = 1
86
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080087
88 # Mapping of partition number of kernel and rootfs.
89 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
90 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
91 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
92 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
93
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080094 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080095 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080096 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080097 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080098 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080099 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800100 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +0800101 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800102 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800103 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +0800104 # Delay for waiting client to return before EC reboot
105 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800106 # Delay for waiting client to full power off
107 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800108 # Delay between EC reboot and pressing power button
109 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800110 # Delay of EC software sync hash calculating time
111 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800112 # Delay between EC boot and ChromeEC console functional
113 EC_BOOT_DELAY = 0.5
114 # Duration of holding cold_reset to reset device
115 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800116
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800117 # The developer screen timeouts fit our spec.
118 DEV_SCREEN_TIMEOUT = 30
119
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800120 CHROMEOS_MAGIC = "CHROMEOS"
121 CORRUPTED_MAGIC = "CORRUPTD"
122
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800123 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800124 _faft_sequence = ()
125
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800126 _customized_ctrl_d_key_command = None
127 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800128 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800129 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800130 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800131 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800132
ctchang38ae4922012-09-03 17:01:16 +0800133 _backup_firmware_sha = ()
134
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800135
136 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
137 # Parse arguments from command line
138 args = {}
139 for arg in cmdline_args:
140 match = re.search("^(\w+)=(.+)", arg)
141 if match:
142 args[match.group(1)] = match.group(2)
143
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800144 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800145 if 'ctrl_d_cmd' in args:
146 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
147 logging.info('Customized Ctrl-D key command: %s' %
148 self._customized_ctrl_d_key_command)
149 if 'enter_cmd' in args:
150 self._customized_enter_key_command = args['enter_cmd']
151 logging.info('Customized Enter key command: %s' %
152 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800153 if 'space_cmd' in args:
154 self._customized_space_key_command = args['space_cmd']
155 logging.info('Customized Space key command: %s' %
156 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800157 if 'rec_reboot_cmd' in args:
158 self._customized_rec_reboot_command = args['rec_reboot_cmd']
159 logging.info('Customized recovery reboot command: %s' %
160 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800161 if 'image' in args:
162 self._install_image_path = args['image']
163 logging.info('Install Chrome OS test image path: %s' %
164 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800165 if 'firmware_update' in args and args['firmware_update'].lower() \
166 not in ('0', 'false', 'no'):
167 if self._install_image_path:
168 self._firmware_update = True
169 logging.info('Also update firmware after installing.')
170 else:
171 logging.warning('Firmware update will not not performed '
172 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800173
174 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
175 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800176 if use_faft:
177 self.client_attr = FAFTClientAttribute(
178 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800179
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 Tam6ec46e32012-10-05 16:39:21 +0800195 self.clear_set_gbb_flags(vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
196 vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
197 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800198 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800199 self.install_test_image(self._install_image_path,
200 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800201
202
203 def cleanup(self):
204 """Autotest cleanup function."""
205 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800206 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800207 super(FAFTSequence, self).cleanup()
208
209
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800210 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800211 """Reset client, if necessary.
212
213 This method is called when the client is not responsive. It may be
214 caused by the following cases:
215 - network flaky (can be recovered by replugging the Ethernet);
216 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
217 - corrupted firmware;
218 - corrutped OS image.
219 """
220 # DUT works fine, done.
221 if self._ping_test(self._client.ip, timeout=5):
222 return
223
224 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
225 # first reset item.
226
227 # DUT may halt on a firmware screen. Try cold reboot.
228 logging.info('Try cold reboot...')
229 self.cold_reboot()
230 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800231 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800232 return
233 except AssertionError:
234 pass
235
236 # DUT may be broken by a corrupted firmware. Restore firmware.
237 # We assume the recovery boot still works fine. Since the recovery
238 # code is in RO region and all FAFT tests don't change the RO region
239 # except GBB.
240 if self.is_firmware_saved():
241 self.ensure_client_in_recovery()
242 logging.info('Try restore the original firmware...')
243 if self.is_firmware_changed():
244 try:
245 self.restore_firmware()
246 return
247 except AssertionError:
248 logging.info('Restoring firmware doesn\'t help.')
249
250 # DUT may be broken by a corrupted OS image. Restore OS image.
251 self.ensure_client_in_recovery()
252 logging.info('Try restore the OS image...')
253 self.faft_client.run_shell_command('chromeos-install --yes')
254 self.sync_and_warm_reboot()
255 self.wait_for_client_offline()
256 try:
257 self.wait_for_client(install_deps=True)
258 logging.info('Successfully restore OS image.')
259 return
260 except AssertionError:
261 logging.info('Restoring OS image doesn\'t help.')
262
263
264 def ensure_client_in_recovery(self):
265 """Ensure client in recovery boot; reboot into it if necessary.
266
267 Raises:
268 error.TestError: if failed to boot the USB image.
269 """
270 # DUT works fine and is already in recovery boot, done.
271 if self._ping_test(self._client.ip, timeout=5):
272 if self.crossystem_checker({'mainfw_type': 'recovery'}):
273 return
274
275 logging.info('Try boot into USB image...')
276 self.servo.enable_usb_hub(host=True)
277 self.enable_rec_mode_and_reboot()
278 self.wait_fw_screen_and_plug_usb()
279 try:
280 self.wait_for_client(install_deps=True)
281 except AssertionError:
282 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800283
284
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800285 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800286 """Assert an USB disk plugged-in on servo and a test image inside.
287
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800288 Args:
289 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
290 If None, it is detected automatically.
291
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800292 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800293 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800294 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800295 if usb_dev:
296 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
297 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700298 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800299 usb_dev = self.servo.probe_host_usb_dev()
300 if not usb_dev:
301 raise error.TestError(
302 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800303
304 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800305 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800306 code = utils.system(
307 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
308 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800309 utils.system('sudo umount %s' % tmp_dir)
310 os.removedirs(tmp_dir)
311 if code != 0:
312 raise error.TestError(
313 'The image in the USB disk should be a test image.')
314
315
Simran Basi741b5d42012-05-18 11:27:15 -0700316 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800317 """Install the test image specied by the path onto the USB and DUT disk.
318
319 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500320 recovery mode. Then runs 'chromeos-install' (and possible
321 chromeos-firmwareupdate') to install it to DUT disk.
322
323 Sample command line:
324
325 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
326 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
327 server/site_tests/firmware_XXXX/control
328
329 This test requires an automated recovery to occur while simulating
330 inserting and removing the usb key from the servo. To allow this the
331 following hardware setup is required:
332 1. servo2 board connected via servoflex.
333 2. USB key inserted in the servo2.
334 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
335 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800336
337 Args:
338 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800339 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800340 """
341 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
342 image_path)
343 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800344
Mike Truty49153d82012-08-21 22:27:30 -0500345 # Reuse the servo method that uses the servo USB key to install
346 # the test image.
347 self.servo.image_to_servo_usb(image_path)
348
349 # DUT is powered off while imaging servo USB.
350 # Now turn it on.
351 self.servo.power_short_press()
352 self.wait_for_client()
353 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
354
355 install_cmd = 'chromeos-install --yes'
356 if firmware_update:
357 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
358
359 self.register_faft_sequence((
360 { # Step 1, request recovery boot
361 'state_checker': (self.crossystem_checker, {
362 'mainfw_type': ('developer', 'normal'),
363 }),
364 'userspace_action': self.faft_client.request_recovery_boot,
365 'firmware_action': self.wait_fw_screen_and_plug_usb,
366 'install_deps_after_boot': True,
367 },
368 { # Step 2, expected recovery boot
369 'state_checker': (self.crossystem_checker, {
370 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800371 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500372 }),
373 'userspace_action': (self.faft_client.run_shell_command,
374 install_cmd),
375 'reboot_action': self.cold_reboot,
376 'install_deps_after_boot': True,
377 },
378 { # Step 3, expected normal or developer boot (not recovery)
379 'state_checker': (self.crossystem_checker, {
380 'mainfw_type': ('developer', 'normal')
381 }),
382 },
383 ))
384 self.run_faft_sequence()
385 # 'Unplug' any USB keys in the servo from the dut.
386 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800387
388
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800389 def clear_set_gbb_flags(self, clear_mask, set_mask):
390 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800391
392 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800393 clear_mask: A mask of flags to be cleared.
394 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800395 """
396 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800397 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
398
399 if (gbb_flags != new_flags):
400 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
401 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800402 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800403 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800404 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800405 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800406 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800407 self.run_faft_step({
408 'firmware_action': self.wait_fw_screen_and_ctrl_d,
409 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800410
411
Vic Yangb4e3e742012-06-02 13:17:38 +0800412 def send_uart_command(self, command):
413 """Send command through UART.
414
415 This function open UART pty when called, and then command is sent
416 through UART.
417
418 Args:
419 command: The command string to send.
Vic Yangb4e3e742012-06-02 13:17:38 +0800420 """
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800421 self.servo.set('ec_uart_regexp', 'None')
422 self.servo.set_nocheck('ec_uart_cmd', command)
Vic Yangb4e3e742012-06-02 13:17:38 +0800423
424
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800425 def send_uart_command_get_output(self, command, regexp_list, timeout=1):
Vic Yangb4e3e742012-06-02 13:17:38 +0800426 """Send command through UART and wait for response.
427
428 This function waits for response message matching regular expressions.
429
430 Args:
431 command: The command sent.
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800432 regexp_list: List of regular expressions used to match response
433 message. Note, list must be ordered.
Vic Yangb4e3e742012-06-02 13:17:38 +0800434
435 Returns:
Tom Wai-Hong Tam41859a62012-10-03 09:20:20 +0800436 List of tuples, each of which contains the entire matched string and
437 all the subgroups of the match. None if not matched.
438 For example:
439 response of the given command:
440 High temp: 37.2
441 Low temp: 36.4
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800442 regexp_list:
Tom Wai-Hong Tam41859a62012-10-03 09:20:20 +0800443 ['High temp: (\d+)\.(\d+)', 'Low temp: (\d+)\.(\d+)']
444 returns:
445 [('High temp: 37.2', '37', '2'), ('Low temp: 36.4', '36', '4')]
Vic Yangb4e3e742012-06-02 13:17:38 +0800446
447 Raises:
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800448 error.TestError: An error when the given regexp_list is not valid.
Vic Yangb4e3e742012-06-02 13:17:38 +0800449 """
Tom Wai-Hong Tamc1163f32012-10-04 15:25:10 +0800450 if not isinstance(regexp_list, list):
451 raise error.TestError('Arugment regexp_list is not a list: %s' %
452 str(regexp_list))
453
454 self.servo.set('ec_uart_timeout', str(float(timeout)))
455 self.servo.set('ec_uart_regexp', str(regexp_list))
456 self.servo.set_nocheck('ec_uart_cmd', command)
457 return ast.literal_eval(self.servo.get('ec_uart_cmd'))
Vic Yangb4e3e742012-06-02 13:17:38 +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 Tamcfda61f2011-11-02 17:41:01 +0800614 def root_part_checker(self, expected_part):
615 """Check the partition number of the root device matched.
616
617 Args:
618 expected_part: A string containing the number of the expected root
619 partition.
620
621 Returns:
622 True if the currect root partition number matched; otherwise, False.
623 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800624 part = self.faft_client.get_root_part()[-1]
625 if self.ROOTFS_MAP[expected_part] != part:
626 logging.info("Expected root part %s but got %s" %
627 (self.ROOTFS_MAP[expected_part], part))
628 return False
629 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800630
631
Vic Yang59cac9c2012-05-21 15:28:42 +0800632 def ec_act_copy_checker(self, expected_copy):
633 """Check the EC running firmware copy matches.
634
635 Args:
636 expected_copy: A string containing 'RO', 'A', or 'B' indicating
637 the expected copy of EC running firmware.
638
639 Returns:
640 True if the current EC running copy matches; otherwise, False.
641 """
642 lines = self.faft_client.run_shell_command_get_output('ectool version')
643 pattern = re.compile("Firmware copy: (.*)")
644 for line in lines:
645 matched = pattern.match(line)
646 if matched and matched.group(1) == expected_copy:
647 return True
648 return False
649
650
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800651 def check_root_part_on_non_recovery(self, part):
652 """Check the partition number of root device and on normal/dev boot.
653
654 Returns:
655 True if the root device matched and on normal/dev boot;
656 otherwise, False.
657 """
658 return self.root_part_checker(part) and \
659 self.crossystem_checker({
660 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800661 })
662
663
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800664 def _join_part(self, dev, part):
665 """Return a concatenated string of device and partition number.
666
667 Args:
668 dev: A string of device, e.g.'/dev/sda'.
669 part: A string of partition number, e.g.'3'.
670
671 Returns:
672 A concatenated string of device and partition number, e.g.'/dev/sda3'.
673
674 >>> seq = FAFTSequence()
675 >>> seq._join_part('/dev/sda', '3')
676 '/dev/sda3'
677 >>> seq._join_part('/dev/mmcblk0', '2')
678 '/dev/mmcblk0p2'
679 """
680 if 'mmcblk' in dev:
681 return dev + 'p' + part
682 else:
683 return dev + part
684
685
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800686 def copy_kernel_and_rootfs(self, from_part, to_part):
687 """Copy kernel and rootfs from from_part to to_part.
688
689 Args:
690 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800691 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800692 """
693 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800694 logging.info('Copying kernel from %s to %s. Please wait...' %
695 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800696 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800697 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
698 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
699 logging.info('Copying rootfs from %s to %s. Please wait...' %
700 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800701 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800702 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
703 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800704
705
706 def ensure_kernel_boot(self, part):
707 """Ensure the request kernel boot.
708
709 If not, it duplicates the current kernel to the requested kernel
710 and sets the requested higher priority to ensure it boot.
711
712 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800713 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800714 """
715 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800716 if self.faft_client.diff_kernel_a_b():
717 self.copy_kernel_and_rootfs(
718 from_part=self.OTHER_KERNEL_MAP[part],
719 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800720 self.run_faft_step({
721 'userspace_action': (self.reset_and_prioritize_kernel, part),
722 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800723
724
Vic Yang416f2032012-08-28 10:18:03 +0800725 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800726 """Set hardware write protect pin.
727
728 Args:
729 enable: True if asserting write protect pin. Otherwise, False.
730 """
731 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
732 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800733 self.servo.set('fw_wp', 'on' if enabled else 'off')
734
735
736 def set_EC_write_protect_and_reboot(self, enabled):
737 """Set EC write protect status and reboot to take effect.
738
739 EC write protect is only activated if both hardware write protect pin
740 is asserted and software write protect flag is set. Also, a reboot is
741 required for write protect to take effect.
742
743 Since the software write protect flag cannot be unset if hardware write
744 protect pin is asserted, we need to deasserted the pin first if we are
745 deactivating write protect. Similarly, a reboot is required before we
746 can modify the software flag.
747
748 This method asserts/deasserts hardware write protect pin first, and
749 set corresponding EC software write protect flag.
750
751 Args:
752 enable: True if activating EC write protect. Otherwise, False.
753 """
754 self.set_hardware_write_protect(enabled)
755 if enabled:
756 # Set write protect flag and reboot to take effect.
757 self.send_uart_command("flashwp enable")
758 self.sync_and_ec_reboot()
759 else:
760 # Reboot after deasserting hardware write protect pin to deactivate
761 # write protect. And then remove software write protect flag.
762 self.sync_and_ec_reboot()
763 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800764
765
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800766 def send_ctrl_d_to_dut(self):
767 """Send Ctrl-D key to DUT."""
768 if self._customized_ctrl_d_key_command:
769 logging.info('running the customized Ctrl-D key command')
770 os.system(self._customized_ctrl_d_key_command)
771 else:
772 self.servo.ctrl_d()
773
774
775 def send_enter_to_dut(self):
776 """Send Enter key to DUT."""
777 if self._customized_enter_key_command:
778 logging.info('running the customized Enter key command')
779 os.system(self._customized_enter_key_command)
780 else:
781 self.servo.enter_key()
782
783
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800784 def send_space_to_dut(self):
785 """Send Space key to DUT."""
786 if self._customized_space_key_command:
787 logging.info('running the customized Space key command')
788 os.system(self._customized_space_key_command)
789 else:
790 # Send the alternative key combinaton of space key to servo.
791 self.servo.ctrl_refresh_key()
792
793
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800794 def wait_fw_screen_and_ctrl_d(self):
795 """Wait for firmware warning screen and press Ctrl-D."""
796 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800797 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800798
799
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800800 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
801 """Wait for firmware warning screen and trigger recovery boot."""
802 time.sleep(self.FIRMWARE_SCREEN_DELAY)
803 self.send_enter_to_dut()
804
805 # For Alex/ZGB, there is a dev warning screen in text mode.
806 # Skip it by pressing Ctrl-D.
807 if need_dev_transition:
808 time.sleep(self.TEXT_SCREEN_DELAY)
809 self.send_ctrl_d_to_dut()
810
811
Mike Truty49153d82012-08-21 22:27:30 -0500812 def wait_fw_screen_and_unplug_usb(self):
813 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800814 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800815 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
816 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500817
818
819 def wait_fw_screen_and_plug_usb(self):
820 """Wait for firmware warning screen and then unplug and plug the USB."""
821 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800822 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
823
824
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800825 def wait_fw_screen_and_press_power(self):
826 """Wait for firmware warning screen and press power button."""
827 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800828 # While the firmware screen, the power button probing loop sleeps
829 # 0.25 second on every scan. Use the normal delay (1.2 second) for
830 # power press.
831 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800832
833
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800834 def wait_longer_fw_screen_and_press_power(self):
835 """Wait for firmware screen without timeout and press power button."""
836 time.sleep(self.DEV_SCREEN_TIMEOUT)
837 self.wait_fw_screen_and_press_power()
838
839
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800840 def wait_fw_screen_and_close_lid(self):
841 """Wait for firmware warning screen and close lid."""
842 time.sleep(self.FIRMWARE_SCREEN_DELAY)
843 self.servo.lid_close()
844
845
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800846 def wait_longer_fw_screen_and_close_lid(self):
847 """Wait for firmware screen without timeout and close lid."""
848 time.sleep(self.FIRMWARE_SCREEN_DELAY)
849 self.wait_fw_screen_and_close_lid()
850
851
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800852 def setup_tried_fwb(self, tried_fwb):
853 """Setup for fw B tried state.
854
855 It makes sure the system in the requested fw B tried state. If not, it
856 tries to do so.
857
858 Args:
859 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
860 """
861 if tried_fwb:
862 if not self.crossystem_checker({'tried_fwb': '1'}):
863 logging.info(
864 'Firmware is not booted with tried_fwb. Reboot into it.')
865 self.run_faft_step({
866 'userspace_action': self.faft_client.set_try_fw_b,
867 })
868 else:
869 if not self.crossystem_checker({'tried_fwb': '0'}):
870 logging.info(
871 'Firmware is booted with tried_fwb. Reboot to clear.')
872 self.run_faft_step({})
873
874
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800875 def enable_rec_mode_and_reboot(self):
876 """Switch to rec mode and reboot.
877
878 This method emulates the behavior of the old physical recovery switch,
879 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
880 recovery mode, i.e. just press Power + Esc + Refresh.
881 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800882 if self._customized_rec_reboot_command:
883 logging.info('running the customized rec reboot command')
884 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800885 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800886 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800887 self.servo.set('cold_reset', 'on')
888 time.sleep(self.COLD_RESET_DELAY)
889 self.servo.set('cold_reset', 'off')
890 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +0800891 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800892 time.sleep(self.EC_BOOT_DELAY)
893 self.send_uart_command("hostevent set 0x4000")
894 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800895 else:
896 self.servo.enable_recovery_mode()
897 self.cold_reboot()
898 time.sleep(self.EC_REBOOT_DELAY)
899 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800900
901
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800902 def enable_dev_mode_and_reboot(self):
903 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800904 if self.client_attr.keyboard_dev:
905 self.enable_keyboard_dev_mode()
906 else:
907 self.servo.enable_development_mode()
908 self.faft_client.run_shell_command(
909 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800910
911
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800912 def enable_normal_mode_and_reboot(self):
913 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800914 if self.client_attr.keyboard_dev:
915 self.disable_keyboard_dev_mode()
916 else:
917 self.servo.disable_development_mode()
918 self.faft_client.run_shell_command(
919 'chromeos-firmwareupdate --mode tonormal && reboot')
920
921
922 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
923 """Wait for firmware screen and then switch into or out of dev mode.
924
925 Args:
926 dev: True if switching into dev mode. Otherwise, False.
927 """
928 time.sleep(self.FIRMWARE_SCREEN_DELAY)
929 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800930 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800931 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800932 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800933 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800934 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800935
936
937 def enable_keyboard_dev_mode(self):
938 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800939 # Plug out USB disk for preventing recovery boot without warning
940 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800941 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800942 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800943 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800944 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800945
946
947 def disable_keyboard_dev_mode(self):
948 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800949 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800950 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800951 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800952 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800953 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800954
955
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800956 def setup_dev_mode(self, dev_mode):
957 """Setup for development mode.
958
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800959 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800960 tries to do so.
961
962 Args:
963 dev_mode: True if requested in dev mode; False if normal mode.
964 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800965 # Change the default firmware_action for dev mode passing the fw screen.
966 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800967 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
968 else None),
969 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800970 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800971 if (not self.client_attr.keyboard_dev and
972 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800973 logging.info('Dev switch is not on. Now switch it on.')
974 self.servo.enable_development_mode()
975 if not self.crossystem_checker({'devsw_boot': '1',
976 'mainfw_type': 'developer'}):
977 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800978 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800979 'userspace_action': None if self.client_attr.keyboard_dev
980 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800981 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800982 'reboot_action': self.enable_keyboard_dev_mode if
983 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800984 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800985 else:
Vic Yange7553162012-06-20 16:20:47 +0800986 if (not self.client_attr.keyboard_dev and
987 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800988 logging.info('Dev switch is not off. Now switch it off.')
989 self.servo.disable_development_mode()
990 if not self.crossystem_checker({'devsw_boot': '0',
991 'mainfw_type': 'normal'}):
992 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800993 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800994 'userspace_action': None if self.client_attr.keyboard_dev
995 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800996 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800997 'reboot_action': self.disable_keyboard_dev_mode if
998 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800999 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001000
1001
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001002 def setup_kernel(self, part):
1003 """Setup for kernel test.
1004
1005 It makes sure both kernel A and B bootable and the current boot is
1006 the requested kernel part.
1007
1008 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001009 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001010 """
1011 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001012 if self.faft_client.diff_kernel_a_b():
1013 self.copy_kernel_and_rootfs(from_part=part,
1014 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001015 self.reset_and_prioritize_kernel(part)
1016
1017
1018 def reset_and_prioritize_kernel(self, part):
1019 """Make the requested partition highest priority.
1020
1021 This function also reset kerenl A and B to bootable.
1022
1023 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001024 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001025 """
1026 root_dev = self.faft_client.get_root_dev()
1027 # Reset kernel A and B to bootable.
1028 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1029 (self.KERNEL_MAP['a'], root_dev))
1030 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1031 (self.KERNEL_MAP['b'], root_dev))
1032 # Set kernel part highest priority.
1033 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1034 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001035 # Safer to sync and wait until the cgpt status written to the disk.
1036 self.faft_client.run_shell_command('sync')
1037 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001038
1039
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001040 def warm_reboot(self):
1041 """Request a warm reboot.
1042
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001043 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001044 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001045 # Use cold reset if the warm reset is broken.
1046 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001047 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1048 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001049 else:
1050 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001051
1052
1053 def cold_reboot(self):
1054 """Request a cold reboot.
1055
1056 A wrapper for underlying servo cold reset.
1057 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001058 if self.client_attr.platform == 'Parrot':
1059 self.servo.set('pwr_button', 'press')
1060 self.servo.set('cold_reset', 'on')
1061 self.servo.set('cold_reset', 'off')
1062 time.sleep(self.POWER_BTN_DELAY)
1063 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001064 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001065 # We don't use servo.cold_reset() here because software sync is
1066 # not yet finished, and device may or may not come up after cold
1067 # reset. Pressing power button before firmware comes up solves this.
1068 #
1069 # The correct behavior should be (not work now):
1070 # - If rebooting EC with rec mode on, power on AP and it boots
1071 # into recovery mode.
1072 # - If rebooting EC with rec mode off, power on AP for software
1073 # sync. Then AP checks if lid open or not. If lid open, continue;
1074 # otherwise, shut AP down and need servo for a power button
1075 # press.
1076 self.servo.set('cold_reset', 'on')
1077 self.servo.set('cold_reset', 'off')
1078 time.sleep(self.POWER_BTN_DELAY)
1079 self.servo.power_short_press()
1080 else:
1081 self.servo.cold_reset()
1082
1083
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001084 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001085 """Request the client sync and do a warm reboot.
1086
1087 This is the default reboot action on FAFT.
1088 """
1089 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001090 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001091 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001092
1093
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001094 def sync_and_cold_reboot(self):
1095 """Request the client sync and do a cold reboot.
1096
1097 This reboot action is used to reset EC for recovery mode.
1098 """
1099 self.faft_client.run_shell_command('sync')
1100 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001101 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001102
1103
Vic Yangaeb10392012-08-28 09:25:09 +08001104 def sync_and_ec_reboot(self, args=''):
1105 """Request the client sync and do a EC triggered reboot.
1106
1107 Args:
1108 args: Arguments passed to "ectool reboot_ec". Including:
1109 RO: jump to EC RO firmware.
1110 RW: jump to EC RW firmware.
1111 cold: Cold/hard reboot.
1112 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001113 self.faft_client.run_shell_command('sync')
1114 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001115 # Since EC reboot happens immediately, delay before actual reboot to
1116 # allow FAFT client returning.
1117 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1118 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001119 time.sleep(self.EC_REBOOT_DELAY)
1120 self.check_lid_and_power_on()
1121
1122
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001123 def full_power_off_and_on(self):
1124 """Shutdown the device by pressing power button and power on again."""
1125 # Press power button to trigger Chrome OS normal shutdown process.
1126 self.servo.power_normal_press()
1127 time.sleep(self.FULL_POWER_OFF_DELAY)
1128 # Short press power button to boot DUT again.
1129 self.servo.power_short_press()
1130
1131
Vic Yangf86728a2012-07-30 10:44:07 +08001132 def check_lid_and_power_on(self):
1133 """
1134 On devices with EC software sync, system powers on after EC reboots if
1135 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1136 This method checks lid switch state and presses power button if
1137 necessary.
1138 """
1139 if self.servo.get("lid_open") == "no":
1140 time.sleep(self.SOFTWARE_SYNC_DELAY)
1141 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001142
1143
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001144 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1145 """Modify the kernel header magic in USB stick.
1146
1147 The kernel header magic is the first 8-byte of kernel partition.
1148 We modify it to make it fail on kernel verification check.
1149
1150 Args:
1151 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1152 from_magic: A string of magic which we change it from.
1153 to_magic: A string of magic which we change it to.
1154
1155 Raises:
1156 error.TestError: if failed to change magic.
1157 """
1158 assert len(from_magic) == 8
1159 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001160 # USB image only contains one kernel.
1161 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001162 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1163 current_magic = utils.system_output(read_cmd)
1164 if current_magic == to_magic:
1165 logging.info("The kernel magic is already %s." % current_magic)
1166 return
1167 if current_magic != from_magic:
1168 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1169
1170 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1171 (from_magic, to_magic))
1172 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1173 " 2>/dev/null" % (to_magic, kernel_part))
1174 utils.system(write_cmd)
1175
1176 if utils.system_output(read_cmd) != to_magic:
1177 raise error.TestError("Failed to write new magic.")
1178
1179
1180 def corrupt_usb_kernel(self, usb_dev):
1181 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1182
1183 Args:
1184 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1185 """
1186 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1187 self.CORRUPTED_MAGIC)
1188
1189
1190 def restore_usb_kernel(self, usb_dev):
1191 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1192
1193 Args:
1194 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1195 """
1196 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1197 self.CHROMEOS_MAGIC)
1198
1199
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001200 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001201 """Call the action function with/without arguments.
1202
1203 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001204 action_tuple: A function, or a tuple (function, args, error_msg),
1205 in which, args and error_msg are optional. args is
1206 either a value or a tuple if multiple arguments.
1207 check_status: Check the return value of action function. If not
1208 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001209
1210 Returns:
1211 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001212
1213 Raises:
1214 error.TestError: An error when the action function is not callable.
1215 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001216 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001217 action = action_tuple
1218 args = ()
1219 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001220 if isinstance(action_tuple, tuple):
1221 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001222 if len(action_tuple) >= 2:
1223 args = action_tuple[1]
1224 if not isinstance(args, tuple):
1225 args = (args,)
1226 if len(action_tuple) >= 3:
1227 error_msg = action
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001228
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001229 if action is None:
1230 return
1231
1232 if not callable(action):
1233 raise error.TestError('action is not callable!')
1234
1235 info_msg = 'calling %s' % str(action)
1236 if args:
1237 info_msg += ' with args %s' % str(args)
1238 logging.info(info_msg)
1239 ret = action(*args)
1240
1241 if check_status and not ret:
1242 raise error.TestFail('%s: %s returning %s' %
1243 (error_msg, info_msg, str(ret)))
1244 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001245
1246
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001247 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1248 post_power_action=None):
1249 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1250
1251 Args:
1252 shutdown_action: a function which makes DUT shutdown, like pressing
1253 power key.
1254 pre_power_action: a function which is called before next power on.
1255 post_power_action: a function which is called after next power on.
1256
1257 Raises:
1258 error.TestFail: if the shutdown_action() failed to turn DUT off.
1259 """
1260 self._call_action(shutdown_action)
1261 logging.info('Wait to ensure DUT shut down...')
1262 try:
1263 self.wait_for_client()
1264 raise error.TestFail(
1265 'Should shut the device down after calling %s.' %
1266 str(shutdown_action))
1267 except AssertionError:
1268 logging.info(
1269 'DUT is surely shutdown. We are going to power it on again...')
1270
1271 if pre_power_action:
1272 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001273 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001274 if post_power_action:
1275 self._call_action(post_power_action)
1276
1277
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001278 def register_faft_template(self, template):
1279 """Register FAFT template, the default FAFT_STEP of each step.
1280
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001281 Any missing field falls back to the original faft_template.
1282
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001283 Args:
1284 template: A FAFT_STEP dict.
1285 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001286 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001287
1288
1289 def register_faft_sequence(self, sequence):
1290 """Register FAFT sequence.
1291
1292 Args:
1293 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1294 """
1295 self._faft_sequence = sequence
1296
1297
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001298 def run_faft_step(self, step, no_reboot=False):
1299 """Run a single FAFT step.
1300
1301 Any missing field falls back to faft_template. An empty step means
1302 running the default faft_template.
1303
1304 Args:
1305 step: A FAFT_STEP dict.
1306 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001307
1308 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001309 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001310 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001311 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1312 'firmware_action', 'install_deps_after_boot')
1313
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001314 test = {}
1315 test.update(self._faft_template)
1316 test.update(step)
1317
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001318 for key in test:
1319 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001320 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001321
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001322 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001323 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001324
1325 self._call_action(test['userspace_action'])
1326
1327 # Don't run reboot_action and firmware_action if no_reboot is True.
1328 if not no_reboot:
1329 self._call_action(test['reboot_action'])
1330 self.wait_for_client_offline()
1331 self._call_action(test['firmware_action'])
1332
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001333 try:
1334 if 'install_deps_after_boot' in test:
1335 self.wait_for_client(
1336 install_deps=test['install_deps_after_boot'])
1337 else:
1338 self.wait_for_client()
1339 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001340 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001341 self.reset_client()
1342 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001343
1344
1345 def run_faft_sequence(self):
1346 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001347 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001348 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001349 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001350 logging.info('======== Running FAFT sequence step %d ========' %
1351 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001352 # Don't reboot in the last step.
1353 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001354 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001355
1356
ctchang38ae4922012-09-03 17:01:16 +08001357 def get_current_firmware_sha(self):
1358 """Get current firmware sha of body and vblock.
1359
1360 Returns:
1361 Current firmware sha follows the order (
1362 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1363 """
1364 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1365 self.faft_client.get_firmware_sha('a'),
1366 self.faft_client.get_firmware_sig_sha('b'),
1367 self.faft_client.get_firmware_sha('b'))
1368 return current_firmware_sha
1369
1370
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001371 def is_firmware_changed(self):
1372 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001373
1374 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001375 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001376 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001377 # Device may not be rebooted after test.
1378 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001379
1380 current_sha = self.get_current_firmware_sha()
1381
1382 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001383 return False
ctchang38ae4922012-09-03 17:01:16 +08001384 else:
ctchang38ae4922012-09-03 17:01:16 +08001385 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1386 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1387 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1388 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001389 logging.info("Firmware changed:")
1390 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1391 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1392 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1393 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1394 return True
ctchang38ae4922012-09-03 17:01:16 +08001395
1396
1397 def backup_firmware(self, suffix='.original'):
1398 """Backup firmware to file, and then send it to host.
1399
1400 Args:
1401 suffix: a string appended to backup file name
1402 """
1403 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001404 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1405 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1406 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001407
1408 self._backup_firmware_sha = self.get_current_firmware_sha()
1409 logging.info('Backup firmware stored in %s with suffix %s' % (
1410 self.resultsdir, suffix))
1411
1412
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001413 def is_firmware_saved(self):
1414 """Check if a firmware saved (called backup_firmware before).
1415
1416 Returns:
1417 True if the firmware is backuped; otherwise False.
1418 """
1419 return self._backup_firmware_sha != ()
1420
1421
ctchang38ae4922012-09-03 17:01:16 +08001422 def restore_firmware(self, suffix='.original'):
1423 """Restore firmware from host in resultsdir.
1424
1425 Args:
1426 suffix: a string appended to backup file name
1427 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001428 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001429 return
1430
1431 # Backup current corrupted firmware.
1432 self.backup_firmware(suffix='.corrupt')
1433
1434 # Restore firmware.
1435 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001436 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1437 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001438
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001439 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001440 self.sync_and_warm_reboot()
1441 self.wait_for_client_offline()
1442 self.wait_for_client()
1443
ctchang38ae4922012-09-03 17:01:16 +08001444 logging.info('Successfully restore firmware.')