blob: aa4ce2d1d35e393dc8a916532c497cbe900bcc14 [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:
Tom Wai-Hong Tam41859a62012-10-03 09:20:20 +0800485 List of tuples, each of which contains the entire matched string and
486 all the subgroups of the match. None if not matched.
487 For example:
488 response of the given command:
489 High temp: 37.2
490 Low temp: 36.4
491 regex_list:
492 ['High temp: (\d+)\.(\d+)', 'Low temp: (\d+)\.(\d+)']
493 returns:
494 [('High temp: 37.2', '37', '2'), ('Low temp: 36.4', '36', '4')]
Vic Yangb4e3e742012-06-02 13:17:38 +0800495
496 Raises:
497 error.TestFail: If timed out waiting for EC response.
498 """
499 if not isinstance(regex_list, list):
500 regex_list = [regex_list]
501 result_list = []
502 (fd, child) = self._open_uart_pty()
503 try:
504 self._uart_send(child, command)
505 for regex in regex_list:
506 child.expect(regex, timeout=timeout)
Tom Wai-Hong Tam41859a62012-10-03 09:20:20 +0800507 match = child.match
508 lastindex = match.lastindex if match and match.lastindex else 0
509 # Create a tuple which contains the entire matched string and
510 # all the subgroups of the match.
511 result = match.group(*range(lastindex + 1)) if match else None
512 result_list.append(result)
Vic Yangb4e3e742012-06-02 13:17:38 +0800513 except pexpect.TIMEOUT:
514 raise error.TestFail("Timeout waiting for UART response.")
515 finally:
516 os.close(fd)
517 return result_list
518
519
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800520 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800521 """Check if current platform has required EC capabilities.
522
523 Args:
524 required_cap: A list containing required EC capabilities. Pass in
525 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800526 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800527
528 Returns:
529 True if requirements are met. Otherwise, False.
530 """
531 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800532 if not suppress_warning:
533 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800534 return False
535
536 for cap in required_cap:
537 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800538 if not suppress_warning:
539 logging.warn('Requires EC capability "%s" to run this '
540 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800541 return False
542
543 return True
544
545
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800546 def _parse_crossystem_output(self, lines):
547 """Parse the crossystem output into a dict.
548
549 Args:
550 lines: The list of crossystem output strings.
551
552 Returns:
553 A dict which contains the crossystem keys/values.
554
555 Raises:
556 error.TestError: If wrong format in crossystem output.
557
558 >>> seq = FAFTSequence()
559 >>> seq._parse_crossystem_output([ \
560 "arch = x86 # Platform architecture", \
561 "cros_debug = 1 # OS should allow debug", \
562 ])
563 {'cros_debug': '1', 'arch': 'x86'}
564 >>> seq._parse_crossystem_output([ \
565 "arch=x86", \
566 ])
567 Traceback (most recent call last):
568 ...
569 TestError: Failed to parse crossystem output: arch=x86
570 >>> seq._parse_crossystem_output([ \
571 "arch = x86 # Platform architecture", \
572 "arch = arm # Platform architecture", \
573 ])
574 Traceback (most recent call last):
575 ...
576 TestError: Duplicated crossystem key: arch
577 """
578 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
579 parsed_list = {}
580 for line in lines:
581 matched = re.match(pattern, line.strip())
582 if not matched:
583 raise error.TestError("Failed to parse crossystem output: %s"
584 % line)
585 (name, value) = (matched.group(1), matched.group(2))
586 if name in parsed_list:
587 raise error.TestError("Duplicated crossystem key: %s" % name)
588 parsed_list[name] = value
589 return parsed_list
590
591
592 def crossystem_checker(self, expected_dict):
593 """Check the crossystem values matched.
594
595 Given an expect_dict which describes the expected crossystem values,
596 this function check the current crossystem values are matched or not.
597
598 Args:
599 expected_dict: A dict which contains the expected values.
600
601 Returns:
602 True if the crossystem value matched; otherwise, False.
603 """
604 lines = self.faft_client.run_shell_command_get_output('crossystem')
605 got_dict = self._parse_crossystem_output(lines)
606 for key in expected_dict:
607 if key not in got_dict:
608 logging.info('Expected key "%s" not in crossystem result' % key)
609 return False
610 if isinstance(expected_dict[key], str):
611 if got_dict[key] != expected_dict[key]:
612 logging.info("Expected '%s' value '%s' but got '%s'" %
613 (key, expected_dict[key], got_dict[key]))
614 return False
615 elif isinstance(expected_dict[key], tuple):
616 # Expected value is a tuple of possible actual values.
617 if got_dict[key] not in expected_dict[key]:
618 logging.info("Expected '%s' values %s but got '%s'" %
619 (key, str(expected_dict[key]), got_dict[key]))
620 return False
621 else:
622 logging.info("The expected_dict is neither a str nor a dict.")
623 return False
624 return True
625
626
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800627 def vdat_flags_checker(self, mask, value):
628 """Check the flags from VbSharedData matched.
629
630 This function checks the masked flags from VbSharedData using crossystem
631 are matched the given value.
632
633 Args:
634 mask: A bitmask of flags to be matched.
635 value: An expected value.
636
637 Returns:
638 True if the flags matched; otherwise, False.
639 """
640 lines = self.faft_client.run_shell_command_get_output(
641 'crossystem vdat_flags')
642 vdat_flags = int(lines[0], 16)
643 if vdat_flags & mask != value:
644 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
645 (value, mask, vdat_flags))
646 return False
647 return True
648
649
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800650 def ro_normal_checker(self, expected_fw=None, twostop=False):
651 """Check the current boot uses RO boot.
652
653 Args:
654 expected_fw: A string of expected firmware, 'A', 'B', or
655 None if don't care.
656 twostop: True to expect a TwoStop boot; False to expect a RO boot.
657
658 Returns:
659 True if the currect boot firmware matched and used RO boot;
660 otherwise, False.
661 """
662 crossystem_dict = {'tried_fwb': '0'}
663 if expected_fw:
664 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800665 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800666 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
667
668 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800669 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
670 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800671 self.crossystem_checker(crossystem_dict))
672
673
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800674 def root_part_checker(self, expected_part):
675 """Check the partition number of the root device matched.
676
677 Args:
678 expected_part: A string containing the number of the expected root
679 partition.
680
681 Returns:
682 True if the currect root partition number matched; otherwise, False.
683 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800684 part = self.faft_client.get_root_part()[-1]
685 if self.ROOTFS_MAP[expected_part] != part:
686 logging.info("Expected root part %s but got %s" %
687 (self.ROOTFS_MAP[expected_part], part))
688 return False
689 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800690
691
Vic Yang59cac9c2012-05-21 15:28:42 +0800692 def ec_act_copy_checker(self, expected_copy):
693 """Check the EC running firmware copy matches.
694
695 Args:
696 expected_copy: A string containing 'RO', 'A', or 'B' indicating
697 the expected copy of EC running firmware.
698
699 Returns:
700 True if the current EC running copy matches; otherwise, False.
701 """
702 lines = self.faft_client.run_shell_command_get_output('ectool version')
703 pattern = re.compile("Firmware copy: (.*)")
704 for line in lines:
705 matched = pattern.match(line)
706 if matched and matched.group(1) == expected_copy:
707 return True
708 return False
709
710
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800711 def check_root_part_on_non_recovery(self, part):
712 """Check the partition number of root device and on normal/dev boot.
713
714 Returns:
715 True if the root device matched and on normal/dev boot;
716 otherwise, False.
717 """
718 return self.root_part_checker(part) and \
719 self.crossystem_checker({
720 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800721 })
722
723
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800724 def _join_part(self, dev, part):
725 """Return a concatenated string of device and partition number.
726
727 Args:
728 dev: A string of device, e.g.'/dev/sda'.
729 part: A string of partition number, e.g.'3'.
730
731 Returns:
732 A concatenated string of device and partition number, e.g.'/dev/sda3'.
733
734 >>> seq = FAFTSequence()
735 >>> seq._join_part('/dev/sda', '3')
736 '/dev/sda3'
737 >>> seq._join_part('/dev/mmcblk0', '2')
738 '/dev/mmcblk0p2'
739 """
740 if 'mmcblk' in dev:
741 return dev + 'p' + part
742 else:
743 return dev + part
744
745
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800746 def copy_kernel_and_rootfs(self, from_part, to_part):
747 """Copy kernel and rootfs from from_part to to_part.
748
749 Args:
750 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800751 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800752 """
753 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800754 logging.info('Copying kernel from %s to %s. Please wait...' %
755 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800756 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800757 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
758 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
759 logging.info('Copying rootfs from %s to %s. Please wait...' %
760 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800761 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800762 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
763 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800764
765
766 def ensure_kernel_boot(self, part):
767 """Ensure the request kernel boot.
768
769 If not, it duplicates the current kernel to the requested kernel
770 and sets the requested higher priority to ensure it boot.
771
772 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800773 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800774 """
775 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800776 if self.faft_client.diff_kernel_a_b():
777 self.copy_kernel_and_rootfs(
778 from_part=self.OTHER_KERNEL_MAP[part],
779 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800780 self.run_faft_step({
781 'userspace_action': (self.reset_and_prioritize_kernel, part),
782 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800783
784
Vic Yang416f2032012-08-28 10:18:03 +0800785 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800786 """Set hardware write protect pin.
787
788 Args:
789 enable: True if asserting write protect pin. Otherwise, False.
790 """
791 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
792 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800793 self.servo.set('fw_wp', 'on' if enabled else 'off')
794
795
796 def set_EC_write_protect_and_reboot(self, enabled):
797 """Set EC write protect status and reboot to take effect.
798
799 EC write protect is only activated if both hardware write protect pin
800 is asserted and software write protect flag is set. Also, a reboot is
801 required for write protect to take effect.
802
803 Since the software write protect flag cannot be unset if hardware write
804 protect pin is asserted, we need to deasserted the pin first if we are
805 deactivating write protect. Similarly, a reboot is required before we
806 can modify the software flag.
807
808 This method asserts/deasserts hardware write protect pin first, and
809 set corresponding EC software write protect flag.
810
811 Args:
812 enable: True if activating EC write protect. Otherwise, False.
813 """
814 self.set_hardware_write_protect(enabled)
815 if enabled:
816 # Set write protect flag and reboot to take effect.
817 self.send_uart_command("flashwp enable")
818 self.sync_and_ec_reboot()
819 else:
820 # Reboot after deasserting hardware write protect pin to deactivate
821 # write protect. And then remove software write protect flag.
822 self.sync_and_ec_reboot()
823 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800824
825
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800826 def send_ctrl_d_to_dut(self):
827 """Send Ctrl-D key to DUT."""
828 if self._customized_ctrl_d_key_command:
829 logging.info('running the customized Ctrl-D key command')
830 os.system(self._customized_ctrl_d_key_command)
831 else:
832 self.servo.ctrl_d()
833
834
835 def send_enter_to_dut(self):
836 """Send Enter key to DUT."""
837 if self._customized_enter_key_command:
838 logging.info('running the customized Enter key command')
839 os.system(self._customized_enter_key_command)
840 else:
841 self.servo.enter_key()
842
843
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800844 def send_space_to_dut(self):
845 """Send Space key to DUT."""
846 if self._customized_space_key_command:
847 logging.info('running the customized Space key command')
848 os.system(self._customized_space_key_command)
849 else:
850 # Send the alternative key combinaton of space key to servo.
851 self.servo.ctrl_refresh_key()
852
853
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800854 def wait_fw_screen_and_ctrl_d(self):
855 """Wait for firmware warning screen and press Ctrl-D."""
856 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800857 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800858
859
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800860 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
861 """Wait for firmware warning screen and trigger recovery boot."""
862 time.sleep(self.FIRMWARE_SCREEN_DELAY)
863 self.send_enter_to_dut()
864
865 # For Alex/ZGB, there is a dev warning screen in text mode.
866 # Skip it by pressing Ctrl-D.
867 if need_dev_transition:
868 time.sleep(self.TEXT_SCREEN_DELAY)
869 self.send_ctrl_d_to_dut()
870
871
Mike Truty49153d82012-08-21 22:27:30 -0500872 def wait_fw_screen_and_unplug_usb(self):
873 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800874 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800875 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
876 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500877
878
879 def wait_fw_screen_and_plug_usb(self):
880 """Wait for firmware warning screen and then unplug and plug the USB."""
881 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800882 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
883
884
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800885 def wait_fw_screen_and_press_power(self):
886 """Wait for firmware warning screen and press power button."""
887 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800888 # While the firmware screen, the power button probing loop sleeps
889 # 0.25 second on every scan. Use the normal delay (1.2 second) for
890 # power press.
891 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800892
893
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800894 def wait_longer_fw_screen_and_press_power(self):
895 """Wait for firmware screen without timeout and press power button."""
896 time.sleep(self.DEV_SCREEN_TIMEOUT)
897 self.wait_fw_screen_and_press_power()
898
899
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800900 def wait_fw_screen_and_close_lid(self):
901 """Wait for firmware warning screen and close lid."""
902 time.sleep(self.FIRMWARE_SCREEN_DELAY)
903 self.servo.lid_close()
904
905
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800906 def wait_longer_fw_screen_and_close_lid(self):
907 """Wait for firmware screen without timeout and close lid."""
908 time.sleep(self.FIRMWARE_SCREEN_DELAY)
909 self.wait_fw_screen_and_close_lid()
910
911
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800912 def setup_tried_fwb(self, tried_fwb):
913 """Setup for fw B tried state.
914
915 It makes sure the system in the requested fw B tried state. If not, it
916 tries to do so.
917
918 Args:
919 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
920 """
921 if tried_fwb:
922 if not self.crossystem_checker({'tried_fwb': '1'}):
923 logging.info(
924 'Firmware is not booted with tried_fwb. Reboot into it.')
925 self.run_faft_step({
926 'userspace_action': self.faft_client.set_try_fw_b,
927 })
928 else:
929 if not self.crossystem_checker({'tried_fwb': '0'}):
930 logging.info(
931 'Firmware is booted with tried_fwb. Reboot to clear.')
932 self.run_faft_step({})
933
934
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800935 def enable_rec_mode_and_reboot(self):
936 """Switch to rec mode and reboot.
937
938 This method emulates the behavior of the old physical recovery switch,
939 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
940 recovery mode, i.e. just press Power + Esc + Refresh.
941 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800942 if self._customized_rec_reboot_command:
943 logging.info('running the customized rec reboot command')
944 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800945 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800946 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800947 self.servo.set('cold_reset', 'on')
948 time.sleep(self.COLD_RESET_DELAY)
949 self.servo.set('cold_reset', 'off')
950 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +0800951 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800952 time.sleep(self.EC_BOOT_DELAY)
953 self.send_uart_command("hostevent set 0x4000")
954 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800955 else:
956 self.servo.enable_recovery_mode()
957 self.cold_reboot()
958 time.sleep(self.EC_REBOOT_DELAY)
959 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800960
961
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800962 def enable_dev_mode_and_reboot(self):
963 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800964 if self.client_attr.keyboard_dev:
965 self.enable_keyboard_dev_mode()
966 else:
967 self.servo.enable_development_mode()
968 self.faft_client.run_shell_command(
969 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800970
971
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800972 def enable_normal_mode_and_reboot(self):
973 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800974 if self.client_attr.keyboard_dev:
975 self.disable_keyboard_dev_mode()
976 else:
977 self.servo.disable_development_mode()
978 self.faft_client.run_shell_command(
979 'chromeos-firmwareupdate --mode tonormal && reboot')
980
981
982 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
983 """Wait for firmware screen and then switch into or out of dev mode.
984
985 Args:
986 dev: True if switching into dev mode. Otherwise, False.
987 """
988 time.sleep(self.FIRMWARE_SCREEN_DELAY)
989 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800990 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800991 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800992 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800993 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800994 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800995
996
997 def enable_keyboard_dev_mode(self):
998 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800999 # Plug out USB disk for preventing recovery boot without warning
1000 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001001 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001002 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001003 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001004 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001005
1006
1007 def disable_keyboard_dev_mode(self):
1008 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001009 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001010 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001011 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001012 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001013 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001014
1015
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001016 def setup_dev_mode(self, dev_mode):
1017 """Setup for development mode.
1018
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001019 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001020 tries to do so.
1021
1022 Args:
1023 dev_mode: True if requested in dev mode; False if normal mode.
1024 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001025 # Change the default firmware_action for dev mode passing the fw screen.
1026 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001027 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1028 else None),
1029 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001030 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001031 if (not self.client_attr.keyboard_dev and
1032 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001033 logging.info('Dev switch is not on. Now switch it on.')
1034 self.servo.enable_development_mode()
1035 if not self.crossystem_checker({'devsw_boot': '1',
1036 'mainfw_type': 'developer'}):
1037 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001038 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001039 'userspace_action': None if self.client_attr.keyboard_dev
1040 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001041 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001042 'reboot_action': self.enable_keyboard_dev_mode if
1043 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001044 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001045 else:
Vic Yange7553162012-06-20 16:20:47 +08001046 if (not self.client_attr.keyboard_dev and
1047 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001048 logging.info('Dev switch is not off. Now switch it off.')
1049 self.servo.disable_development_mode()
1050 if not self.crossystem_checker({'devsw_boot': '0',
1051 'mainfw_type': 'normal'}):
1052 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001053 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001054 'userspace_action': None if self.client_attr.keyboard_dev
1055 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001056 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001057 'reboot_action': self.disable_keyboard_dev_mode if
1058 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001059 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001060
1061
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001062 def setup_kernel(self, part):
1063 """Setup for kernel test.
1064
1065 It makes sure both kernel A and B bootable and the current boot is
1066 the requested kernel part.
1067
1068 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001069 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001070 """
1071 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001072 if self.faft_client.diff_kernel_a_b():
1073 self.copy_kernel_and_rootfs(from_part=part,
1074 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001075 self.reset_and_prioritize_kernel(part)
1076
1077
1078 def reset_and_prioritize_kernel(self, part):
1079 """Make the requested partition highest priority.
1080
1081 This function also reset kerenl A and B to bootable.
1082
1083 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001084 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001085 """
1086 root_dev = self.faft_client.get_root_dev()
1087 # Reset kernel A and B to bootable.
1088 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1089 (self.KERNEL_MAP['a'], root_dev))
1090 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1091 (self.KERNEL_MAP['b'], root_dev))
1092 # Set kernel part highest priority.
1093 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1094 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001095 # Safer to sync and wait until the cgpt status written to the disk.
1096 self.faft_client.run_shell_command('sync')
1097 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001098
1099
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001100 def warm_reboot(self):
1101 """Request a warm reboot.
1102
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001103 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001104 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001105 # Use cold reset if the warm reset is broken.
1106 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001107 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1108 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001109 else:
1110 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001111
1112
1113 def cold_reboot(self):
1114 """Request a cold reboot.
1115
1116 A wrapper for underlying servo cold reset.
1117 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001118 if self.client_attr.platform == 'Parrot':
1119 self.servo.set('pwr_button', 'press')
1120 self.servo.set('cold_reset', 'on')
1121 self.servo.set('cold_reset', 'off')
1122 time.sleep(self.POWER_BTN_DELAY)
1123 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001124 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001125 # We don't use servo.cold_reset() here because software sync is
1126 # not yet finished, and device may or may not come up after cold
1127 # reset. Pressing power button before firmware comes up solves this.
1128 #
1129 # The correct behavior should be (not work now):
1130 # - If rebooting EC with rec mode on, power on AP and it boots
1131 # into recovery mode.
1132 # - If rebooting EC with rec mode off, power on AP for software
1133 # sync. Then AP checks if lid open or not. If lid open, continue;
1134 # otherwise, shut AP down and need servo for a power button
1135 # press.
1136 self.servo.set('cold_reset', 'on')
1137 self.servo.set('cold_reset', 'off')
1138 time.sleep(self.POWER_BTN_DELAY)
1139 self.servo.power_short_press()
1140 else:
1141 self.servo.cold_reset()
1142
1143
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001144 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001145 """Request the client sync and do a warm reboot.
1146
1147 This is the default reboot action on FAFT.
1148 """
1149 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001150 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001151 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001152
1153
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001154 def sync_and_cold_reboot(self):
1155 """Request the client sync and do a cold reboot.
1156
1157 This reboot action is used to reset EC for recovery mode.
1158 """
1159 self.faft_client.run_shell_command('sync')
1160 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001161 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001162
1163
Vic Yangaeb10392012-08-28 09:25:09 +08001164 def sync_and_ec_reboot(self, args=''):
1165 """Request the client sync and do a EC triggered reboot.
1166
1167 Args:
1168 args: Arguments passed to "ectool reboot_ec". Including:
1169 RO: jump to EC RO firmware.
1170 RW: jump to EC RW firmware.
1171 cold: Cold/hard reboot.
1172 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001173 self.faft_client.run_shell_command('sync')
1174 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001175 # Since EC reboot happens immediately, delay before actual reboot to
1176 # allow FAFT client returning.
1177 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1178 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001179 time.sleep(self.EC_REBOOT_DELAY)
1180 self.check_lid_and_power_on()
1181
1182
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001183 def full_power_off_and_on(self):
1184 """Shutdown the device by pressing power button and power on again."""
1185 # Press power button to trigger Chrome OS normal shutdown process.
1186 self.servo.power_normal_press()
1187 time.sleep(self.FULL_POWER_OFF_DELAY)
1188 # Short press power button to boot DUT again.
1189 self.servo.power_short_press()
1190
1191
Vic Yangf86728a2012-07-30 10:44:07 +08001192 def check_lid_and_power_on(self):
1193 """
1194 On devices with EC software sync, system powers on after EC reboots if
1195 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1196 This method checks lid switch state and presses power button if
1197 necessary.
1198 """
1199 if self.servo.get("lid_open") == "no":
1200 time.sleep(self.SOFTWARE_SYNC_DELAY)
1201 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001202
1203
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001204 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1205 """Modify the kernel header magic in USB stick.
1206
1207 The kernel header magic is the first 8-byte of kernel partition.
1208 We modify it to make it fail on kernel verification check.
1209
1210 Args:
1211 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1212 from_magic: A string of magic which we change it from.
1213 to_magic: A string of magic which we change it to.
1214
1215 Raises:
1216 error.TestError: if failed to change magic.
1217 """
1218 assert len(from_magic) == 8
1219 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001220 # USB image only contains one kernel.
1221 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001222 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1223 current_magic = utils.system_output(read_cmd)
1224 if current_magic == to_magic:
1225 logging.info("The kernel magic is already %s." % current_magic)
1226 return
1227 if current_magic != from_magic:
1228 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1229
1230 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1231 (from_magic, to_magic))
1232 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1233 " 2>/dev/null" % (to_magic, kernel_part))
1234 utils.system(write_cmd)
1235
1236 if utils.system_output(read_cmd) != to_magic:
1237 raise error.TestError("Failed to write new magic.")
1238
1239
1240 def corrupt_usb_kernel(self, usb_dev):
1241 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1242
1243 Args:
1244 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1245 """
1246 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1247 self.CORRUPTED_MAGIC)
1248
1249
1250 def restore_usb_kernel(self, usb_dev):
1251 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1252
1253 Args:
1254 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1255 """
1256 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1257 self.CHROMEOS_MAGIC)
1258
1259
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001260 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001261 """Call the action function with/without arguments.
1262
1263 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001264 action_tuple: A function, or a tuple (function, args, error_msg),
1265 in which, args and error_msg are optional. args is
1266 either a value or a tuple if multiple arguments.
1267 check_status: Check the return value of action function. If not
1268 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001269
1270 Returns:
1271 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001272
1273 Raises:
1274 error.TestError: An error when the action function is not callable.
1275 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001276 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001277 action = action_tuple
1278 args = ()
1279 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001280 if isinstance(action_tuple, tuple):
1281 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001282 if len(action_tuple) >= 2:
1283 args = action_tuple[1]
1284 if not isinstance(args, tuple):
1285 args = (args,)
1286 if len(action_tuple) >= 3:
1287 error_msg = action
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001288
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001289 if action is None:
1290 return
1291
1292 if not callable(action):
1293 raise error.TestError('action is not callable!')
1294
1295 info_msg = 'calling %s' % str(action)
1296 if args:
1297 info_msg += ' with args %s' % str(args)
1298 logging.info(info_msg)
1299 ret = action(*args)
1300
1301 if check_status and not ret:
1302 raise error.TestFail('%s: %s returning %s' %
1303 (error_msg, info_msg, str(ret)))
1304 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001305
1306
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001307 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1308 post_power_action=None):
1309 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1310
1311 Args:
1312 shutdown_action: a function which makes DUT shutdown, like pressing
1313 power key.
1314 pre_power_action: a function which is called before next power on.
1315 post_power_action: a function which is called after next power on.
1316
1317 Raises:
1318 error.TestFail: if the shutdown_action() failed to turn DUT off.
1319 """
1320 self._call_action(shutdown_action)
1321 logging.info('Wait to ensure DUT shut down...')
1322 try:
1323 self.wait_for_client()
1324 raise error.TestFail(
1325 'Should shut the device down after calling %s.' %
1326 str(shutdown_action))
1327 except AssertionError:
1328 logging.info(
1329 'DUT is surely shutdown. We are going to power it on again...')
1330
1331 if pre_power_action:
1332 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001333 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001334 if post_power_action:
1335 self._call_action(post_power_action)
1336
1337
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001338 def register_faft_template(self, template):
1339 """Register FAFT template, the default FAFT_STEP of each step.
1340
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001341 Any missing field falls back to the original faft_template.
1342
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001343 Args:
1344 template: A FAFT_STEP dict.
1345 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001346 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001347
1348
1349 def register_faft_sequence(self, sequence):
1350 """Register FAFT sequence.
1351
1352 Args:
1353 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1354 """
1355 self._faft_sequence = sequence
1356
1357
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001358 def run_faft_step(self, step, no_reboot=False):
1359 """Run a single FAFT step.
1360
1361 Any missing field falls back to faft_template. An empty step means
1362 running the default faft_template.
1363
1364 Args:
1365 step: A FAFT_STEP dict.
1366 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001367
1368 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001369 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001370 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001371 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1372 'firmware_action', 'install_deps_after_boot')
1373
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001374 test = {}
1375 test.update(self._faft_template)
1376 test.update(step)
1377
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001378 for key in test:
1379 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001380 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001381
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001382 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001383 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001384
1385 self._call_action(test['userspace_action'])
1386
1387 # Don't run reboot_action and firmware_action if no_reboot is True.
1388 if not no_reboot:
1389 self._call_action(test['reboot_action'])
1390 self.wait_for_client_offline()
1391 self._call_action(test['firmware_action'])
1392
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001393 try:
1394 if 'install_deps_after_boot' in test:
1395 self.wait_for_client(
1396 install_deps=test['install_deps_after_boot'])
1397 else:
1398 self.wait_for_client()
1399 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001400 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001401 self.reset_client()
1402 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001403
1404
1405 def run_faft_sequence(self):
1406 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001407 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001408 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001409 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001410 logging.info('======== Running FAFT sequence step %d ========' %
1411 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001412 # Don't reboot in the last step.
1413 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001414 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001415
1416
ctchang38ae4922012-09-03 17:01:16 +08001417 def get_current_firmware_sha(self):
1418 """Get current firmware sha of body and vblock.
1419
1420 Returns:
1421 Current firmware sha follows the order (
1422 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1423 """
1424 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1425 self.faft_client.get_firmware_sha('a'),
1426 self.faft_client.get_firmware_sig_sha('b'),
1427 self.faft_client.get_firmware_sha('b'))
1428 return current_firmware_sha
1429
1430
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001431 def is_firmware_changed(self):
1432 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001433
1434 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001435 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001436 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001437 # Device may not be rebooted after test.
1438 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001439
1440 current_sha = self.get_current_firmware_sha()
1441
1442 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001443 return False
ctchang38ae4922012-09-03 17:01:16 +08001444 else:
ctchang38ae4922012-09-03 17:01:16 +08001445 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1446 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1447 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1448 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001449 logging.info("Firmware changed:")
1450 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1451 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1452 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1453 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1454 return True
ctchang38ae4922012-09-03 17:01:16 +08001455
1456
1457 def backup_firmware(self, suffix='.original'):
1458 """Backup firmware to file, and then send it to host.
1459
1460 Args:
1461 suffix: a string appended to backup file name
1462 """
1463 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001464 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1465 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1466 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001467
1468 self._backup_firmware_sha = self.get_current_firmware_sha()
1469 logging.info('Backup firmware stored in %s with suffix %s' % (
1470 self.resultsdir, suffix))
1471
1472
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001473 def is_firmware_saved(self):
1474 """Check if a firmware saved (called backup_firmware before).
1475
1476 Returns:
1477 True if the firmware is backuped; otherwise False.
1478 """
1479 return self._backup_firmware_sha != ()
1480
1481
ctchang38ae4922012-09-03 17:01:16 +08001482 def restore_firmware(self, suffix='.original'):
1483 """Restore firmware from host in resultsdir.
1484
1485 Args:
1486 suffix: a string appended to backup file name
1487 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001488 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001489 return
1490
1491 # Backup current corrupted firmware.
1492 self.backup_firmware(suffix='.corrupt')
1493
1494 # Restore firmware.
1495 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001496 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1497 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001498
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001499 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001500 self.sync_and_warm_reboot()
1501 self.wait_for_client_offline()
1502 self.wait_for_client()
1503
ctchang38ae4922012-09-03 17:01:16 +08001504 logging.info('Successfully restore firmware.')