blob: 044d172af5ceba45424a1b9f98b6255994683b39 [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
Vic Yangb4e3e742012-06-02 13:17:38 +08006import fdpexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08007import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08008import os
Vic Yangb4e3e742012-06-02 13:17:38 +08009import pexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080010import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080011import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080012import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080013import time
14import xmlrpclib
15
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080016from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080017from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +080018from autotest_lib.server.cros import vboot_constants as vboot
Vic Yangebd6de62012-06-26 14:25:57 +080019from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080020from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080021from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080022
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080023dirname = os.path.dirname(sys.modules[__name__].__file__)
24autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
25cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080026
27class FAFTSequence(ServoTest):
28 """
29 The base class of Fully Automated Firmware Test Sequence.
30
31 Many firmware tests require several reboot cycles and verify the resulted
32 system states. To do that, an Autotest test case should detailly handle
33 every action on each step. It makes the test case hard to read and many
34 duplicated code. The base class FAFTSequence is to solve this problem.
35
36 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
37 There are four functions in the FAFT_STEP dict:
38 state_checker: a function to check the current is valid or not,
39 returning True if valid, otherwise, False to break the whole
40 test sequence.
41 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080042 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080043 firmware_action: a function to describe the action ran after reboot.
44
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080045 And configurations:
46 install_deps_after_boot: if True, install the Autotest dependency after
47 boot; otherwise, do nothing. It is for the cases of recovery mode
48 test. The test boots a USB/SD image instead of an internal image.
49 The previous installed Autotest dependency on the internal image
50 is lost. So need to install it again.
51
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080052 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080053 userspace_action and firmware_action. Its reboot_action is a hardware
54 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080055 self.register_faft_template(FAFT_STEP).
56
57 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
58 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
59 fall back to default.
60
61 In the run_once(), it should register and run FAFT_SEQUENCE like:
62 def run_once(self):
63 self.register_faft_sequence(FAFT_SEQUENCE)
64 self.run_faft_sequnce()
65
66 Note that in the last step, we only run state_checker. The
67 userspace_action, reboot_action, and firmware_action are not executed.
68
69 Attributes:
70 _faft_template: The default FAFT_STEP of each step. The actions would
71 be over-written if the registered FAFT_SEQUENCE is valid.
72 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080073 _customized_ctrl_d_key_command: The customized Ctrl-D key command
74 instead of sending key via servo board.
75 _customized_enter_key_command: The customized Enter key command instead
76 of sending key via servo board.
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +080077 _customized_space_key_command: The customized Space key command instead
78 of sending key via servo board.
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +080079 _customized_rec_reboot_command: The customized recovery reboot command
80 instead of sending key combination of Power + Esc + F3 for
81 triggering recovery reboot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080082 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080083 _firmware_update: Boolean. True if firmware update needed after
84 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080085 """
86 version = 1
87
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080088
89 # Mapping of partition number of kernel and rootfs.
90 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
91 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
92 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
93 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
94
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080096 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080097 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080098 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080099 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800100 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800101 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +0800102 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800103 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800104 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +0800105 # Delay for waiting client to return before EC reboot
106 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800107 # Delay for waiting client to full power off
108 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800109 # Delay between EC reboot and pressing power button
110 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800111 # Delay of EC software sync hash calculating time
112 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800113 # Delay between EC boot and ChromeEC console functional
114 EC_BOOT_DELAY = 0.5
115 # Duration of holding cold_reset to reset device
116 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800117
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800118 # The developer screen timeouts fit our spec.
119 DEV_SCREEN_TIMEOUT = 30
120
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800121 CHROMEOS_MAGIC = "CHROMEOS"
122 CORRUPTED_MAGIC = "CORRUPTD"
123
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800124 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800125 _faft_sequence = ()
126
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800127 _customized_ctrl_d_key_command = None
128 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800129 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800130 _customized_rec_reboot_command = None
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
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800136
137 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
138 # Parse arguments from command line
139 args = {}
140 for arg in cmdline_args:
141 match = re.search("^(\w+)=(.+)", arg)
142 if match:
143 args[match.group(1)] = match.group(2)
144
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800145 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800146 if 'ctrl_d_cmd' in args:
147 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
148 logging.info('Customized Ctrl-D key command: %s' %
149 self._customized_ctrl_d_key_command)
150 if 'enter_cmd' in args:
151 self._customized_enter_key_command = args['enter_cmd']
152 logging.info('Customized Enter key command: %s' %
153 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800154 if 'space_cmd' in args:
155 self._customized_space_key_command = args['space_cmd']
156 logging.info('Customized Space key command: %s' %
157 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800158 if 'rec_reboot_cmd' in args:
159 self._customized_rec_reboot_command = args['rec_reboot_cmd']
160 logging.info('Customized recovery reboot command: %s' %
161 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800162 if 'image' in args:
163 self._install_image_path = args['image']
164 logging.info('Install Chrome OS test image path: %s' %
165 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800166 if 'firmware_update' in args and args['firmware_update'].lower() \
167 not in ('0', 'false', 'no'):
168 if self._install_image_path:
169 self._firmware_update = True
170 logging.info('Also update firmware after installing.')
171 else:
172 logging.warning('Firmware update will not not performed '
173 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800174
175 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
176 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800177 if use_faft:
178 self.client_attr = FAFTClientAttribute(
179 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800180
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700181 # Setting up key matrix mapping
182 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
183
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800184
185 def setup(self):
186 """Autotest setup function."""
187 super(FAFTSequence, self).setup()
188 if not self._remote_infos['faft']['used']:
189 raise error.TestError('The use_faft flag should be enabled.')
190 self.register_faft_template({
191 'state_checker': (None),
192 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800193 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800194 'firmware_action': (None)
195 })
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800196 self.clear_set_gbb_flags(vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
197 vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
198 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800199 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800200 self.install_test_image(self._install_image_path,
201 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800202
203
204 def cleanup(self):
205 """Autotest cleanup function."""
206 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800207 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800208 super(FAFTSequence, self).cleanup()
209
210
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800211 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800212 """Reset client, if necessary.
213
214 This method is called when the client is not responsive. It may be
215 caused by the following cases:
216 - network flaky (can be recovered by replugging the Ethernet);
217 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
218 - corrupted firmware;
219 - corrutped OS image.
220 """
221 # DUT works fine, done.
222 if self._ping_test(self._client.ip, timeout=5):
223 return
224
225 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
226 # first reset item.
227
228 # DUT may halt on a firmware screen. Try cold reboot.
229 logging.info('Try cold reboot...')
230 self.cold_reboot()
231 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800232 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800233 return
234 except AssertionError:
235 pass
236
237 # DUT may be broken by a corrupted firmware. Restore firmware.
238 # We assume the recovery boot still works fine. Since the recovery
239 # code is in RO region and all FAFT tests don't change the RO region
240 # except GBB.
241 if self.is_firmware_saved():
242 self.ensure_client_in_recovery()
243 logging.info('Try restore the original firmware...')
244 if self.is_firmware_changed():
245 try:
246 self.restore_firmware()
247 return
248 except AssertionError:
249 logging.info('Restoring firmware doesn\'t help.')
250
251 # DUT may be broken by a corrupted OS image. Restore OS image.
252 self.ensure_client_in_recovery()
253 logging.info('Try restore the OS image...')
254 self.faft_client.run_shell_command('chromeos-install --yes')
255 self.sync_and_warm_reboot()
256 self.wait_for_client_offline()
257 try:
258 self.wait_for_client(install_deps=True)
259 logging.info('Successfully restore OS image.')
260 return
261 except AssertionError:
262 logging.info('Restoring OS image doesn\'t help.')
263
264
265 def ensure_client_in_recovery(self):
266 """Ensure client in recovery boot; reboot into it if necessary.
267
268 Raises:
269 error.TestError: if failed to boot the USB image.
270 """
271 # DUT works fine and is already in recovery boot, done.
272 if self._ping_test(self._client.ip, timeout=5):
273 if self.crossystem_checker({'mainfw_type': 'recovery'}):
274 return
275
276 logging.info('Try boot into USB image...')
277 self.servo.enable_usb_hub(host=True)
278 self.enable_rec_mode_and_reboot()
279 self.wait_fw_screen_and_plug_usb()
280 try:
281 self.wait_for_client(install_deps=True)
282 except AssertionError:
283 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800284
285
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800286 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800287 """Assert an USB disk plugged-in on servo and a test image inside.
288
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800289 Args:
290 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
291 If None, it is detected automatically.
292
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800293 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800294 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800295 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800296 if usb_dev:
297 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
298 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700299 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800300 usb_dev = self.servo.probe_host_usb_dev()
301 if not usb_dev:
302 raise error.TestError(
303 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800304
305 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800306 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800307 code = utils.system(
308 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
309 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800310 utils.system('sudo umount %s' % tmp_dir)
311 os.removedirs(tmp_dir)
312 if code != 0:
313 raise error.TestError(
314 'The image in the USB disk should be a test image.')
315
316
Simran Basi741b5d42012-05-18 11:27:15 -0700317 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800318 """Install the test image specied by the path onto the USB and DUT disk.
319
320 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500321 recovery mode. Then runs 'chromeos-install' (and possible
322 chromeos-firmwareupdate') to install it to DUT disk.
323
324 Sample command line:
325
326 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
327 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
328 server/site_tests/firmware_XXXX/control
329
330 This test requires an automated recovery to occur while simulating
331 inserting and removing the usb key from the servo. To allow this the
332 following hardware setup is required:
333 1. servo2 board connected via servoflex.
334 2. USB key inserted in the servo2.
335 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
336 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800337
338 Args:
339 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800340 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800341 """
342 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
343 image_path)
344 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800345
Mike Truty49153d82012-08-21 22:27:30 -0500346 # Reuse the servo method that uses the servo USB key to install
347 # the test image.
348 self.servo.image_to_servo_usb(image_path)
349
350 # DUT is powered off while imaging servo USB.
351 # Now turn it on.
352 self.servo.power_short_press()
353 self.wait_for_client()
354 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
355
356 install_cmd = 'chromeos-install --yes'
357 if firmware_update:
358 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
359
360 self.register_faft_sequence((
361 { # Step 1, request recovery boot
362 'state_checker': (self.crossystem_checker, {
363 'mainfw_type': ('developer', 'normal'),
364 }),
365 'userspace_action': self.faft_client.request_recovery_boot,
366 'firmware_action': self.wait_fw_screen_and_plug_usb,
367 'install_deps_after_boot': True,
368 },
369 { # Step 2, expected recovery boot
370 'state_checker': (self.crossystem_checker, {
371 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800372 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500373 }),
374 'userspace_action': (self.faft_client.run_shell_command,
375 install_cmd),
376 'reboot_action': self.cold_reboot,
377 'install_deps_after_boot': True,
378 },
379 { # Step 3, expected normal or developer boot (not recovery)
380 'state_checker': (self.crossystem_checker, {
381 'mainfw_type': ('developer', 'normal')
382 }),
383 },
384 ))
385 self.run_faft_sequence()
386 # 'Unplug' any USB keys in the servo from the dut.
387 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800388
389
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800390 def clear_set_gbb_flags(self, clear_mask, set_mask):
391 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800392
393 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800394 clear_mask: A mask of flags to be cleared.
395 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800396 """
397 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800398 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
399
400 if (gbb_flags != new_flags):
401 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
402 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800403 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800404 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800405 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800406 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800407 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800408 self.run_faft_step({
409 'firmware_action': self.wait_fw_screen_and_ctrl_d,
410 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800411
412
Vic Yangb4e3e742012-06-02 13:17:38 +0800413 def _open_uart_pty(self):
414 """Open UART pty and spawn pexpect object.
415
416 Returns:
417 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
418 child is a fdpexpect object tied to it.
419 """
420 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
421 child = fdpexpect.fdspawn(fd)
422 return (fd, child)
423
424
425 def _flush_uart_pty(self, child):
426 """Flush UART output to prevent previous pending message interferring.
427
428 Args:
429 child: The fdpexpect object tied to UART pty.
430 """
431 child.sendline("")
432 while True:
433 try:
434 child.expect(".", timeout=0.01)
435 except pexpect.TIMEOUT:
436 break
437
438
439 def _uart_send(self, child, line):
440 """Flush and send command through UART.
441
442 Args:
443 child: The pexpect object tied to UART pty.
444 line: String to send through UART.
445
446 Raises:
447 error.TestFail: Raised when writing to UART fails.
448 """
449 logging.info("Sending UART command: %s" % line)
450 self._flush_uart_pty(child)
451 if child.sendline(line) != len(line) + 1:
452 raise error.TestFail("Failed to send UART command.")
453
454
455 def send_uart_command(self, command):
456 """Send command through UART.
457
458 This function open UART pty when called, and then command is sent
459 through UART.
460
461 Args:
462 command: The command string to send.
463
464 Raises:
465 error.TestFail: Raised when writing to UART fails.
466 """
467 (fd, child) = self._open_uart_pty()
468 try:
469 self._uart_send(child, command)
470 finally:
471 os.close(fd)
472
473
474 def send_uart_command_get_output(self, command, regex_list, timeout=1):
475 """Send command through UART and wait for response.
476
477 This function waits for response message matching regular expressions.
478
479 Args:
480 command: The command sent.
481 regex_list: List of regular expressions used to match response message.
482 Note, list must be ordered.
483
484 Returns:
485 List of match objects of response message.
486
487 Raises:
488 error.TestFail: If timed out waiting for EC response.
489 """
490 if not isinstance(regex_list, list):
491 regex_list = [regex_list]
492 result_list = []
493 (fd, child) = self._open_uart_pty()
494 try:
495 self._uart_send(child, command)
496 for regex in regex_list:
497 child.expect(regex, timeout=timeout)
498 result_list.append(child.match)
499 except pexpect.TIMEOUT:
500 raise error.TestFail("Timeout waiting for UART response.")
501 finally:
502 os.close(fd)
503 return result_list
504
505
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800506 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800507 """Check if current platform has required EC capabilities.
508
509 Args:
510 required_cap: A list containing required EC capabilities. Pass in
511 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800512 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800513
514 Returns:
515 True if requirements are met. Otherwise, False.
516 """
517 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800518 if not suppress_warning:
519 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800520 return False
521
522 for cap in required_cap:
523 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800524 if not suppress_warning:
525 logging.warn('Requires EC capability "%s" to run this '
526 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800527 return False
528
529 return True
530
531
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800532 def _parse_crossystem_output(self, lines):
533 """Parse the crossystem output into a dict.
534
535 Args:
536 lines: The list of crossystem output strings.
537
538 Returns:
539 A dict which contains the crossystem keys/values.
540
541 Raises:
542 error.TestError: If wrong format in crossystem output.
543
544 >>> seq = FAFTSequence()
545 >>> seq._parse_crossystem_output([ \
546 "arch = x86 # Platform architecture", \
547 "cros_debug = 1 # OS should allow debug", \
548 ])
549 {'cros_debug': '1', 'arch': 'x86'}
550 >>> seq._parse_crossystem_output([ \
551 "arch=x86", \
552 ])
553 Traceback (most recent call last):
554 ...
555 TestError: Failed to parse crossystem output: arch=x86
556 >>> seq._parse_crossystem_output([ \
557 "arch = x86 # Platform architecture", \
558 "arch = arm # Platform architecture", \
559 ])
560 Traceback (most recent call last):
561 ...
562 TestError: Duplicated crossystem key: arch
563 """
564 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
565 parsed_list = {}
566 for line in lines:
567 matched = re.match(pattern, line.strip())
568 if not matched:
569 raise error.TestError("Failed to parse crossystem output: %s"
570 % line)
571 (name, value) = (matched.group(1), matched.group(2))
572 if name in parsed_list:
573 raise error.TestError("Duplicated crossystem key: %s" % name)
574 parsed_list[name] = value
575 return parsed_list
576
577
578 def crossystem_checker(self, expected_dict):
579 """Check the crossystem values matched.
580
581 Given an expect_dict which describes the expected crossystem values,
582 this function check the current crossystem values are matched or not.
583
584 Args:
585 expected_dict: A dict which contains the expected values.
586
587 Returns:
588 True if the crossystem value matched; otherwise, False.
589 """
590 lines = self.faft_client.run_shell_command_get_output('crossystem')
591 got_dict = self._parse_crossystem_output(lines)
592 for key in expected_dict:
593 if key not in got_dict:
594 logging.info('Expected key "%s" not in crossystem result' % key)
595 return False
596 if isinstance(expected_dict[key], str):
597 if got_dict[key] != expected_dict[key]:
598 logging.info("Expected '%s' value '%s' but got '%s'" %
599 (key, expected_dict[key], got_dict[key]))
600 return False
601 elif isinstance(expected_dict[key], tuple):
602 # Expected value is a tuple of possible actual values.
603 if got_dict[key] not in expected_dict[key]:
604 logging.info("Expected '%s' values %s but got '%s'" %
605 (key, str(expected_dict[key]), got_dict[key]))
606 return False
607 else:
608 logging.info("The expected_dict is neither a str nor a dict.")
609 return False
610 return True
611
612
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800613 def vdat_flags_checker(self, mask, value):
614 """Check the flags from VbSharedData matched.
615
616 This function checks the masked flags from VbSharedData using crossystem
617 are matched the given value.
618
619 Args:
620 mask: A bitmask of flags to be matched.
621 value: An expected value.
622
623 Returns:
624 True if the flags matched; otherwise, False.
625 """
626 lines = self.faft_client.run_shell_command_get_output(
627 'crossystem vdat_flags')
628 vdat_flags = int(lines[0], 16)
629 if vdat_flags & mask != value:
630 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
631 (value, mask, vdat_flags))
632 return False
633 return True
634
635
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800636 def ro_normal_checker(self, expected_fw=None, twostop=False):
637 """Check the current boot uses RO boot.
638
639 Args:
640 expected_fw: A string of expected firmware, 'A', 'B', or
641 None if don't care.
642 twostop: True to expect a TwoStop boot; False to expect a RO boot.
643
644 Returns:
645 True if the currect boot firmware matched and used RO boot;
646 otherwise, False.
647 """
648 crossystem_dict = {'tried_fwb': '0'}
649 if expected_fw:
650 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800651 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800652 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
653
654 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800655 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
656 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800657 self.crossystem_checker(crossystem_dict))
658
659
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800660 def root_part_checker(self, expected_part):
661 """Check the partition number of the root device matched.
662
663 Args:
664 expected_part: A string containing the number of the expected root
665 partition.
666
667 Returns:
668 True if the currect root partition number matched; otherwise, False.
669 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800670 part = self.faft_client.get_root_part()[-1]
671 if self.ROOTFS_MAP[expected_part] != part:
672 logging.info("Expected root part %s but got %s" %
673 (self.ROOTFS_MAP[expected_part], part))
674 return False
675 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800676
677
Vic Yang59cac9c2012-05-21 15:28:42 +0800678 def ec_act_copy_checker(self, expected_copy):
679 """Check the EC running firmware copy matches.
680
681 Args:
682 expected_copy: A string containing 'RO', 'A', or 'B' indicating
683 the expected copy of EC running firmware.
684
685 Returns:
686 True if the current EC running copy matches; otherwise, False.
687 """
688 lines = self.faft_client.run_shell_command_get_output('ectool version')
689 pattern = re.compile("Firmware copy: (.*)")
690 for line in lines:
691 matched = pattern.match(line)
692 if matched and matched.group(1) == expected_copy:
693 return True
694 return False
695
696
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800697 def check_root_part_on_non_recovery(self, part):
698 """Check the partition number of root device and on normal/dev boot.
699
700 Returns:
701 True if the root device matched and on normal/dev boot;
702 otherwise, False.
703 """
704 return self.root_part_checker(part) and \
705 self.crossystem_checker({
706 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800707 })
708
709
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800710 def _join_part(self, dev, part):
711 """Return a concatenated string of device and partition number.
712
713 Args:
714 dev: A string of device, e.g.'/dev/sda'.
715 part: A string of partition number, e.g.'3'.
716
717 Returns:
718 A concatenated string of device and partition number, e.g.'/dev/sda3'.
719
720 >>> seq = FAFTSequence()
721 >>> seq._join_part('/dev/sda', '3')
722 '/dev/sda3'
723 >>> seq._join_part('/dev/mmcblk0', '2')
724 '/dev/mmcblk0p2'
725 """
726 if 'mmcblk' in dev:
727 return dev + 'p' + part
728 else:
729 return dev + part
730
731
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800732 def copy_kernel_and_rootfs(self, from_part, to_part):
733 """Copy kernel and rootfs from from_part to to_part.
734
735 Args:
736 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800737 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800738 """
739 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800740 logging.info('Copying kernel from %s to %s. Please wait...' %
741 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800742 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800743 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
744 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
745 logging.info('Copying rootfs from %s to %s. Please wait...' %
746 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800747 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800748 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
749 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800750
751
752 def ensure_kernel_boot(self, part):
753 """Ensure the request kernel boot.
754
755 If not, it duplicates the current kernel to the requested kernel
756 and sets the requested higher priority to ensure it boot.
757
758 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800759 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800760 """
761 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800762 if self.faft_client.diff_kernel_a_b():
763 self.copy_kernel_and_rootfs(
764 from_part=self.OTHER_KERNEL_MAP[part],
765 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800766 self.run_faft_step({
767 'userspace_action': (self.reset_and_prioritize_kernel, part),
768 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800769
770
Vic Yang416f2032012-08-28 10:18:03 +0800771 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800772 """Set hardware write protect pin.
773
774 Args:
775 enable: True if asserting write protect pin. Otherwise, False.
776 """
777 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
778 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800779 self.servo.set('fw_wp', 'on' if enabled else 'off')
780
781
782 def set_EC_write_protect_and_reboot(self, enabled):
783 """Set EC write protect status and reboot to take effect.
784
785 EC write protect is only activated if both hardware write protect pin
786 is asserted and software write protect flag is set. Also, a reboot is
787 required for write protect to take effect.
788
789 Since the software write protect flag cannot be unset if hardware write
790 protect pin is asserted, we need to deasserted the pin first if we are
791 deactivating write protect. Similarly, a reboot is required before we
792 can modify the software flag.
793
794 This method asserts/deasserts hardware write protect pin first, and
795 set corresponding EC software write protect flag.
796
797 Args:
798 enable: True if activating EC write protect. Otherwise, False.
799 """
800 self.set_hardware_write_protect(enabled)
801 if enabled:
802 # Set write protect flag and reboot to take effect.
803 self.send_uart_command("flashwp enable")
804 self.sync_and_ec_reboot()
805 else:
806 # Reboot after deasserting hardware write protect pin to deactivate
807 # write protect. And then remove software write protect flag.
808 self.sync_and_ec_reboot()
809 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800810
811
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800812 def send_ctrl_d_to_dut(self):
813 """Send Ctrl-D key to DUT."""
814 if self._customized_ctrl_d_key_command:
815 logging.info('running the customized Ctrl-D key command')
816 os.system(self._customized_ctrl_d_key_command)
817 else:
818 self.servo.ctrl_d()
819
820
821 def send_enter_to_dut(self):
822 """Send Enter key to DUT."""
823 if self._customized_enter_key_command:
824 logging.info('running the customized Enter key command')
825 os.system(self._customized_enter_key_command)
826 else:
827 self.servo.enter_key()
828
829
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800830 def send_space_to_dut(self):
831 """Send Space key to DUT."""
832 if self._customized_space_key_command:
833 logging.info('running the customized Space key command')
834 os.system(self._customized_space_key_command)
835 else:
836 # Send the alternative key combinaton of space key to servo.
837 self.servo.ctrl_refresh_key()
838
839
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800840 def wait_fw_screen_and_ctrl_d(self):
841 """Wait for firmware warning screen and press Ctrl-D."""
842 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800843 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800844
845
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800846 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
847 """Wait for firmware warning screen and trigger recovery boot."""
848 time.sleep(self.FIRMWARE_SCREEN_DELAY)
849 self.send_enter_to_dut()
850
851 # For Alex/ZGB, there is a dev warning screen in text mode.
852 # Skip it by pressing Ctrl-D.
853 if need_dev_transition:
854 time.sleep(self.TEXT_SCREEN_DELAY)
855 self.send_ctrl_d_to_dut()
856
857
Mike Truty49153d82012-08-21 22:27:30 -0500858 def wait_fw_screen_and_unplug_usb(self):
859 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800860 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800861 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
862 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500863
864
865 def wait_fw_screen_and_plug_usb(self):
866 """Wait for firmware warning screen and then unplug and plug the USB."""
867 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800868 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
869
870
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800871 def wait_fw_screen_and_press_power(self):
872 """Wait for firmware warning screen and press power button."""
873 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800874 # While the firmware screen, the power button probing loop sleeps
875 # 0.25 second on every scan. Use the normal delay (1.2 second) for
876 # power press.
877 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800878
879
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800880 def wait_longer_fw_screen_and_press_power(self):
881 """Wait for firmware screen without timeout and press power button."""
882 time.sleep(self.DEV_SCREEN_TIMEOUT)
883 self.wait_fw_screen_and_press_power()
884
885
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800886 def wait_fw_screen_and_close_lid(self):
887 """Wait for firmware warning screen and close lid."""
888 time.sleep(self.FIRMWARE_SCREEN_DELAY)
889 self.servo.lid_close()
890
891
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800892 def wait_longer_fw_screen_and_close_lid(self):
893 """Wait for firmware screen without timeout and close lid."""
894 time.sleep(self.FIRMWARE_SCREEN_DELAY)
895 self.wait_fw_screen_and_close_lid()
896
897
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800898 def setup_tried_fwb(self, tried_fwb):
899 """Setup for fw B tried state.
900
901 It makes sure the system in the requested fw B tried state. If not, it
902 tries to do so.
903
904 Args:
905 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
906 """
907 if tried_fwb:
908 if not self.crossystem_checker({'tried_fwb': '1'}):
909 logging.info(
910 'Firmware is not booted with tried_fwb. Reboot into it.')
911 self.run_faft_step({
912 'userspace_action': self.faft_client.set_try_fw_b,
913 })
914 else:
915 if not self.crossystem_checker({'tried_fwb': '0'}):
916 logging.info(
917 'Firmware is booted with tried_fwb. Reboot to clear.')
918 self.run_faft_step({})
919
920
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800921 def enable_rec_mode_and_reboot(self):
922 """Switch to rec mode and reboot.
923
924 This method emulates the behavior of the old physical recovery switch,
925 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
926 recovery mode, i.e. just press Power + Esc + Refresh.
927 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800928 if self._customized_rec_reboot_command:
929 logging.info('running the customized rec reboot command')
930 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800931 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800932 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800933 self.servo.set('cold_reset', 'on')
934 time.sleep(self.COLD_RESET_DELAY)
935 self.servo.set('cold_reset', 'off')
936 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +0800937 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800938 time.sleep(self.EC_BOOT_DELAY)
939 self.send_uart_command("hostevent set 0x4000")
940 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800941 else:
942 self.servo.enable_recovery_mode()
943 self.cold_reboot()
944 time.sleep(self.EC_REBOOT_DELAY)
945 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800946
947
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800948 def enable_dev_mode_and_reboot(self):
949 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800950 if self.client_attr.keyboard_dev:
951 self.enable_keyboard_dev_mode()
952 else:
953 self.servo.enable_development_mode()
954 self.faft_client.run_shell_command(
955 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800956
957
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800958 def enable_normal_mode_and_reboot(self):
959 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800960 if self.client_attr.keyboard_dev:
961 self.disable_keyboard_dev_mode()
962 else:
963 self.servo.disable_development_mode()
964 self.faft_client.run_shell_command(
965 'chromeos-firmwareupdate --mode tonormal && reboot')
966
967
968 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
969 """Wait for firmware screen and then switch into or out of dev mode.
970
971 Args:
972 dev: True if switching into dev mode. Otherwise, False.
973 """
974 time.sleep(self.FIRMWARE_SCREEN_DELAY)
975 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800976 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800977 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800978 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800979 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800980 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800981
982
983 def enable_keyboard_dev_mode(self):
984 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800985 # Plug out USB disk for preventing recovery boot without warning
986 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800987 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800988 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800989 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800990 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800991
992
993 def disable_keyboard_dev_mode(self):
994 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800995 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800996 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800997 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800998 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800999 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001000
1001
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001002 def setup_dev_mode(self, dev_mode):
1003 """Setup for development mode.
1004
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001005 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001006 tries to do so.
1007
1008 Args:
1009 dev_mode: True if requested in dev mode; False if normal mode.
1010 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001011 # Change the default firmware_action for dev mode passing the fw screen.
1012 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001013 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1014 else None),
1015 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001016 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001017 if (not self.client_attr.keyboard_dev and
1018 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001019 logging.info('Dev switch is not on. Now switch it on.')
1020 self.servo.enable_development_mode()
1021 if not self.crossystem_checker({'devsw_boot': '1',
1022 'mainfw_type': 'developer'}):
1023 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001024 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001025 'userspace_action': None if self.client_attr.keyboard_dev
1026 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001027 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001028 'reboot_action': self.enable_keyboard_dev_mode if
1029 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001030 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001031 else:
Vic Yange7553162012-06-20 16:20:47 +08001032 if (not self.client_attr.keyboard_dev and
1033 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001034 logging.info('Dev switch is not off. Now switch it off.')
1035 self.servo.disable_development_mode()
1036 if not self.crossystem_checker({'devsw_boot': '0',
1037 'mainfw_type': 'normal'}):
1038 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001039 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001040 'userspace_action': None if self.client_attr.keyboard_dev
1041 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001042 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001043 'reboot_action': self.disable_keyboard_dev_mode if
1044 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001045 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001046
1047
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001048 def setup_kernel(self, part):
1049 """Setup for kernel test.
1050
1051 It makes sure both kernel A and B bootable and the current boot is
1052 the requested kernel part.
1053
1054 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001055 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001056 """
1057 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001058 if self.faft_client.diff_kernel_a_b():
1059 self.copy_kernel_and_rootfs(from_part=part,
1060 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001061 self.reset_and_prioritize_kernel(part)
1062
1063
1064 def reset_and_prioritize_kernel(self, part):
1065 """Make the requested partition highest priority.
1066
1067 This function also reset kerenl A and B to bootable.
1068
1069 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001070 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001071 """
1072 root_dev = self.faft_client.get_root_dev()
1073 # Reset kernel A and B to bootable.
1074 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1075 (self.KERNEL_MAP['a'], root_dev))
1076 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1077 (self.KERNEL_MAP['b'], root_dev))
1078 # Set kernel part highest priority.
1079 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1080 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001081 # Safer to sync and wait until the cgpt status written to the disk.
1082 self.faft_client.run_shell_command('sync')
1083 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001084
1085
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001086 def warm_reboot(self):
1087 """Request a warm reboot.
1088
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001089 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001090 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001091 # Use cold reset if the warm reset is broken.
1092 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001093 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1094 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001095 else:
1096 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001097
1098
1099 def cold_reboot(self):
1100 """Request a cold reboot.
1101
1102 A wrapper for underlying servo cold reset.
1103 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001104 if self.client_attr.platform == 'Parrot':
1105 self.servo.set('pwr_button', 'press')
1106 self.servo.set('cold_reset', 'on')
1107 self.servo.set('cold_reset', 'off')
1108 time.sleep(self.POWER_BTN_DELAY)
1109 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001110 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001111 # We don't use servo.cold_reset() here because software sync is
1112 # not yet finished, and device may or may not come up after cold
1113 # reset. Pressing power button before firmware comes up solves this.
1114 #
1115 # The correct behavior should be (not work now):
1116 # - If rebooting EC with rec mode on, power on AP and it boots
1117 # into recovery mode.
1118 # - If rebooting EC with rec mode off, power on AP for software
1119 # sync. Then AP checks if lid open or not. If lid open, continue;
1120 # otherwise, shut AP down and need servo for a power button
1121 # press.
1122 self.servo.set('cold_reset', 'on')
1123 self.servo.set('cold_reset', 'off')
1124 time.sleep(self.POWER_BTN_DELAY)
1125 self.servo.power_short_press()
1126 else:
1127 self.servo.cold_reset()
1128
1129
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001130 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001131 """Request the client sync and do a warm reboot.
1132
1133 This is the default reboot action on FAFT.
1134 """
1135 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001136 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001137 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001138
1139
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001140 def sync_and_cold_reboot(self):
1141 """Request the client sync and do a cold reboot.
1142
1143 This reboot action is used to reset EC for recovery mode.
1144 """
1145 self.faft_client.run_shell_command('sync')
1146 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001147 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001148
1149
Vic Yangaeb10392012-08-28 09:25:09 +08001150 def sync_and_ec_reboot(self, args=''):
1151 """Request the client sync and do a EC triggered reboot.
1152
1153 Args:
1154 args: Arguments passed to "ectool reboot_ec". Including:
1155 RO: jump to EC RO firmware.
1156 RW: jump to EC RW firmware.
1157 cold: Cold/hard reboot.
1158 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001159 self.faft_client.run_shell_command('sync')
1160 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001161 # Since EC reboot happens immediately, delay before actual reboot to
1162 # allow FAFT client returning.
1163 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1164 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001165 time.sleep(self.EC_REBOOT_DELAY)
1166 self.check_lid_and_power_on()
1167
1168
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001169 def full_power_off_and_on(self):
1170 """Shutdown the device by pressing power button and power on again."""
1171 # Press power button to trigger Chrome OS normal shutdown process.
1172 self.servo.power_normal_press()
1173 time.sleep(self.FULL_POWER_OFF_DELAY)
1174 # Short press power button to boot DUT again.
1175 self.servo.power_short_press()
1176
1177
Vic Yangf86728a2012-07-30 10:44:07 +08001178 def check_lid_and_power_on(self):
1179 """
1180 On devices with EC software sync, system powers on after EC reboots if
1181 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1182 This method checks lid switch state and presses power button if
1183 necessary.
1184 """
1185 if self.servo.get("lid_open") == "no":
1186 time.sleep(self.SOFTWARE_SYNC_DELAY)
1187 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001188
1189
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001190 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1191 """Modify the kernel header magic in USB stick.
1192
1193 The kernel header magic is the first 8-byte of kernel partition.
1194 We modify it to make it fail on kernel verification check.
1195
1196 Args:
1197 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1198 from_magic: A string of magic which we change it from.
1199 to_magic: A string of magic which we change it to.
1200
1201 Raises:
1202 error.TestError: if failed to change magic.
1203 """
1204 assert len(from_magic) == 8
1205 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001206 # USB image only contains one kernel.
1207 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001208 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1209 current_magic = utils.system_output(read_cmd)
1210 if current_magic == to_magic:
1211 logging.info("The kernel magic is already %s." % current_magic)
1212 return
1213 if current_magic != from_magic:
1214 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1215
1216 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1217 (from_magic, to_magic))
1218 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1219 " 2>/dev/null" % (to_magic, kernel_part))
1220 utils.system(write_cmd)
1221
1222 if utils.system_output(read_cmd) != to_magic:
1223 raise error.TestError("Failed to write new magic.")
1224
1225
1226 def corrupt_usb_kernel(self, usb_dev):
1227 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1228
1229 Args:
1230 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1231 """
1232 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1233 self.CORRUPTED_MAGIC)
1234
1235
1236 def restore_usb_kernel(self, usb_dev):
1237 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1238
1239 Args:
1240 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1241 """
1242 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1243 self.CHROMEOS_MAGIC)
1244
1245
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001246 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001247 """Call the action function with/without arguments.
1248
1249 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001250 action_tuple: A function, or a tuple (function, args, error_msg),
1251 in which, args and error_msg are optional. args is
1252 either a value or a tuple if multiple arguments.
1253 check_status: Check the return value of action function. If not
1254 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001255
1256 Returns:
1257 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001258
1259 Raises:
1260 error.TestError: An error when the action function is not callable.
1261 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001262 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001263 action = action_tuple
1264 args = ()
1265 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001266 if isinstance(action_tuple, tuple):
1267 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001268 if len(action_tuple) >= 2:
1269 args = action_tuple[1]
1270 if not isinstance(args, tuple):
1271 args = (args,)
1272 if len(action_tuple) >= 3:
1273 error_msg = action
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001274
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001275 if action is None:
1276 return
1277
1278 if not callable(action):
1279 raise error.TestError('action is not callable!')
1280
1281 info_msg = 'calling %s' % str(action)
1282 if args:
1283 info_msg += ' with args %s' % str(args)
1284 logging.info(info_msg)
1285 ret = action(*args)
1286
1287 if check_status and not ret:
1288 raise error.TestFail('%s: %s returning %s' %
1289 (error_msg, info_msg, str(ret)))
1290 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001291
1292
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001293 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1294 post_power_action=None):
1295 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1296
1297 Args:
1298 shutdown_action: a function which makes DUT shutdown, like pressing
1299 power key.
1300 pre_power_action: a function which is called before next power on.
1301 post_power_action: a function which is called after next power on.
1302
1303 Raises:
1304 error.TestFail: if the shutdown_action() failed to turn DUT off.
1305 """
1306 self._call_action(shutdown_action)
1307 logging.info('Wait to ensure DUT shut down...')
1308 try:
1309 self.wait_for_client()
1310 raise error.TestFail(
1311 'Should shut the device down after calling %s.' %
1312 str(shutdown_action))
1313 except AssertionError:
1314 logging.info(
1315 'DUT is surely shutdown. We are going to power it on again...')
1316
1317 if pre_power_action:
1318 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001319 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001320 if post_power_action:
1321 self._call_action(post_power_action)
1322
1323
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001324 def register_faft_template(self, template):
1325 """Register FAFT template, the default FAFT_STEP of each step.
1326
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001327 Any missing field falls back to the original faft_template.
1328
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001329 Args:
1330 template: A FAFT_STEP dict.
1331 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001332 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001333
1334
1335 def register_faft_sequence(self, sequence):
1336 """Register FAFT sequence.
1337
1338 Args:
1339 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1340 """
1341 self._faft_sequence = sequence
1342
1343
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001344 def run_faft_step(self, step, no_reboot=False):
1345 """Run a single FAFT step.
1346
1347 Any missing field falls back to faft_template. An empty step means
1348 running the default faft_template.
1349
1350 Args:
1351 step: A FAFT_STEP dict.
1352 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001353
1354 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001355 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001356 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001357 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1358 'firmware_action', 'install_deps_after_boot')
1359
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001360 test = {}
1361 test.update(self._faft_template)
1362 test.update(step)
1363
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001364 for key in test:
1365 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001366 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001367
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001368 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001369 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001370
1371 self._call_action(test['userspace_action'])
1372
1373 # Don't run reboot_action and firmware_action if no_reboot is True.
1374 if not no_reboot:
1375 self._call_action(test['reboot_action'])
1376 self.wait_for_client_offline()
1377 self._call_action(test['firmware_action'])
1378
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001379 try:
1380 if 'install_deps_after_boot' in test:
1381 self.wait_for_client(
1382 install_deps=test['install_deps_after_boot'])
1383 else:
1384 self.wait_for_client()
1385 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001386 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001387 self.reset_client()
1388 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001389
1390
1391 def run_faft_sequence(self):
1392 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001393 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001394 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001395 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001396 logging.info('======== Running FAFT sequence step %d ========' %
1397 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001398 # Don't reboot in the last step.
1399 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001400 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001401
1402
ctchang38ae4922012-09-03 17:01:16 +08001403 def get_current_firmware_sha(self):
1404 """Get current firmware sha of body and vblock.
1405
1406 Returns:
1407 Current firmware sha follows the order (
1408 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1409 """
1410 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1411 self.faft_client.get_firmware_sha('a'),
1412 self.faft_client.get_firmware_sig_sha('b'),
1413 self.faft_client.get_firmware_sha('b'))
1414 return current_firmware_sha
1415
1416
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001417 def is_firmware_changed(self):
1418 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001419
1420 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001421 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001422 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001423 # Device may not be rebooted after test.
1424 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001425
1426 current_sha = self.get_current_firmware_sha()
1427
1428 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001429 return False
ctchang38ae4922012-09-03 17:01:16 +08001430 else:
ctchang38ae4922012-09-03 17:01:16 +08001431 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1432 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1433 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1434 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001435 logging.info("Firmware changed:")
1436 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1437 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1438 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1439 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1440 return True
ctchang38ae4922012-09-03 17:01:16 +08001441
1442
1443 def backup_firmware(self, suffix='.original'):
1444 """Backup firmware to file, and then send it to host.
1445
1446 Args:
1447 suffix: a string appended to backup file name
1448 """
1449 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001450 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1451 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1452 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001453
1454 self._backup_firmware_sha = self.get_current_firmware_sha()
1455 logging.info('Backup firmware stored in %s with suffix %s' % (
1456 self.resultsdir, suffix))
1457
1458
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001459 def is_firmware_saved(self):
1460 """Check if a firmware saved (called backup_firmware before).
1461
1462 Returns:
1463 True if the firmware is backuped; otherwise False.
1464 """
1465 return self._backup_firmware_sha != ()
1466
1467
ctchang38ae4922012-09-03 17:01:16 +08001468 def restore_firmware(self, suffix='.original'):
1469 """Restore firmware from host in resultsdir.
1470
1471 Args:
1472 suffix: a string appended to backup file name
1473 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001474 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001475 return
1476
1477 # Backup current corrupted firmware.
1478 self.backup_firmware(suffix='.corrupt')
1479
1480 # Restore firmware.
1481 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001482 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1483 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001484
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001485 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001486 self.sync_and_warm_reboot()
1487 self.wait_for_client_offline()
1488 self.wait_for_client()
1489
ctchang38ae4922012-09-03 17:01:16 +08001490 logging.info('Successfully restore firmware.')