blob: 84a4ab89bdd9b35e61aafde27583985cf9219857 [file] [log] [blame]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +08005import ctypes
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08006import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08007import os
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08008import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +08009import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080010import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080011import time
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080012
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080013from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080014from autotest_lib.client.common_lib import error
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +080015from autotest_lib.server.cros import vboot_constants as vboot
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +080016from autotest_lib.server.cros.chrome_ec import ChromeEC
Vic Yangebd6de62012-06-26 14:25:57 +080017from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080018from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080019from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080020
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080021dirname = os.path.dirname(sys.modules[__name__].__file__)
22autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
23cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080024
25class FAFTSequence(ServoTest):
26 """
27 The base class of Fully Automated Firmware Test Sequence.
28
29 Many firmware tests require several reboot cycles and verify the resulted
30 system states. To do that, an Autotest test case should detailly handle
31 every action on each step. It makes the test case hard to read and many
32 duplicated code. The base class FAFTSequence is to solve this problem.
33
34 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
35 There are four functions in the FAFT_STEP dict:
36 state_checker: a function to check the current is valid or not,
37 returning True if valid, otherwise, False to break the whole
38 test sequence.
39 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080040 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080041 firmware_action: a function to describe the action ran after reboot.
42
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080043 And configurations:
44 install_deps_after_boot: if True, install the Autotest dependency after
45 boot; otherwise, do nothing. It is for the cases of recovery mode
46 test. The test boots a USB/SD image instead of an internal image.
47 The previous installed Autotest dependency on the internal image
48 is lost. So need to install it again.
49
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080050 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080051 userspace_action and firmware_action. Its reboot_action is a hardware
52 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080053 self.register_faft_template(FAFT_STEP).
54
55 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
56 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
57 fall back to default.
58
59 In the run_once(), it should register and run FAFT_SEQUENCE like:
60 def run_once(self):
61 self.register_faft_sequence(FAFT_SEQUENCE)
62 self.run_faft_sequnce()
63
64 Note that in the last step, we only run state_checker. The
65 userspace_action, reboot_action, and firmware_action are not executed.
66
67 Attributes:
68 _faft_template: The default FAFT_STEP of each step. The actions would
69 be over-written if the registered FAFT_SEQUENCE is valid.
70 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080071 _customized_ctrl_d_key_command: The customized Ctrl-D key command
72 instead of sending key via servo board.
73 _customized_enter_key_command: The customized Enter key command instead
74 of sending key via servo board.
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +080075 _customized_space_key_command: The customized Space key command instead
76 of sending key via servo board.
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +080077 _customized_rec_reboot_command: The customized recovery reboot command
78 instead of sending key combination of Power + Esc + F3 for
79 triggering recovery reboot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080080 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080081 _firmware_update: Boolean. True if firmware update needed after
82 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080083 """
84 version = 1
85
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080086
87 # Mapping of partition number of kernel and rootfs.
88 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
89 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
90 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
91 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
92
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080093 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080094 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080096 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080097 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080098 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080099 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +0800100 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800101 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800102 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +0800103 # Delay for waiting client to return before EC reboot
104 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800105 # Delay for waiting client to full power off
106 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800107 # Delay between EC reboot and pressing power button
108 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800109 # Delay of EC software sync hash calculating time
110 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800111 # Delay between EC boot and ChromeEC console functional
112 EC_BOOT_DELAY = 0.5
113 # Duration of holding cold_reset to reset device
114 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800115
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800116 # The developer screen timeouts fit our spec.
117 DEV_SCREEN_TIMEOUT = 30
118
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800119 CHROMEOS_MAGIC = "CHROMEOS"
120 CORRUPTED_MAGIC = "CORRUPTD"
121
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800122 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800123 _faft_sequence = ()
124
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800125 _customized_ctrl_d_key_command = None
126 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800127 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800128 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800129 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800130 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800131
ctchang38ae4922012-09-03 17:01:16 +0800132 _backup_firmware_sha = ()
133
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800134
135 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
136 # Parse arguments from command line
137 args = {}
138 for arg in cmdline_args:
139 match = re.search("^(\w+)=(.+)", arg)
140 if match:
141 args[match.group(1)] = match.group(2)
142
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800143 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800144 if 'ctrl_d_cmd' in args:
145 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
146 logging.info('Customized Ctrl-D key command: %s' %
147 self._customized_ctrl_d_key_command)
148 if 'enter_cmd' in args:
149 self._customized_enter_key_command = args['enter_cmd']
150 logging.info('Customized Enter key command: %s' %
151 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800152 if 'space_cmd' in args:
153 self._customized_space_key_command = args['space_cmd']
154 logging.info('Customized Space key command: %s' %
155 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800156 if 'rec_reboot_cmd' in args:
157 self._customized_rec_reboot_command = args['rec_reboot_cmd']
158 logging.info('Customized recovery reboot command: %s' %
159 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800160 if 'image' in args:
161 self._install_image_path = args['image']
162 logging.info('Install Chrome OS test image path: %s' %
163 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800164 if 'firmware_update' in args and args['firmware_update'].lower() \
165 not in ('0', 'false', 'no'):
166 if self._install_image_path:
167 self._firmware_update = True
168 logging.info('Also update firmware after installing.')
169 else:
170 logging.warning('Firmware update will not not performed '
171 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800172
173 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
174 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800175 if use_faft:
176 self.client_attr = FAFTClientAttribute(
177 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800178
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800179 if self.client_attr.chrome_ec:
180 self.ec = ChromeEC(self.servo)
181
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700182 # Setting up key matrix mapping
183 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
184
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800185
186 def setup(self):
187 """Autotest setup function."""
188 super(FAFTSequence, self).setup()
189 if not self._remote_infos['faft']['used']:
190 raise error.TestError('The use_faft flag should be enabled.')
191 self.register_faft_template({
192 'state_checker': (None),
193 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800194 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800195 'firmware_action': (None)
196 })
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800197 self.clear_set_gbb_flags(vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
198 vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
199 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800200 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800201 self.install_test_image(self._install_image_path,
202 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800203
204
205 def cleanup(self):
206 """Autotest cleanup function."""
207 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800208 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800209 super(FAFTSequence, self).cleanup()
210
211
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800212 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800213 """Reset client, if necessary.
214
215 This method is called when the client is not responsive. It may be
216 caused by the following cases:
217 - network flaky (can be recovered by replugging the Ethernet);
218 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
219 - corrupted firmware;
220 - corrutped OS image.
221 """
222 # DUT works fine, done.
223 if self._ping_test(self._client.ip, timeout=5):
224 return
225
226 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
227 # first reset item.
228
229 # DUT may halt on a firmware screen. Try cold reboot.
230 logging.info('Try cold reboot...')
231 self.cold_reboot()
232 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800233 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800234 return
235 except AssertionError:
236 pass
237
238 # DUT may be broken by a corrupted firmware. Restore firmware.
239 # We assume the recovery boot still works fine. Since the recovery
240 # code is in RO region and all FAFT tests don't change the RO region
241 # except GBB.
242 if self.is_firmware_saved():
243 self.ensure_client_in_recovery()
244 logging.info('Try restore the original firmware...')
245 if self.is_firmware_changed():
246 try:
247 self.restore_firmware()
248 return
249 except AssertionError:
250 logging.info('Restoring firmware doesn\'t help.')
251
252 # DUT may be broken by a corrupted OS image. Restore OS image.
253 self.ensure_client_in_recovery()
254 logging.info('Try restore the OS image...')
255 self.faft_client.run_shell_command('chromeos-install --yes')
256 self.sync_and_warm_reboot()
257 self.wait_for_client_offline()
258 try:
259 self.wait_for_client(install_deps=True)
260 logging.info('Successfully restore OS image.')
261 return
262 except AssertionError:
263 logging.info('Restoring OS image doesn\'t help.')
264
265
266 def ensure_client_in_recovery(self):
267 """Ensure client in recovery boot; reboot into it if necessary.
268
269 Raises:
270 error.TestError: if failed to boot the USB image.
271 """
272 # DUT works fine and is already in recovery boot, done.
273 if self._ping_test(self._client.ip, timeout=5):
274 if self.crossystem_checker({'mainfw_type': 'recovery'}):
275 return
276
277 logging.info('Try boot into USB image...')
278 self.servo.enable_usb_hub(host=True)
279 self.enable_rec_mode_and_reboot()
280 self.wait_fw_screen_and_plug_usb()
281 try:
282 self.wait_for_client(install_deps=True)
283 except AssertionError:
284 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800285
286
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800287 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800288 """Assert an USB disk plugged-in on servo and a test image inside.
289
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800290 Args:
291 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
292 If None, it is detected automatically.
293
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800294 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800295 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800296 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800297 if usb_dev:
298 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
299 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700300 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800301 usb_dev = self.servo.probe_host_usb_dev()
302 if not usb_dev:
303 raise error.TestError(
304 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800305
306 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800307 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800308 code = utils.system(
309 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
310 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800311 utils.system('sudo umount %s' % tmp_dir)
312 os.removedirs(tmp_dir)
313 if code != 0:
314 raise error.TestError(
315 'The image in the USB disk should be a test image.')
316
317
Simran Basi741b5d42012-05-18 11:27:15 -0700318 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800319 """Install the test image specied by the path onto the USB and DUT disk.
320
321 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500322 recovery mode. Then runs 'chromeos-install' (and possible
323 chromeos-firmwareupdate') to install it to DUT disk.
324
325 Sample command line:
326
327 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
328 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
329 server/site_tests/firmware_XXXX/control
330
331 This test requires an automated recovery to occur while simulating
332 inserting and removing the usb key from the servo. To allow this the
333 following hardware setup is required:
334 1. servo2 board connected via servoflex.
335 2. USB key inserted in the servo2.
336 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
337 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800338
339 Args:
340 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800341 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800342 """
343 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
344 image_path)
345 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800346
Mike Truty49153d82012-08-21 22:27:30 -0500347 # Reuse the servo method that uses the servo USB key to install
348 # the test image.
349 self.servo.image_to_servo_usb(image_path)
350
351 # DUT is powered off while imaging servo USB.
352 # Now turn it on.
353 self.servo.power_short_press()
354 self.wait_for_client()
355 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
356
357 install_cmd = 'chromeos-install --yes'
358 if firmware_update:
359 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
360
361 self.register_faft_sequence((
362 { # Step 1, request recovery boot
363 'state_checker': (self.crossystem_checker, {
364 'mainfw_type': ('developer', 'normal'),
365 }),
366 'userspace_action': self.faft_client.request_recovery_boot,
367 'firmware_action': self.wait_fw_screen_and_plug_usb,
368 'install_deps_after_boot': True,
369 },
370 { # Step 2, expected recovery boot
371 'state_checker': (self.crossystem_checker, {
372 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800373 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500374 }),
375 'userspace_action': (self.faft_client.run_shell_command,
376 install_cmd),
377 'reboot_action': self.cold_reboot,
378 'install_deps_after_boot': True,
379 },
380 { # Step 3, expected normal or developer boot (not recovery)
381 'state_checker': (self.crossystem_checker, {
382 'mainfw_type': ('developer', 'normal')
383 }),
384 },
385 ))
386 self.run_faft_sequence()
387 # 'Unplug' any USB keys in the servo from the dut.
388 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800389
390
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800391 def clear_set_gbb_flags(self, clear_mask, set_mask):
392 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800393
394 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800395 clear_mask: A mask of flags to be cleared.
396 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800397 """
398 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800399 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
400
401 if (gbb_flags != new_flags):
402 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
403 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800404 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800405 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800406 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800407 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800408 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800409 self.run_faft_step({
410 'firmware_action': self.wait_fw_screen_and_ctrl_d,
411 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800412
413
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800414 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800415 """Check if current platform has required EC capabilities.
416
417 Args:
418 required_cap: A list containing required EC capabilities. Pass in
419 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800420 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800421
422 Returns:
423 True if requirements are met. Otherwise, False.
424 """
425 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800426 if not suppress_warning:
427 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800428 return False
429
430 for cap in required_cap:
431 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800432 if not suppress_warning:
433 logging.warn('Requires EC capability "%s" to run this '
434 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800435 return False
436
437 return True
438
439
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800440 def _parse_crossystem_output(self, lines):
441 """Parse the crossystem output into a dict.
442
443 Args:
444 lines: The list of crossystem output strings.
445
446 Returns:
447 A dict which contains the crossystem keys/values.
448
449 Raises:
450 error.TestError: If wrong format in crossystem output.
451
452 >>> seq = FAFTSequence()
453 >>> seq._parse_crossystem_output([ \
454 "arch = x86 # Platform architecture", \
455 "cros_debug = 1 # OS should allow debug", \
456 ])
457 {'cros_debug': '1', 'arch': 'x86'}
458 >>> seq._parse_crossystem_output([ \
459 "arch=x86", \
460 ])
461 Traceback (most recent call last):
462 ...
463 TestError: Failed to parse crossystem output: arch=x86
464 >>> seq._parse_crossystem_output([ \
465 "arch = x86 # Platform architecture", \
466 "arch = arm # Platform architecture", \
467 ])
468 Traceback (most recent call last):
469 ...
470 TestError: Duplicated crossystem key: arch
471 """
472 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
473 parsed_list = {}
474 for line in lines:
475 matched = re.match(pattern, line.strip())
476 if not matched:
477 raise error.TestError("Failed to parse crossystem output: %s"
478 % line)
479 (name, value) = (matched.group(1), matched.group(2))
480 if name in parsed_list:
481 raise error.TestError("Duplicated crossystem key: %s" % name)
482 parsed_list[name] = value
483 return parsed_list
484
485
486 def crossystem_checker(self, expected_dict):
487 """Check the crossystem values matched.
488
489 Given an expect_dict which describes the expected crossystem values,
490 this function check the current crossystem values are matched or not.
491
492 Args:
493 expected_dict: A dict which contains the expected values.
494
495 Returns:
496 True if the crossystem value matched; otherwise, False.
497 """
498 lines = self.faft_client.run_shell_command_get_output('crossystem')
499 got_dict = self._parse_crossystem_output(lines)
500 for key in expected_dict:
501 if key not in got_dict:
502 logging.info('Expected key "%s" not in crossystem result' % key)
503 return False
504 if isinstance(expected_dict[key], str):
505 if got_dict[key] != expected_dict[key]:
506 logging.info("Expected '%s' value '%s' but got '%s'" %
507 (key, expected_dict[key], got_dict[key]))
508 return False
509 elif isinstance(expected_dict[key], tuple):
510 # Expected value is a tuple of possible actual values.
511 if got_dict[key] not in expected_dict[key]:
512 logging.info("Expected '%s' values %s but got '%s'" %
513 (key, str(expected_dict[key]), got_dict[key]))
514 return False
515 else:
516 logging.info("The expected_dict is neither a str nor a dict.")
517 return False
518 return True
519
520
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800521 def vdat_flags_checker(self, mask, value):
522 """Check the flags from VbSharedData matched.
523
524 This function checks the masked flags from VbSharedData using crossystem
525 are matched the given value.
526
527 Args:
528 mask: A bitmask of flags to be matched.
529 value: An expected value.
530
531 Returns:
532 True if the flags matched; otherwise, False.
533 """
534 lines = self.faft_client.run_shell_command_get_output(
535 'crossystem vdat_flags')
536 vdat_flags = int(lines[0], 16)
537 if vdat_flags & mask != value:
538 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
539 (value, mask, vdat_flags))
540 return False
541 return True
542
543
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800544 def ro_normal_checker(self, expected_fw=None, twostop=False):
545 """Check the current boot uses RO boot.
546
547 Args:
548 expected_fw: A string of expected firmware, 'A', 'B', or
549 None if don't care.
550 twostop: True to expect a TwoStop boot; False to expect a RO boot.
551
552 Returns:
553 True if the currect boot firmware matched and used RO boot;
554 otherwise, False.
555 """
556 crossystem_dict = {'tried_fwb': '0'}
557 if expected_fw:
558 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800559 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800560 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
561
562 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800563 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
564 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800565 self.crossystem_checker(crossystem_dict))
566
567
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800568 def root_part_checker(self, expected_part):
569 """Check the partition number of the root device matched.
570
571 Args:
572 expected_part: A string containing the number of the expected root
573 partition.
574
575 Returns:
576 True if the currect root partition number matched; otherwise, False.
577 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800578 part = self.faft_client.get_root_part()[-1]
579 if self.ROOTFS_MAP[expected_part] != part:
580 logging.info("Expected root part %s but got %s" %
581 (self.ROOTFS_MAP[expected_part], part))
582 return False
583 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800584
585
Vic Yang59cac9c2012-05-21 15:28:42 +0800586 def ec_act_copy_checker(self, expected_copy):
587 """Check the EC running firmware copy matches.
588
589 Args:
590 expected_copy: A string containing 'RO', 'A', or 'B' indicating
591 the expected copy of EC running firmware.
592
593 Returns:
594 True if the current EC running copy matches; otherwise, False.
595 """
596 lines = self.faft_client.run_shell_command_get_output('ectool version')
597 pattern = re.compile("Firmware copy: (.*)")
598 for line in lines:
599 matched = pattern.match(line)
600 if matched and matched.group(1) == expected_copy:
601 return True
602 return False
603
604
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800605 def check_root_part_on_non_recovery(self, part):
606 """Check the partition number of root device and on normal/dev boot.
607
608 Returns:
609 True if the root device matched and on normal/dev boot;
610 otherwise, False.
611 """
612 return self.root_part_checker(part) and \
613 self.crossystem_checker({
614 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800615 })
616
617
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800618 def _join_part(self, dev, part):
619 """Return a concatenated string of device and partition number.
620
621 Args:
622 dev: A string of device, e.g.'/dev/sda'.
623 part: A string of partition number, e.g.'3'.
624
625 Returns:
626 A concatenated string of device and partition number, e.g.'/dev/sda3'.
627
628 >>> seq = FAFTSequence()
629 >>> seq._join_part('/dev/sda', '3')
630 '/dev/sda3'
631 >>> seq._join_part('/dev/mmcblk0', '2')
632 '/dev/mmcblk0p2'
633 """
634 if 'mmcblk' in dev:
635 return dev + 'p' + part
636 else:
637 return dev + part
638
639
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800640 def copy_kernel_and_rootfs(self, from_part, to_part):
641 """Copy kernel and rootfs from from_part to to_part.
642
643 Args:
644 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800645 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800646 """
647 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800648 logging.info('Copying kernel from %s to %s. Please wait...' %
649 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800650 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800651 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
652 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
653 logging.info('Copying rootfs from %s to %s. Please wait...' %
654 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800655 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800656 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
657 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800658
659
660 def ensure_kernel_boot(self, part):
661 """Ensure the request kernel boot.
662
663 If not, it duplicates the current kernel to the requested kernel
664 and sets the requested higher priority to ensure it boot.
665
666 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800667 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800668 """
669 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800670 if self.faft_client.diff_kernel_a_b():
671 self.copy_kernel_and_rootfs(
672 from_part=self.OTHER_KERNEL_MAP[part],
673 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800674 self.run_faft_step({
675 'userspace_action': (self.reset_and_prioritize_kernel, part),
676 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800677
678
Vic Yang416f2032012-08-28 10:18:03 +0800679 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800680 """Set hardware write protect pin.
681
682 Args:
683 enable: True if asserting write protect pin. Otherwise, False.
684 """
685 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
686 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800687 self.servo.set('fw_wp', 'on' if enabled else 'off')
688
689
690 def set_EC_write_protect_and_reboot(self, enabled):
691 """Set EC write protect status and reboot to take effect.
692
693 EC write protect is only activated if both hardware write protect pin
694 is asserted and software write protect flag is set. Also, a reboot is
695 required for write protect to take effect.
696
697 Since the software write protect flag cannot be unset if hardware write
698 protect pin is asserted, we need to deasserted the pin first if we are
699 deactivating write protect. Similarly, a reboot is required before we
700 can modify the software flag.
701
702 This method asserts/deasserts hardware write protect pin first, and
703 set corresponding EC software write protect flag.
704
705 Args:
706 enable: True if activating EC write protect. Otherwise, False.
707 """
708 self.set_hardware_write_protect(enabled)
709 if enabled:
710 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800711 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800712 self.sync_and_ec_reboot()
713 else:
714 # Reboot after deasserting hardware write protect pin to deactivate
715 # write protect. And then remove software write protect flag.
716 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800717 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800718
719
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800720 def send_ctrl_d_to_dut(self):
721 """Send Ctrl-D key to DUT."""
722 if self._customized_ctrl_d_key_command:
723 logging.info('running the customized Ctrl-D key command')
724 os.system(self._customized_ctrl_d_key_command)
725 else:
726 self.servo.ctrl_d()
727
728
729 def send_enter_to_dut(self):
730 """Send Enter key to DUT."""
731 if self._customized_enter_key_command:
732 logging.info('running the customized Enter key command')
733 os.system(self._customized_enter_key_command)
734 else:
735 self.servo.enter_key()
736
737
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800738 def send_space_to_dut(self):
739 """Send Space key to DUT."""
740 if self._customized_space_key_command:
741 logging.info('running the customized Space key command')
742 os.system(self._customized_space_key_command)
743 else:
744 # Send the alternative key combinaton of space key to servo.
745 self.servo.ctrl_refresh_key()
746
747
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800748 def wait_fw_screen_and_ctrl_d(self):
749 """Wait for firmware warning screen and press Ctrl-D."""
750 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800751 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800752
753
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800754 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
755 """Wait for firmware warning screen and trigger recovery boot."""
756 time.sleep(self.FIRMWARE_SCREEN_DELAY)
757 self.send_enter_to_dut()
758
759 # For Alex/ZGB, there is a dev warning screen in text mode.
760 # Skip it by pressing Ctrl-D.
761 if need_dev_transition:
762 time.sleep(self.TEXT_SCREEN_DELAY)
763 self.send_ctrl_d_to_dut()
764
765
Mike Truty49153d82012-08-21 22:27:30 -0500766 def wait_fw_screen_and_unplug_usb(self):
767 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800768 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800769 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
770 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500771
772
773 def wait_fw_screen_and_plug_usb(self):
774 """Wait for firmware warning screen and then unplug and plug the USB."""
775 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800776 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
777
778
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800779 def wait_fw_screen_and_press_power(self):
780 """Wait for firmware warning screen and press power button."""
781 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800782 # While the firmware screen, the power button probing loop sleeps
783 # 0.25 second on every scan. Use the normal delay (1.2 second) for
784 # power press.
785 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800786
787
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800788 def wait_longer_fw_screen_and_press_power(self):
789 """Wait for firmware screen without timeout and press power button."""
790 time.sleep(self.DEV_SCREEN_TIMEOUT)
791 self.wait_fw_screen_and_press_power()
792
793
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800794 def wait_fw_screen_and_close_lid(self):
795 """Wait for firmware warning screen and close lid."""
796 time.sleep(self.FIRMWARE_SCREEN_DELAY)
797 self.servo.lid_close()
798
799
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800800 def wait_longer_fw_screen_and_close_lid(self):
801 """Wait for firmware screen without timeout and close lid."""
802 time.sleep(self.FIRMWARE_SCREEN_DELAY)
803 self.wait_fw_screen_and_close_lid()
804
805
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800806 def setup_tried_fwb(self, tried_fwb):
807 """Setup for fw B tried state.
808
809 It makes sure the system in the requested fw B tried state. If not, it
810 tries to do so.
811
812 Args:
813 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
814 """
815 if tried_fwb:
816 if not self.crossystem_checker({'tried_fwb': '1'}):
817 logging.info(
818 'Firmware is not booted with tried_fwb. Reboot into it.')
819 self.run_faft_step({
820 'userspace_action': self.faft_client.set_try_fw_b,
821 })
822 else:
823 if not self.crossystem_checker({'tried_fwb': '0'}):
824 logging.info(
825 'Firmware is booted with tried_fwb. Reboot to clear.')
826 self.run_faft_step({})
827
828
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800829 def enable_rec_mode_and_reboot(self):
830 """Switch to rec mode and reboot.
831
832 This method emulates the behavior of the old physical recovery switch,
833 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
834 recovery mode, i.e. just press Power + Esc + Refresh.
835 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800836 if self._customized_rec_reboot_command:
837 logging.info('running the customized rec reboot command')
838 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800839 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800840 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800841 self.servo.set('cold_reset', 'on')
842 time.sleep(self.COLD_RESET_DELAY)
843 self.servo.set('cold_reset', 'off')
844 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800845 self.ec.send_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800846 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800847 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +0800848 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800849 else:
850 self.servo.enable_recovery_mode()
851 self.cold_reboot()
852 time.sleep(self.EC_REBOOT_DELAY)
853 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800854
855
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800856 def enable_dev_mode_and_reboot(self):
857 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800858 if self.client_attr.keyboard_dev:
859 self.enable_keyboard_dev_mode()
860 else:
861 self.servo.enable_development_mode()
862 self.faft_client.run_shell_command(
863 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800864
865
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800866 def enable_normal_mode_and_reboot(self):
867 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800868 if self.client_attr.keyboard_dev:
869 self.disable_keyboard_dev_mode()
870 else:
871 self.servo.disable_development_mode()
872 self.faft_client.run_shell_command(
873 'chromeos-firmwareupdate --mode tonormal && reboot')
874
875
876 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
877 """Wait for firmware screen and then switch into or out of dev mode.
878
879 Args:
880 dev: True if switching into dev mode. Otherwise, False.
881 """
882 time.sleep(self.FIRMWARE_SCREEN_DELAY)
883 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800884 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800885 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800886 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800887 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800888 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800889
890
891 def enable_keyboard_dev_mode(self):
892 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800893 # Plug out USB disk for preventing recovery boot without warning
894 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800895 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800896 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800897 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800898 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800899
900
901 def disable_keyboard_dev_mode(self):
902 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800903 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800904 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800905 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800906 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800907 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800908
909
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800910 def setup_dev_mode(self, dev_mode):
911 """Setup for development mode.
912
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800913 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800914 tries to do so.
915
916 Args:
917 dev_mode: True if requested in dev mode; False if normal mode.
918 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800919 # Change the default firmware_action for dev mode passing the fw screen.
920 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800921 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
922 else None),
923 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800924 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800925 if (not self.client_attr.keyboard_dev and
926 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800927 logging.info('Dev switch is not on. Now switch it on.')
928 self.servo.enable_development_mode()
929 if not self.crossystem_checker({'devsw_boot': '1',
930 'mainfw_type': 'developer'}):
931 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800932 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800933 'userspace_action': None if self.client_attr.keyboard_dev
934 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800935 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800936 'reboot_action': self.enable_keyboard_dev_mode if
937 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800938 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800939 else:
Vic Yange7553162012-06-20 16:20:47 +0800940 if (not self.client_attr.keyboard_dev and
941 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800942 logging.info('Dev switch is not off. Now switch it off.')
943 self.servo.disable_development_mode()
944 if not self.crossystem_checker({'devsw_boot': '0',
945 'mainfw_type': 'normal'}):
946 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800947 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800948 'userspace_action': None if self.client_attr.keyboard_dev
949 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800950 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800951 'reboot_action': self.disable_keyboard_dev_mode if
952 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800953 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800954
955
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800956 def setup_kernel(self, part):
957 """Setup for kernel test.
958
959 It makes sure both kernel A and B bootable and the current boot is
960 the requested kernel part.
961
962 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800963 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800964 """
965 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800966 if self.faft_client.diff_kernel_a_b():
967 self.copy_kernel_and_rootfs(from_part=part,
968 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800969 self.reset_and_prioritize_kernel(part)
970
971
972 def reset_and_prioritize_kernel(self, part):
973 """Make the requested partition highest priority.
974
975 This function also reset kerenl A and B to bootable.
976
977 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800978 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800979 """
980 root_dev = self.faft_client.get_root_dev()
981 # Reset kernel A and B to bootable.
982 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
983 (self.KERNEL_MAP['a'], root_dev))
984 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
985 (self.KERNEL_MAP['b'], root_dev))
986 # Set kernel part highest priority.
987 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
988 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800989 # Safer to sync and wait until the cgpt status written to the disk.
990 self.faft_client.run_shell_command('sync')
991 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800992
993
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800994 def warm_reboot(self):
995 """Request a warm reboot.
996
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800997 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800998 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800999 # Use cold reset if the warm reset is broken.
1000 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001001 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1002 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001003 else:
1004 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001005
1006
1007 def cold_reboot(self):
1008 """Request a cold reboot.
1009
1010 A wrapper for underlying servo cold reset.
1011 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001012 if self.client_attr.platform == 'Parrot':
1013 self.servo.set('pwr_button', 'press')
1014 self.servo.set('cold_reset', 'on')
1015 self.servo.set('cold_reset', 'off')
1016 time.sleep(self.POWER_BTN_DELAY)
1017 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001018 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001019 # We don't use servo.cold_reset() here because software sync is
1020 # not yet finished, and device may or may not come up after cold
1021 # reset. Pressing power button before firmware comes up solves this.
1022 #
1023 # The correct behavior should be (not work now):
1024 # - If rebooting EC with rec mode on, power on AP and it boots
1025 # into recovery mode.
1026 # - If rebooting EC with rec mode off, power on AP for software
1027 # sync. Then AP checks if lid open or not. If lid open, continue;
1028 # otherwise, shut AP down and need servo for a power button
1029 # press.
1030 self.servo.set('cold_reset', 'on')
1031 self.servo.set('cold_reset', 'off')
1032 time.sleep(self.POWER_BTN_DELAY)
1033 self.servo.power_short_press()
1034 else:
1035 self.servo.cold_reset()
1036
1037
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001038 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001039 """Request the client sync and do a warm reboot.
1040
1041 This is the default reboot action on FAFT.
1042 """
1043 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001044 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001045 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001046
1047
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001048 def sync_and_cold_reboot(self):
1049 """Request the client sync and do a cold reboot.
1050
1051 This reboot action is used to reset EC for recovery mode.
1052 """
1053 self.faft_client.run_shell_command('sync')
1054 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001055 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001056
1057
Vic Yangaeb10392012-08-28 09:25:09 +08001058 def sync_and_ec_reboot(self, args=''):
1059 """Request the client sync and do a EC triggered reboot.
1060
1061 Args:
1062 args: Arguments passed to "ectool reboot_ec". Including:
1063 RO: jump to EC RO firmware.
1064 RW: jump to EC RW firmware.
1065 cold: Cold/hard reboot.
1066 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001067 self.faft_client.run_shell_command('sync')
1068 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001069 # Since EC reboot happens immediately, delay before actual reboot to
1070 # allow FAFT client returning.
1071 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1072 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001073 time.sleep(self.EC_REBOOT_DELAY)
1074 self.check_lid_and_power_on()
1075
1076
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001077 def full_power_off_and_on(self):
1078 """Shutdown the device by pressing power button and power on again."""
1079 # Press power button to trigger Chrome OS normal shutdown process.
1080 self.servo.power_normal_press()
1081 time.sleep(self.FULL_POWER_OFF_DELAY)
1082 # Short press power button to boot DUT again.
1083 self.servo.power_short_press()
1084
1085
Vic Yangf86728a2012-07-30 10:44:07 +08001086 def check_lid_and_power_on(self):
1087 """
1088 On devices with EC software sync, system powers on after EC reboots if
1089 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1090 This method checks lid switch state and presses power button if
1091 necessary.
1092 """
1093 if self.servo.get("lid_open") == "no":
1094 time.sleep(self.SOFTWARE_SYNC_DELAY)
1095 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001096
1097
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001098 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1099 """Modify the kernel header magic in USB stick.
1100
1101 The kernel header magic is the first 8-byte of kernel partition.
1102 We modify it to make it fail on kernel verification check.
1103
1104 Args:
1105 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1106 from_magic: A string of magic which we change it from.
1107 to_magic: A string of magic which we change it to.
1108
1109 Raises:
1110 error.TestError: if failed to change magic.
1111 """
1112 assert len(from_magic) == 8
1113 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001114 # USB image only contains one kernel.
1115 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001116 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1117 current_magic = utils.system_output(read_cmd)
1118 if current_magic == to_magic:
1119 logging.info("The kernel magic is already %s." % current_magic)
1120 return
1121 if current_magic != from_magic:
1122 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1123
1124 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1125 (from_magic, to_magic))
1126 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1127 " 2>/dev/null" % (to_magic, kernel_part))
1128 utils.system(write_cmd)
1129
1130 if utils.system_output(read_cmd) != to_magic:
1131 raise error.TestError("Failed to write new magic.")
1132
1133
1134 def corrupt_usb_kernel(self, usb_dev):
1135 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1136
1137 Args:
1138 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1139 """
1140 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1141 self.CORRUPTED_MAGIC)
1142
1143
1144 def restore_usb_kernel(self, usb_dev):
1145 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1146
1147 Args:
1148 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1149 """
1150 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1151 self.CHROMEOS_MAGIC)
1152
1153
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001154 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001155 """Call the action function with/without arguments.
1156
1157 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001158 action_tuple: A function, or a tuple (function, args, error_msg),
1159 in which, args and error_msg are optional. args is
1160 either a value or a tuple if multiple arguments.
1161 check_status: Check the return value of action function. If not
1162 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001163
1164 Returns:
1165 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001166
1167 Raises:
1168 error.TestError: An error when the action function is not callable.
1169 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001170 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001171 action = action_tuple
1172 args = ()
1173 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001174 if isinstance(action_tuple, tuple):
1175 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001176 if len(action_tuple) >= 2:
1177 args = action_tuple[1]
1178 if not isinstance(args, tuple):
1179 args = (args,)
1180 if len(action_tuple) >= 3:
1181 error_msg = action
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001182
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001183 if action is None:
1184 return
1185
1186 if not callable(action):
1187 raise error.TestError('action is not callable!')
1188
1189 info_msg = 'calling %s' % str(action)
1190 if args:
1191 info_msg += ' with args %s' % str(args)
1192 logging.info(info_msg)
1193 ret = action(*args)
1194
1195 if check_status and not ret:
1196 raise error.TestFail('%s: %s returning %s' %
1197 (error_msg, info_msg, str(ret)))
1198 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001199
1200
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001201 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1202 post_power_action=None):
1203 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1204
1205 Args:
1206 shutdown_action: a function which makes DUT shutdown, like pressing
1207 power key.
1208 pre_power_action: a function which is called before next power on.
1209 post_power_action: a function which is called after next power on.
1210
1211 Raises:
1212 error.TestFail: if the shutdown_action() failed to turn DUT off.
1213 """
1214 self._call_action(shutdown_action)
1215 logging.info('Wait to ensure DUT shut down...')
1216 try:
1217 self.wait_for_client()
1218 raise error.TestFail(
1219 'Should shut the device down after calling %s.' %
1220 str(shutdown_action))
1221 except AssertionError:
1222 logging.info(
1223 'DUT is surely shutdown. We are going to power it on again...')
1224
1225 if pre_power_action:
1226 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001227 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001228 if post_power_action:
1229 self._call_action(post_power_action)
1230
1231
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001232 def register_faft_template(self, template):
1233 """Register FAFT template, the default FAFT_STEP of each step.
1234
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001235 Any missing field falls back to the original faft_template.
1236
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001237 Args:
1238 template: A FAFT_STEP dict.
1239 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001240 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001241
1242
1243 def register_faft_sequence(self, sequence):
1244 """Register FAFT sequence.
1245
1246 Args:
1247 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1248 """
1249 self._faft_sequence = sequence
1250
1251
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001252 def run_faft_step(self, step, no_reboot=False):
1253 """Run a single FAFT step.
1254
1255 Any missing field falls back to faft_template. An empty step means
1256 running the default faft_template.
1257
1258 Args:
1259 step: A FAFT_STEP dict.
1260 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001261
1262 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001263 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001264 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001265 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1266 'firmware_action', 'install_deps_after_boot')
1267
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001268 test = {}
1269 test.update(self._faft_template)
1270 test.update(step)
1271
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001272 for key in test:
1273 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001274 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001275
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001276 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001277 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001278
1279 self._call_action(test['userspace_action'])
1280
1281 # Don't run reboot_action and firmware_action if no_reboot is True.
1282 if not no_reboot:
1283 self._call_action(test['reboot_action'])
1284 self.wait_for_client_offline()
1285 self._call_action(test['firmware_action'])
1286
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001287 try:
1288 if 'install_deps_after_boot' in test:
1289 self.wait_for_client(
1290 install_deps=test['install_deps_after_boot'])
1291 else:
1292 self.wait_for_client()
1293 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001294 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001295 self.reset_client()
1296 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001297
1298
1299 def run_faft_sequence(self):
1300 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001301 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001302 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001303 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001304 logging.info('======== Running FAFT sequence step %d ========' %
1305 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001306 # Don't reboot in the last step.
1307 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001308 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001309
1310
ctchang38ae4922012-09-03 17:01:16 +08001311 def get_current_firmware_sha(self):
1312 """Get current firmware sha of body and vblock.
1313
1314 Returns:
1315 Current firmware sha follows the order (
1316 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1317 """
1318 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1319 self.faft_client.get_firmware_sha('a'),
1320 self.faft_client.get_firmware_sig_sha('b'),
1321 self.faft_client.get_firmware_sha('b'))
1322 return current_firmware_sha
1323
1324
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001325 def is_firmware_changed(self):
1326 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001327
1328 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001329 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001330 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001331 # Device may not be rebooted after test.
1332 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001333
1334 current_sha = self.get_current_firmware_sha()
1335
1336 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001337 return False
ctchang38ae4922012-09-03 17:01:16 +08001338 else:
ctchang38ae4922012-09-03 17:01:16 +08001339 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1340 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1341 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1342 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001343 logging.info("Firmware changed:")
1344 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1345 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1346 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1347 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1348 return True
ctchang38ae4922012-09-03 17:01:16 +08001349
1350
1351 def backup_firmware(self, suffix='.original'):
1352 """Backup firmware to file, and then send it to host.
1353
1354 Args:
1355 suffix: a string appended to backup file name
1356 """
1357 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001358 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1359 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1360 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001361
1362 self._backup_firmware_sha = self.get_current_firmware_sha()
1363 logging.info('Backup firmware stored in %s with suffix %s' % (
1364 self.resultsdir, suffix))
1365
1366
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001367 def is_firmware_saved(self):
1368 """Check if a firmware saved (called backup_firmware before).
1369
1370 Returns:
1371 True if the firmware is backuped; otherwise False.
1372 """
1373 return self._backup_firmware_sha != ()
1374
1375
ctchang38ae4922012-09-03 17:01:16 +08001376 def restore_firmware(self, suffix='.original'):
1377 """Restore firmware from host in resultsdir.
1378
1379 Args:
1380 suffix: a string appended to backup file name
1381 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001382 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001383 return
1384
1385 # Backup current corrupted firmware.
1386 self.backup_firmware(suffix='.corrupt')
1387
1388 # Restore firmware.
1389 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001390 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1391 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001392
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001393 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001394 self.sync_and_warm_reboot()
1395 self.wait_for_client_offline()
1396 self.wait_for_client()
1397
ctchang38ae4922012-09-03 17:01:16 +08001398 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001399
1400
1401 def setup_firmwareupdate_shellball(self, shellball=None):
1402 """Deside a shellball to use in firmware update test.
1403
1404 Check if there is a given shellball, and it is a shell script. Then,
1405 send it to the remote host. Otherwise, use
1406 /usr/sbin/chromeos-firmwareupdate.
1407
1408 Args:
1409 shellball: path of a shellball or default to None.
1410
1411 Returns:
1412 Path of shellball in remote host.
1413 If use default shellball, reutrn None.
1414 """
1415 updater_path = None
1416 if shellball:
1417 # Determine the firmware file is a shellball or a raw binary.
1418 is_shellball = (utils.system_output("file %s" % shellball).find(
1419 "shell script") != -1)
1420 if is_shellball:
1421 logging.info('Device will update firmware with shellball %s'
1422 % shellball)
1423 temp_dir = self.faft_client.create_temp_dir('shellball_')
1424 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1425 self._client.send_file(shellball, temp_shellball)
1426 updater_path = temp_shellball
1427 else:
1428 raise error.TestFail(
1429 'The given shellball is not a shell script.')
1430 return updater_path