blob: fc96e347015f4005b0629cab0c41f810987c79f4 [file] [log] [blame]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +08005import ctypes
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08006import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08007import os
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08008import re
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +08009import subprocess
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080010import sys
Tom Wai-Hong 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 Tam08885ae2012-10-19 17:16:45 +080020from autotest_lib.site_utils.chromeos_test.common_util import ChromeOSTestError
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080021
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080022dirname = os.path.dirname(sys.modules[__name__].__file__)
23autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
24cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080025
26class FAFTSequence(ServoTest):
27 """
28 The base class of Fully Automated Firmware Test Sequence.
29
30 Many firmware tests require several reboot cycles and verify the resulted
31 system states. To do that, an Autotest test case should detailly handle
32 every action on each step. It makes the test case hard to read and many
33 duplicated code. The base class FAFTSequence is to solve this problem.
34
35 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
36 There are four functions in the FAFT_STEP dict:
37 state_checker: a function to check the current is valid or not,
38 returning True if valid, otherwise, False to break the whole
39 test sequence.
40 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080041 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080042 firmware_action: a function to describe the action ran after reboot.
43
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080044 And configurations:
45 install_deps_after_boot: if True, install the Autotest dependency after
46 boot; otherwise, do nothing. It is for the cases of recovery mode
47 test. The test boots a USB/SD image instead of an internal image.
48 The previous installed Autotest dependency on the internal image
49 is lost. So need to install it again.
50
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080051 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080052 userspace_action and firmware_action. Its reboot_action is a hardware
53 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080054 self.register_faft_template(FAFT_STEP).
55
56 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
57 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
58 fall back to default.
59
60 In the run_once(), it should register and run FAFT_SEQUENCE like:
61 def run_once(self):
62 self.register_faft_sequence(FAFT_SEQUENCE)
63 self.run_faft_sequnce()
64
65 Note that in the last step, we only run state_checker. The
66 userspace_action, reboot_action, and firmware_action are not executed.
67
68 Attributes:
69 _faft_template: The default FAFT_STEP of each step. The actions would
70 be over-written if the registered FAFT_SEQUENCE is valid.
71 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +080072 _customized_key_commands: The dict of the customized key commands,
73 including Ctrl-D, Ctrl-U, Enter, Space, and recovery reboot.
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +080074 _install_image_path: The URL or the path on the host to the Chrome OS
75 test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080076 _firmware_update: Boolean. True if firmware update needed after
77 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080078 """
79 version = 1
80
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080081 # Mapping of partition number of kernel and rootfs.
82 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
83 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
84 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
85 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
86
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080087 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080088 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080089 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080090 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +080091 # Delay for waiting beep done.
92 BEEP_DELAY = 1
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080093 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080094 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080095 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +080096 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080097 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +080098 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +080099 # Delay for waiting client to return before EC reboot
100 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800101 # Delay for waiting client to full power off
102 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800103 # Delay between EC reboot and pressing power button
104 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800105 # Delay of EC software sync hash calculating time
106 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800107 # Delay between EC boot and ChromeEC console functional
108 EC_BOOT_DELAY = 0.5
109 # Duration of holding cold_reset to reset device
110 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800111
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800112 # The developer screen timeouts fit our spec.
113 DEV_SCREEN_TIMEOUT = 30
114
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800115 CHROMEOS_MAGIC = "CHROMEOS"
116 CORRUPTED_MAGIC = "CORRUPTD"
117
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800118 _HTTP_PREFIX = 'http://'
119 _DEVSERVER_PORT = '8090'
120
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800121 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800122 _faft_sequence = ()
123
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800124 _customized_key_commands = {
125 'ctrl_d': None,
126 'ctrl_u': None,
127 'enter': None,
128 'rec_reboot': None,
129 'space': None,
130 }
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800131 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800132 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800133
ctchang38ae4922012-09-03 17:01:16 +0800134 _backup_firmware_sha = ()
135
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800136 # Class level variable, keep track the states of one time setup.
137 # This variable is preserved across tests which inherit this class.
138 _global_setup_done = {
139 'gbb_flags': False,
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800140 'reimage': False,
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800141 'usb_check': False,
142 }
Vic Yang54f70572012-10-19 17:05:26 +0800143
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800144 @classmethod
145 def check_setup_done(cls, label):
146 """Check if the given setup is done.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800147
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800148 Args:
149 label: The label of the setup.
150 """
151 return cls._global_setup_done[label]
152
153
154 @classmethod
155 def mark_setup_done(cls, label):
156 """Mark the given setup done.
157
158 Args:
159 label: The label of the setup.
160 """
161 cls._global_setup_done[label] = True
162
163
164 @classmethod
165 def unmark_setup_done(cls, label):
166 """Mark the given setup not done.
167
168 Args:
169 label: The label of the setup.
170 """
171 cls._global_setup_done[label] = False
Vic Yang54f70572012-10-19 17:05:26 +0800172
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800173
174 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
175 # Parse arguments from command line
176 args = {}
177 for arg in cmdline_args:
178 match = re.search("^(\w+)=(.+)", arg)
179 if match:
180 args[match.group(1)] = match.group(2)
181
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800182 # Keep the arguments which will be used later.
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800183 for key in self._customized_key_commands:
184 key_cmd = key + '_cmd'
185 if key_cmd in args:
186 self._customized_key_commands[key] = args[key_cmd]
187 logging.info('Customized %s key command: %s' %
188 (key, args[key_cmd]))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800189 if 'image' in args:
190 self._install_image_path = args['image']
191 logging.info('Install Chrome OS test image path: %s' %
192 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800193 if 'firmware_update' in args and args['firmware_update'].lower() \
194 not in ('0', 'false', 'no'):
195 if self._install_image_path:
196 self._firmware_update = True
197 logging.info('Also update firmware after installing.')
198 else:
199 logging.warning('Firmware update will not not performed '
200 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800201
202 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
203 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800204 if use_faft:
205 self.client_attr = FAFTClientAttribute(
206 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800207
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800208 if self.client_attr.chrome_ec:
209 self.ec = ChromeEC(self.servo)
210
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700211 # Setting up key matrix mapping
212 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
213
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800214
215 def setup(self):
216 """Autotest setup function."""
217 super(FAFTSequence, self).setup()
218 if not self._remote_infos['faft']['used']:
219 raise error.TestError('The use_faft flag should be enabled.')
220 self.register_faft_template({
221 'state_checker': (None),
222 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800223 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800224 'firmware_action': (None)
225 })
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800226 self.setup_gbb_flags()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800227 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800228 self.install_test_image(self._install_image_path,
229 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800230
231
232 def cleanup(self):
233 """Autotest cleanup function."""
234 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800235 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800236 super(FAFTSequence, self).cleanup()
237
238
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800239 def invalidate_firmware_setup(self):
240 """Invalidate all firmware related setup state.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800241
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800242 This method is called when the firmware is re-flashed. It resets all
243 firmware related setup states so that the next test setup properly
244 again.
Vic Yangdbaba8f2012-10-17 16:05:35 +0800245 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800246 self.unmark_setup_done('gbb_flags')
Vic Yangdbaba8f2012-10-17 16:05:35 +0800247
248
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800249 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800250 """Reset client, if necessary.
251
252 This method is called when the client is not responsive. It may be
253 caused by the following cases:
254 - network flaky (can be recovered by replugging the Ethernet);
255 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
256 - corrupted firmware;
257 - corrutped OS image.
258 """
259 # DUT works fine, done.
260 if self._ping_test(self._client.ip, timeout=5):
261 return
262
263 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
264 # first reset item.
265
266 # DUT may halt on a firmware screen. Try cold reboot.
267 logging.info('Try cold reboot...')
268 self.cold_reboot()
269 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800270 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800271 return
272 except AssertionError:
273 pass
274
275 # DUT may be broken by a corrupted firmware. Restore firmware.
276 # We assume the recovery boot still works fine. Since the recovery
277 # code is in RO region and all FAFT tests don't change the RO region
278 # except GBB.
279 if self.is_firmware_saved():
280 self.ensure_client_in_recovery()
281 logging.info('Try restore the original firmware...')
282 if self.is_firmware_changed():
283 try:
284 self.restore_firmware()
285 return
286 except AssertionError:
287 logging.info('Restoring firmware doesn\'t help.')
288
289 # DUT may be broken by a corrupted OS image. Restore OS image.
290 self.ensure_client_in_recovery()
291 logging.info('Try restore the OS image...')
292 self.faft_client.run_shell_command('chromeos-install --yes')
293 self.sync_and_warm_reboot()
294 self.wait_for_client_offline()
295 try:
296 self.wait_for_client(install_deps=True)
297 logging.info('Successfully restore OS image.')
298 return
299 except AssertionError:
300 logging.info('Restoring OS image doesn\'t help.')
301
302
303 def ensure_client_in_recovery(self):
304 """Ensure client in recovery boot; reboot into it if necessary.
305
306 Raises:
307 error.TestError: if failed to boot the USB image.
308 """
309 # DUT works fine and is already in recovery boot, done.
310 if self._ping_test(self._client.ip, timeout=5):
311 if self.crossystem_checker({'mainfw_type': 'recovery'}):
312 return
313
314 logging.info('Try boot into USB image...')
315 self.servo.enable_usb_hub(host=True)
316 self.enable_rec_mode_and_reboot()
317 self.wait_fw_screen_and_plug_usb()
318 try:
319 self.wait_for_client(install_deps=True)
320 except AssertionError:
321 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800322
323
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800324 def assert_test_image_in_path(self, image_path):
325 """Assert the image of image_path be a Chrome OS test image.
326
327 Args:
328 image_path: A path on the host to the test image.
329
330 Raises:
331 error.TestError: if the image is not a test image.
332 """
333 try:
334 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
335 image_path)
336 logging.info('Build of image: %s %s' % (build_ver, build_hash))
337 except ChromeOSTestError:
338 raise error.TestError(
339 'An USB disk containning a test image should be plugged '
340 'in the servo board.')
341
342
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800343 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800344 """Assert an USB disk plugged-in on servo and a test image inside.
345
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800346 Args:
347 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
348 If None, it is detected automatically.
349
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800350 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800351 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800352 """
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800353 if self.check_setup_done('usb_check'):
Vic Yang54f70572012-10-19 17:05:26 +0800354 return
355
Tom Wai-Hong Tam1c86c7a2012-10-22 10:08:24 +0800356 # TODO(waihong@chromium.org): We skip the check when servod runs in
357 # a different host since no easy way to access the servo host so far.
358 # Should find a way to work-around it.
359 if not self.servo.is_localhost():
360 logging.info('Skip checking Chrome OS test image in USB as servod '
361 'runs in a different host.')
362 return
363
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800364 if usb_dev:
365 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
366 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700367 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800368 usb_dev = self.servo.probe_host_usb_dev()
369 if not usb_dev:
370 raise error.TestError(
371 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800372 self.assert_test_image_in_path(usb_dev)
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800373 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800374
375
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800376 def get_server_address(self):
377 """Get the server address seen from the client.
378
379 Returns:
380 A string of the server address.
381 """
382 r = self.faft_client.run_shell_command_get_output("echo $SSH_CLIENT")
383 return r[0].split()[0]
384
385
Simran Basi741b5d42012-05-18 11:27:15 -0700386 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800387 """Install the test image specied by the path onto the USB and DUT disk.
388
389 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500390 recovery mode. Then runs 'chromeos-install' (and possible
391 chromeos-firmwareupdate') to install it to DUT disk.
392
393 Sample command line:
394
395 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
396 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
397 server/site_tests/firmware_XXXX/control
398
399 This test requires an automated recovery to occur while simulating
400 inserting and removing the usb key from the servo. To allow this the
401 following hardware setup is required:
402 1. servo2 board connected via servoflex.
403 2. USB key inserted in the servo2.
404 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
405 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800406
407 Args:
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800408 image_path: An URL or a path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800409 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800410 """
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800411 if self.check_setup_done('reimage'):
412 return
413
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800414 if image_path.startswith(self._HTTP_PREFIX):
415 # TODO(waihong@chromium.org): Add the check of the URL to ensure
416 # it is a test image.
417 devserver = None
418 image_url = image_path
419 else:
Tom Wai-Hong Tam08885ae2012-10-19 17:16:45 +0800420 self.assert_test_image_in_path(image_path)
Tom Wai-Hong Tame796de42012-10-16 19:42:20 +0800421 image_dir, image_base = os.path.split(image_path)
422 logging.info('Starting devserver to serve the image...')
423 # The following stdout and stderr arguments should not be None,
424 # even we don't use them. Otherwise, the socket of devserve is
425 # created as fd 1 (as no stdout) but it still thinks stdout is fd
426 # 1 and dump the log to the socket. Wrong HTTP protocol happens.
427 devserver = subprocess.Popen(['start_devserver',
428 '--archive_dir=%s' % image_dir,
429 '--port=%s' % self._DEVSERVER_PORT],
430 stdout=subprocess.PIPE,
431 stderr=subprocess.PIPE)
432 image_url = '%s%s:%s/static/archive/%s' % (
433 self._HTTP_PREFIX,
434 self.get_server_address(),
435 self._DEVSERVER_PORT,
436 image_base)
437
438 logging.info('Ask Servo to install the image from %s' % image_url)
439 self.servo.image_to_servo_usb(image_url)
440
441 if devserver and devserver.poll() is None:
442 logging.info('Shutting down devserver...')
443 devserver.terminate()
Mike Truty49153d82012-08-21 22:27:30 -0500444
445 # DUT is powered off while imaging servo USB.
446 # Now turn it on.
447 self.servo.power_short_press()
448 self.wait_for_client()
449 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
450
451 install_cmd = 'chromeos-install --yes'
452 if firmware_update:
453 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
454
455 self.register_faft_sequence((
456 { # Step 1, request recovery boot
457 'state_checker': (self.crossystem_checker, {
458 'mainfw_type': ('developer', 'normal'),
459 }),
460 'userspace_action': self.faft_client.request_recovery_boot,
461 'firmware_action': self.wait_fw_screen_and_plug_usb,
462 'install_deps_after_boot': True,
463 },
464 { # Step 2, expected recovery boot
465 'state_checker': (self.crossystem_checker, {
466 'mainfw_type': 'recovery',
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800467 'recovery_reason' : vboot.RECOVERY_REASON['US_TEST'],
Mike Truty49153d82012-08-21 22:27:30 -0500468 }),
469 'userspace_action': (self.faft_client.run_shell_command,
470 install_cmd),
471 'reboot_action': self.cold_reboot,
472 'install_deps_after_boot': True,
473 },
474 { # Step 3, expected normal or developer boot (not recovery)
475 'state_checker': (self.crossystem_checker, {
476 'mainfw_type': ('developer', 'normal')
477 }),
478 },
479 ))
480 self.run_faft_sequence()
481 # 'Unplug' any USB keys in the servo from the dut.
Tom Wai-Hong Tam953c7742012-10-16 21:09:31 +0800482 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam6668b762012-10-23 11:45:36 +0800483 # Mark usb_check done so it won't check a test image in USB anymore.
484 self.mark_setup_done('usb_check')
Tom Wai-Hong Tam73229372012-10-23 11:58:16 +0800485 self.mark_setup_done('reimage')
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800486
487
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800488 def clear_set_gbb_flags(self, clear_mask, set_mask):
489 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800490
491 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800492 clear_mask: A mask of flags to be cleared.
493 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800494 """
495 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800496 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
497
498 if (gbb_flags != new_flags):
499 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
500 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800501 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800502 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800503 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800504 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800505 if ((gbb_flags ^ new_flags) & vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800506 self.run_faft_step({
507 'firmware_action': self.wait_fw_screen_and_ctrl_d,
508 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800509
510
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800511 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800512 """Check if current platform has required EC capabilities.
513
514 Args:
515 required_cap: A list containing required EC capabilities. Pass in
516 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800517 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800518
519 Returns:
520 True if requirements are met. Otherwise, False.
521 """
522 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800523 if not suppress_warning:
524 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800525 return False
526
527 for cap in required_cap:
528 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800529 if not suppress_warning:
530 logging.warn('Requires EC capability "%s" to run this '
531 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800532 return False
533
534 return True
535
536
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800537 def _parse_crossystem_output(self, lines):
538 """Parse the crossystem output into a dict.
539
540 Args:
541 lines: The list of crossystem output strings.
542
543 Returns:
544 A dict which contains the crossystem keys/values.
545
546 Raises:
547 error.TestError: If wrong format in crossystem output.
548
549 >>> seq = FAFTSequence()
550 >>> seq._parse_crossystem_output([ \
551 "arch = x86 # Platform architecture", \
552 "cros_debug = 1 # OS should allow debug", \
553 ])
554 {'cros_debug': '1', 'arch': 'x86'}
555 >>> seq._parse_crossystem_output([ \
556 "arch=x86", \
557 ])
558 Traceback (most recent call last):
559 ...
560 TestError: Failed to parse crossystem output: arch=x86
561 >>> seq._parse_crossystem_output([ \
562 "arch = x86 # Platform architecture", \
563 "arch = arm # Platform architecture", \
564 ])
565 Traceback (most recent call last):
566 ...
567 TestError: Duplicated crossystem key: arch
568 """
569 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
570 parsed_list = {}
571 for line in lines:
572 matched = re.match(pattern, line.strip())
573 if not matched:
574 raise error.TestError("Failed to parse crossystem output: %s"
575 % line)
576 (name, value) = (matched.group(1), matched.group(2))
577 if name in parsed_list:
578 raise error.TestError("Duplicated crossystem key: %s" % name)
579 parsed_list[name] = value
580 return parsed_list
581
582
583 def crossystem_checker(self, expected_dict):
584 """Check the crossystem values matched.
585
586 Given an expect_dict which describes the expected crossystem values,
587 this function check the current crossystem values are matched or not.
588
589 Args:
590 expected_dict: A dict which contains the expected values.
591
592 Returns:
593 True if the crossystem value matched; otherwise, False.
594 """
595 lines = self.faft_client.run_shell_command_get_output('crossystem')
596 got_dict = self._parse_crossystem_output(lines)
597 for key in expected_dict:
598 if key not in got_dict:
599 logging.info('Expected key "%s" not in crossystem result' % key)
600 return False
601 if isinstance(expected_dict[key], str):
602 if got_dict[key] != expected_dict[key]:
603 logging.info("Expected '%s' value '%s' but got '%s'" %
604 (key, expected_dict[key], got_dict[key]))
605 return False
606 elif isinstance(expected_dict[key], tuple):
607 # Expected value is a tuple of possible actual values.
608 if got_dict[key] not in expected_dict[key]:
609 logging.info("Expected '%s' values %s but got '%s'" %
610 (key, str(expected_dict[key]), got_dict[key]))
611 return False
612 else:
613 logging.info("The expected_dict is neither a str nor a dict.")
614 return False
615 return True
616
617
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800618 def vdat_flags_checker(self, mask, value):
619 """Check the flags from VbSharedData matched.
620
621 This function checks the masked flags from VbSharedData using crossystem
622 are matched the given value.
623
624 Args:
625 mask: A bitmask of flags to be matched.
626 value: An expected value.
627
628 Returns:
629 True if the flags matched; otherwise, False.
630 """
631 lines = self.faft_client.run_shell_command_get_output(
632 'crossystem vdat_flags')
633 vdat_flags = int(lines[0], 16)
634 if vdat_flags & mask != value:
635 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
636 (value, mask, vdat_flags))
637 return False
638 return True
639
640
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800641 def ro_normal_checker(self, expected_fw=None, twostop=False):
642 """Check the current boot uses RO boot.
643
644 Args:
645 expected_fw: A string of expected firmware, 'A', 'B', or
646 None if don't care.
647 twostop: True to expect a TwoStop boot; False to expect a RO boot.
648
649 Returns:
650 True if the currect boot firmware matched and used RO boot;
651 otherwise, False.
652 """
653 crossystem_dict = {'tried_fwb': '0'}
654 if expected_fw:
655 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800656 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800657 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
658
659 return (self.vdat_flags_checker(
Tom Wai-Hong Tam6ec46e32012-10-05 16:39:21 +0800660 vboot.VDAT_FLAG_LF_USE_RO_NORMAL,
661 0 if twostop else vboot.VDAT_FLAG_LF_USE_RO_NORMAL) and
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800662 self.crossystem_checker(crossystem_dict))
663
664
Tom Wai-Hong Tam0a7b2be2012-10-15 16:44:12 +0800665 def dev_boot_usb_checker(self, dev_boot_usb=True):
666 """Check the current boot is from a developer USB (Ctrl-U trigger).
667
668 Args:
669 dev_boot_usb: True to expect an USB boot;
670 False to expect an internal device boot.
671
672 Returns:
673 True if the currect boot device matched; otherwise, False.
674 """
675 return (self.crossystem_checker({'mainfw_type': 'developer'})
676 and self.faft_client.is_removable_device_boot() == dev_boot_usb)
677
678
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800679 def root_part_checker(self, expected_part):
680 """Check the partition number of the root device matched.
681
682 Args:
683 expected_part: A string containing the number of the expected root
684 partition.
685
686 Returns:
687 True if the currect root partition number matched; otherwise, False.
688 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800689 part = self.faft_client.get_root_part()[-1]
690 if self.ROOTFS_MAP[expected_part] != part:
691 logging.info("Expected root part %s but got %s" %
692 (self.ROOTFS_MAP[expected_part], part))
693 return False
694 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800695
696
Vic Yang59cac9c2012-05-21 15:28:42 +0800697 def ec_act_copy_checker(self, expected_copy):
698 """Check the EC running firmware copy matches.
699
700 Args:
701 expected_copy: A string containing 'RO', 'A', or 'B' indicating
702 the expected copy of EC running firmware.
703
704 Returns:
705 True if the current EC running copy matches; otherwise, False.
706 """
707 lines = self.faft_client.run_shell_command_get_output('ectool version')
708 pattern = re.compile("Firmware copy: (.*)")
709 for line in lines:
710 matched = pattern.match(line)
711 if matched and matched.group(1) == expected_copy:
712 return True
713 return False
714
715
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800716 def check_root_part_on_non_recovery(self, part):
717 """Check the partition number of root device and on normal/dev boot.
718
719 Returns:
720 True if the root device matched and on normal/dev boot;
721 otherwise, False.
722 """
723 return self.root_part_checker(part) and \
724 self.crossystem_checker({
725 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800726 })
727
728
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800729 def _join_part(self, dev, part):
730 """Return a concatenated string of device and partition number.
731
732 Args:
733 dev: A string of device, e.g.'/dev/sda'.
734 part: A string of partition number, e.g.'3'.
735
736 Returns:
737 A concatenated string of device and partition number, e.g.'/dev/sda3'.
738
739 >>> seq = FAFTSequence()
740 >>> seq._join_part('/dev/sda', '3')
741 '/dev/sda3'
742 >>> seq._join_part('/dev/mmcblk0', '2')
743 '/dev/mmcblk0p2'
744 """
745 if 'mmcblk' in dev:
746 return dev + 'p' + part
747 else:
748 return dev + part
749
750
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800751 def copy_kernel_and_rootfs(self, from_part, to_part):
752 """Copy kernel and rootfs from from_part to to_part.
753
754 Args:
755 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800756 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800757 """
758 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800759 logging.info('Copying kernel 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.KERNEL_MAP[from_part]),
763 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
764 logging.info('Copying rootfs from %s to %s. Please wait...' %
765 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800766 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800767 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
768 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800769
770
771 def ensure_kernel_boot(self, part):
772 """Ensure the request kernel boot.
773
774 If not, it duplicates the current kernel to the requested kernel
775 and sets the requested higher priority to ensure it boot.
776
777 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800778 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800779 """
780 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800781 if self.faft_client.diff_kernel_a_b():
782 self.copy_kernel_and_rootfs(
783 from_part=self.OTHER_KERNEL_MAP[part],
784 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800785 self.run_faft_step({
786 'userspace_action': (self.reset_and_prioritize_kernel, part),
787 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800788
789
Vic Yang416f2032012-08-28 10:18:03 +0800790 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800791 """Set hardware write protect pin.
792
793 Args:
794 enable: True if asserting write protect pin. Otherwise, False.
795 """
796 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
797 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800798 self.servo.set('fw_wp', 'on' if enabled else 'off')
799
800
801 def set_EC_write_protect_and_reboot(self, enabled):
802 """Set EC write protect status and reboot to take effect.
803
804 EC write protect is only activated if both hardware write protect pin
805 is asserted and software write protect flag is set. Also, a reboot is
806 required for write protect to take effect.
807
808 Since the software write protect flag cannot be unset if hardware write
809 protect pin is asserted, we need to deasserted the pin first if we are
810 deactivating write protect. Similarly, a reboot is required before we
811 can modify the software flag.
812
813 This method asserts/deasserts hardware write protect pin first, and
814 set corresponding EC software write protect flag.
815
816 Args:
817 enable: True if activating EC write protect. Otherwise, False.
818 """
819 self.set_hardware_write_protect(enabled)
820 if enabled:
821 # Set write protect flag and reboot to take effect.
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800822 self.ec.send_command("flashwp enable")
Vic Yang416f2032012-08-28 10:18:03 +0800823 self.sync_and_ec_reboot()
824 else:
825 # Reboot after deasserting hardware write protect pin to deactivate
826 # write protect. And then remove software write protect flag.
827 self.sync_and_ec_reboot()
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800828 self.ec.send_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800829
830
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800831 def send_ctrl_d_to_dut(self):
832 """Send Ctrl-D key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800833 if self._customized_key_commands['ctrl_d']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800834 logging.info('running the customized Ctrl-D key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800835 os.system(self._customized_key_commands['ctrl_d'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800836 else:
837 self.servo.ctrl_d()
838
839
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800840 def send_ctrl_u_to_dut(self):
841 """Send Ctrl-U key to DUT.
842
843 Raises:
844 error.TestError: if a non-Chrome EC device or no Ctrl-U command given
845 on a no-build-in-keyboard device.
846 """
847 if self._customized_key_commands['ctrl_u']:
848 logging.info('running the customized Ctrl-U key command')
849 os.system(self._customized_key_commands['ctrl_u'])
850 elif self.check_ec_capability(['keyboard'], suppress_warning=True):
851 self.ec.key_down('<ctrl_l>')
852 self.ec.key_down('u')
853 self.ec.key_up('u')
854 self.ec.key_up('<ctrl_l>')
855 elif self.client_attr.has_keyboard:
856 raise error.TestError(
857 "Can't send Ctrl-U to DUT without using Chrome EC.")
858 else:
859 raise error.TestError(
860 "Should specify the ctrl_u_cmd argument.")
861
862
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800863 def send_enter_to_dut(self):
864 """Send Enter key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800865 if self._customized_key_commands['enter']:
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800866 logging.info('running the customized Enter key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800867 os.system(self._customized_key_commands['enter'])
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800868 else:
869 self.servo.enter_key()
870
871
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800872 def send_space_to_dut(self):
873 """Send Space key to DUT."""
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800874 if self._customized_key_commands['space']:
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800875 logging.info('running the customized Space key command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800876 os.system(self._customized_key_commands['space'])
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800877 else:
878 # Send the alternative key combinaton of space key to servo.
879 self.servo.ctrl_refresh_key()
880
881
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800882 def wait_fw_screen_and_ctrl_d(self):
883 """Wait for firmware warning screen and press Ctrl-D."""
884 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800885 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800886
887
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800888 def wait_fw_screen_and_ctrl_u(self):
889 """Wait for firmware warning screen and press Ctrl-U."""
890 time.sleep(self.FIRMWARE_SCREEN_DELAY)
891 self.send_ctrl_u_to_dut()
892
893
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800894 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
895 """Wait for firmware warning screen and trigger recovery boot."""
896 time.sleep(self.FIRMWARE_SCREEN_DELAY)
897 self.send_enter_to_dut()
898
899 # For Alex/ZGB, there is a dev warning screen in text mode.
900 # Skip it by pressing Ctrl-D.
901 if need_dev_transition:
902 time.sleep(self.TEXT_SCREEN_DELAY)
903 self.send_ctrl_d_to_dut()
904
905
Mike Truty49153d82012-08-21 22:27:30 -0500906 def wait_fw_screen_and_unplug_usb(self):
907 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800908 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800909 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
910 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500911
912
913 def wait_fw_screen_and_plug_usb(self):
914 """Wait for firmware warning screen and then unplug and plug the USB."""
915 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800916 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
917
918
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800919 def wait_fw_screen_and_press_power(self):
920 """Wait for firmware warning screen and press power button."""
921 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800922 # While the firmware screen, the power button probing loop sleeps
923 # 0.25 second on every scan. Use the normal delay (1.2 second) for
924 # power press.
925 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800926
927
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800928 def wait_longer_fw_screen_and_press_power(self):
929 """Wait for firmware screen without timeout and press power button."""
930 time.sleep(self.DEV_SCREEN_TIMEOUT)
931 self.wait_fw_screen_and_press_power()
932
933
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800934 def wait_fw_screen_and_close_lid(self):
935 """Wait for firmware warning screen and close lid."""
936 time.sleep(self.FIRMWARE_SCREEN_DELAY)
937 self.servo.lid_close()
938
939
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800940 def wait_longer_fw_screen_and_close_lid(self):
941 """Wait for firmware screen without timeout and close lid."""
942 time.sleep(self.FIRMWARE_SCREEN_DELAY)
943 self.wait_fw_screen_and_close_lid()
944
945
Tom Wai-Hong Tam01d5e572012-10-23 10:07:11 +0800946 def setup_gbb_flags(self):
947 """Setup the GBB flags for FAFT test."""
948 if self.check_setup_done('gbb_flags'):
949 return
950
951 logging.info('Set proper GBB flags for test.')
952 self.clear_set_gbb_flags(vboot.GBB_FLAG_DEV_SCREEN_SHORT_DELAY |
953 vboot.GBB_FLAG_FORCE_DEV_SWITCH_ON |
954 vboot.GBB_FLAG_FORCE_DEV_BOOT_USB |
955 vboot.GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK,
956 vboot.GBB_FLAG_ENTER_TRIGGERS_TONORM)
957 self.mark_setup_done('gbb_flags')
958
959
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800960 def setup_tried_fwb(self, tried_fwb):
961 """Setup for fw B tried state.
962
963 It makes sure the system in the requested fw B tried state. If not, it
964 tries to do so.
965
966 Args:
967 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
968 """
969 if tried_fwb:
970 if not self.crossystem_checker({'tried_fwb': '1'}):
971 logging.info(
972 'Firmware is not booted with tried_fwb. Reboot into it.')
973 self.run_faft_step({
974 'userspace_action': self.faft_client.set_try_fw_b,
975 })
976 else:
977 if not self.crossystem_checker({'tried_fwb': '0'}):
978 logging.info(
979 'Firmware is booted with tried_fwb. Reboot to clear.')
980 self.run_faft_step({})
981
982
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800983 def enable_rec_mode_and_reboot(self):
984 """Switch to rec mode and reboot.
985
986 This method emulates the behavior of the old physical recovery switch,
987 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
988 recovery mode, i.e. just press Power + Esc + Refresh.
989 """
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800990 if self._customized_key_commands['rec_reboot']:
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800991 logging.info('running the customized rec reboot command')
Tom Wai-Hong Tamadbec3e2012-10-15 14:20:15 +0800992 os.system(self._customized_key_commands['rec_reboot'])
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800993 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800994 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800995 self.servo.set('cold_reset', 'on')
996 time.sleep(self.COLD_RESET_DELAY)
997 self.servo.set('cold_reset', 'off')
998 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +0800999 self.ec.send_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +08001000 time.sleep(self.EC_BOOT_DELAY)
Tom Wai-Hong Tam6019a1a2012-10-12 14:03:34 +08001001 self.ec.send_command("hostevent set 0x4000")
Vic Yang611dd852012-08-02 15:36:31 +08001002 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001003 else:
1004 self.servo.enable_recovery_mode()
1005 self.cold_reboot()
1006 time.sleep(self.EC_REBOOT_DELAY)
1007 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001008
1009
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001010 def enable_dev_mode_and_reboot(self):
1011 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001012 if self.client_attr.keyboard_dev:
1013 self.enable_keyboard_dev_mode()
1014 else:
1015 self.servo.enable_development_mode()
1016 self.faft_client.run_shell_command(
1017 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001018
1019
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001020 def enable_normal_mode_and_reboot(self):
1021 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001022 if self.client_attr.keyboard_dev:
1023 self.disable_keyboard_dev_mode()
1024 else:
1025 self.servo.disable_development_mode()
1026 self.faft_client.run_shell_command(
1027 'chromeos-firmwareupdate --mode tonormal && reboot')
1028
1029
1030 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
1031 """Wait for firmware screen and then switch into or out of dev mode.
1032
1033 Args:
1034 dev: True if switching into dev mode. Otherwise, False.
1035 """
1036 time.sleep(self.FIRMWARE_SCREEN_DELAY)
1037 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001038 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001039 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001040 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +08001041 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001042 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001043
1044
1045 def enable_keyboard_dev_mode(self):
1046 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001047 # Plug out USB disk for preventing recovery boot without warning
1048 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001049 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001050 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001051 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001052 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001053
1054
1055 def disable_keyboard_dev_mode(self):
1056 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001057 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001058 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001059 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001060 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001061 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001062
1063
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001064 def setup_dev_mode(self, dev_mode):
1065 """Setup for development mode.
1066
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001067 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001068 tries to do so.
1069
1070 Args:
1071 dev_mode: True if requested in dev mode; False if normal mode.
1072 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001073 # Change the default firmware_action for dev mode passing the fw screen.
1074 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001075 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1076 else None),
1077 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001078 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001079 if (not self.client_attr.keyboard_dev and
1080 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001081 logging.info('Dev switch is not on. Now switch it on.')
1082 self.servo.enable_development_mode()
1083 if not self.crossystem_checker({'devsw_boot': '1',
1084 'mainfw_type': 'developer'}):
1085 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001086 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001087 'userspace_action': None if self.client_attr.keyboard_dev
1088 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001089 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001090 'reboot_action': self.enable_keyboard_dev_mode if
1091 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001092 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001093 else:
Vic Yange7553162012-06-20 16:20:47 +08001094 if (not self.client_attr.keyboard_dev and
1095 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001096 logging.info('Dev switch is not off. Now switch it off.')
1097 self.servo.disable_development_mode()
1098 if not self.crossystem_checker({'devsw_boot': '0',
1099 'mainfw_type': 'normal'}):
1100 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001101 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001102 'userspace_action': None if self.client_attr.keyboard_dev
1103 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001104 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001105 'reboot_action': self.disable_keyboard_dev_mode if
1106 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001107 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001108
1109
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001110 def setup_kernel(self, part):
1111 """Setup for kernel test.
1112
1113 It makes sure both kernel A and B bootable and the current boot is
1114 the requested kernel part.
1115
1116 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001117 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001118 """
1119 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001120 if self.faft_client.diff_kernel_a_b():
1121 self.copy_kernel_and_rootfs(from_part=part,
1122 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001123 self.reset_and_prioritize_kernel(part)
1124
1125
1126 def reset_and_prioritize_kernel(self, part):
1127 """Make the requested partition highest priority.
1128
1129 This function also reset kerenl A and B to bootable.
1130
1131 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001132 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001133 """
1134 root_dev = self.faft_client.get_root_dev()
1135 # Reset kernel A and B to bootable.
1136 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1137 (self.KERNEL_MAP['a'], root_dev))
1138 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1139 (self.KERNEL_MAP['b'], root_dev))
1140 # Set kernel part highest priority.
1141 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1142 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001143 # Safer to sync and wait until the cgpt status written to the disk.
1144 self.faft_client.run_shell_command('sync')
1145 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001146
1147
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001148 def warm_reboot(self):
1149 """Request a warm reboot.
1150
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001151 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001152 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001153 # Use cold reset if the warm reset is broken.
1154 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001155 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1156 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001157 else:
1158 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001159
1160
1161 def cold_reboot(self):
1162 """Request a cold reboot.
1163
1164 A wrapper for underlying servo cold reset.
1165 """
Gediminas Ramanauskasc6025692012-10-23 14:33:40 -07001166 if self.client_attr.broken_warm_reset:
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001167 self.servo.set('pwr_button', 'press')
1168 self.servo.set('cold_reset', 'on')
1169 self.servo.set('cold_reset', 'off')
1170 time.sleep(self.POWER_BTN_DELAY)
1171 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001172 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001173 # We don't use servo.cold_reset() here because software sync is
1174 # not yet finished, and device may or may not come up after cold
1175 # reset. Pressing power button before firmware comes up solves this.
1176 #
1177 # The correct behavior should be (not work now):
1178 # - If rebooting EC with rec mode on, power on AP and it boots
1179 # into recovery mode.
1180 # - If rebooting EC with rec mode off, power on AP for software
1181 # sync. Then AP checks if lid open or not. If lid open, continue;
1182 # otherwise, shut AP down and need servo for a power button
1183 # press.
1184 self.servo.set('cold_reset', 'on')
1185 self.servo.set('cold_reset', 'off')
1186 time.sleep(self.POWER_BTN_DELAY)
1187 self.servo.power_short_press()
1188 else:
1189 self.servo.cold_reset()
1190
1191
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001192 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001193 """Request the client sync and do a warm reboot.
1194
1195 This is the default reboot action on FAFT.
1196 """
1197 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001198 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001199 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001200
1201
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001202 def sync_and_cold_reboot(self):
1203 """Request the client sync and do a cold reboot.
1204
1205 This reboot action is used to reset EC for recovery mode.
1206 """
1207 self.faft_client.run_shell_command('sync')
1208 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001209 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001210
1211
Vic Yangaeb10392012-08-28 09:25:09 +08001212 def sync_and_ec_reboot(self, args=''):
1213 """Request the client sync and do a EC triggered reboot.
1214
1215 Args:
1216 args: Arguments passed to "ectool reboot_ec". Including:
1217 RO: jump to EC RO firmware.
1218 RW: jump to EC RW firmware.
1219 cold: Cold/hard reboot.
1220 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001221 self.faft_client.run_shell_command('sync')
1222 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001223 # Since EC reboot happens immediately, delay before actual reboot to
1224 # allow FAFT client returning.
1225 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1226 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001227 time.sleep(self.EC_REBOOT_DELAY)
1228 self.check_lid_and_power_on()
1229
1230
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001231 def full_power_off_and_on(self):
1232 """Shutdown the device by pressing power button and power on again."""
1233 # Press power button to trigger Chrome OS normal shutdown process.
1234 self.servo.power_normal_press()
1235 time.sleep(self.FULL_POWER_OFF_DELAY)
1236 # Short press power button to boot DUT again.
1237 self.servo.power_short_press()
1238
1239
Vic Yangf86728a2012-07-30 10:44:07 +08001240 def check_lid_and_power_on(self):
1241 """
1242 On devices with EC software sync, system powers on after EC reboots if
1243 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1244 This method checks lid switch state and presses power button if
1245 necessary.
1246 """
1247 if self.servo.get("lid_open") == "no":
1248 time.sleep(self.SOFTWARE_SYNC_DELAY)
1249 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001250
1251
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001252 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1253 """Modify the kernel header magic in USB stick.
1254
1255 The kernel header magic is the first 8-byte of kernel partition.
1256 We modify it to make it fail on kernel verification check.
1257
1258 Args:
1259 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1260 from_magic: A string of magic which we change it from.
1261 to_magic: A string of magic which we change it to.
1262
1263 Raises:
1264 error.TestError: if failed to change magic.
1265 """
1266 assert len(from_magic) == 8
1267 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001268 # USB image only contains one kernel.
1269 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001270 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1271 current_magic = utils.system_output(read_cmd)
1272 if current_magic == to_magic:
1273 logging.info("The kernel magic is already %s." % current_magic)
1274 return
1275 if current_magic != from_magic:
1276 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1277
1278 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1279 (from_magic, to_magic))
1280 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1281 " 2>/dev/null" % (to_magic, kernel_part))
1282 utils.system(write_cmd)
1283
1284 if utils.system_output(read_cmd) != to_magic:
1285 raise error.TestError("Failed to write new magic.")
1286
1287
1288 def corrupt_usb_kernel(self, usb_dev):
1289 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1290
1291 Args:
1292 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1293 """
1294 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1295 self.CORRUPTED_MAGIC)
1296
1297
1298 def restore_usb_kernel(self, usb_dev):
1299 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1300
1301 Args:
1302 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1303 """
1304 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1305 self.CHROMEOS_MAGIC)
1306
1307
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001308 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001309 """Call the action function with/without arguments.
1310
1311 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001312 action_tuple: A function, or a tuple (function, args, error_msg),
1313 in which, args and error_msg are optional. args is
1314 either a value or a tuple if multiple arguments.
1315 check_status: Check the return value of action function. If not
1316 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001317
1318 Returns:
1319 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001320
1321 Raises:
1322 error.TestError: An error when the action function is not callable.
1323 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001324 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001325 action = action_tuple
1326 args = ()
1327 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001328 if isinstance(action_tuple, tuple):
1329 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001330 if len(action_tuple) >= 2:
1331 args = action_tuple[1]
1332 if not isinstance(args, tuple):
1333 args = (args,)
1334 if len(action_tuple) >= 3:
Tom Wai-Hong Tamff560882012-10-15 16:50:06 +08001335 error_msg = action_tuple[2]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001336
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001337 if action is None:
1338 return
1339
1340 if not callable(action):
1341 raise error.TestError('action is not callable!')
1342
1343 info_msg = 'calling %s' % str(action)
1344 if args:
1345 info_msg += ' with args %s' % str(args)
1346 logging.info(info_msg)
1347 ret = action(*args)
1348
1349 if check_status and not ret:
1350 raise error.TestFail('%s: %s returning %s' %
1351 (error_msg, info_msg, str(ret)))
1352 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001353
1354
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001355 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1356 post_power_action=None):
1357 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1358
1359 Args:
1360 shutdown_action: a function which makes DUT shutdown, like pressing
1361 power key.
1362 pre_power_action: a function which is called before next power on.
1363 post_power_action: a function which is called after next power on.
1364
1365 Raises:
1366 error.TestFail: if the shutdown_action() failed to turn DUT off.
1367 """
1368 self._call_action(shutdown_action)
1369 logging.info('Wait to ensure DUT shut down...')
1370 try:
1371 self.wait_for_client()
1372 raise error.TestFail(
1373 'Should shut the device down after calling %s.' %
1374 str(shutdown_action))
1375 except AssertionError:
1376 logging.info(
1377 'DUT is surely shutdown. We are going to power it on again...')
1378
1379 if pre_power_action:
1380 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001381 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001382 if post_power_action:
1383 self._call_action(post_power_action)
1384
1385
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001386 def register_faft_template(self, template):
1387 """Register FAFT template, the default FAFT_STEP of each step.
1388
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001389 Any missing field falls back to the original faft_template.
1390
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001391 Args:
1392 template: A FAFT_STEP dict.
1393 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001394 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001395
1396
1397 def register_faft_sequence(self, sequence):
1398 """Register FAFT sequence.
1399
1400 Args:
1401 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1402 """
1403 self._faft_sequence = sequence
1404
1405
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001406 def run_faft_step(self, step, no_reboot=False):
1407 """Run a single FAFT step.
1408
1409 Any missing field falls back to faft_template. An empty step means
1410 running the default faft_template.
1411
1412 Args:
1413 step: A FAFT_STEP dict.
1414 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001415
1416 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001417 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001418 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001419 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1420 'firmware_action', 'install_deps_after_boot')
1421
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001422 test = {}
1423 test.update(self._faft_template)
1424 test.update(step)
1425
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001426 for key in test:
1427 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001428 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001429
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001430 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001431 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001432
1433 self._call_action(test['userspace_action'])
1434
1435 # Don't run reboot_action and firmware_action if no_reboot is True.
1436 if not no_reboot:
1437 self._call_action(test['reboot_action'])
1438 self.wait_for_client_offline()
1439 self._call_action(test['firmware_action'])
1440
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001441 try:
1442 if 'install_deps_after_boot' in test:
1443 self.wait_for_client(
1444 install_deps=test['install_deps_after_boot'])
1445 else:
1446 self.wait_for_client()
1447 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001448 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001449 self.reset_client()
1450 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001451
1452
1453 def run_faft_sequence(self):
1454 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001455 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001456 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001457 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001458 logging.info('======== Running FAFT sequence step %d ========' %
1459 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001460 # Don't reboot in the last step.
1461 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001462 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001463
1464
ctchang38ae4922012-09-03 17:01:16 +08001465 def get_current_firmware_sha(self):
1466 """Get current firmware sha of body and vblock.
1467
1468 Returns:
1469 Current firmware sha follows the order (
1470 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1471 """
1472 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1473 self.faft_client.get_firmware_sha('a'),
1474 self.faft_client.get_firmware_sig_sha('b'),
1475 self.faft_client.get_firmware_sha('b'))
1476 return current_firmware_sha
1477
1478
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001479 def is_firmware_changed(self):
1480 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001481
1482 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001483 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001484 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001485 # Device may not be rebooted after test.
1486 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001487
1488 current_sha = self.get_current_firmware_sha()
1489
1490 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001491 return False
ctchang38ae4922012-09-03 17:01:16 +08001492 else:
ctchang38ae4922012-09-03 17:01:16 +08001493 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1494 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1495 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1496 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001497 logging.info("Firmware changed:")
1498 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1499 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1500 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1501 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1502 return True
ctchang38ae4922012-09-03 17:01:16 +08001503
1504
1505 def backup_firmware(self, suffix='.original'):
1506 """Backup firmware to file, and then send it to host.
1507
1508 Args:
1509 suffix: a string appended to backup file name
1510 """
1511 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001512 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1513 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1514 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001515
1516 self._backup_firmware_sha = self.get_current_firmware_sha()
1517 logging.info('Backup firmware stored in %s with suffix %s' % (
1518 self.resultsdir, suffix))
1519
1520
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001521 def is_firmware_saved(self):
1522 """Check if a firmware saved (called backup_firmware before).
1523
1524 Returns:
1525 True if the firmware is backuped; otherwise False.
1526 """
1527 return self._backup_firmware_sha != ()
1528
1529
ctchang38ae4922012-09-03 17:01:16 +08001530 def restore_firmware(self, suffix='.original'):
1531 """Restore firmware from host in resultsdir.
1532
1533 Args:
1534 suffix: a string appended to backup file name
1535 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001536 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001537 return
1538
1539 # Backup current corrupted firmware.
1540 self.backup_firmware(suffix='.corrupt')
1541
1542 # Restore firmware.
1543 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001544 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1545 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001546
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001547 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001548 self.sync_and_warm_reboot()
1549 self.wait_for_client_offline()
1550 self.wait_for_client()
1551
ctchang38ae4922012-09-03 17:01:16 +08001552 logging.info('Successfully restore firmware.')
Chun-ting Changf91ee0f2012-09-17 18:31:54 +08001553
1554
1555 def setup_firmwareupdate_shellball(self, shellball=None):
1556 """Deside a shellball to use in firmware update test.
1557
1558 Check if there is a given shellball, and it is a shell script. Then,
1559 send it to the remote host. Otherwise, use
1560 /usr/sbin/chromeos-firmwareupdate.
1561
1562 Args:
1563 shellball: path of a shellball or default to None.
1564
1565 Returns:
1566 Path of shellball in remote host.
1567 If use default shellball, reutrn None.
1568 """
1569 updater_path = None
1570 if shellball:
1571 # Determine the firmware file is a shellball or a raw binary.
1572 is_shellball = (utils.system_output("file %s" % shellball).find(
1573 "shell script") != -1)
1574 if is_shellball:
1575 logging.info('Device will update firmware with shellball %s'
1576 % shellball)
1577 temp_dir = self.faft_client.create_temp_dir('shellball_')
1578 temp_shellball = os.path.join(temp_dir, 'updater.sh')
1579 self._client.send_file(shellball, temp_shellball)
1580 updater_path = temp_shellball
1581 else:
1582 raise error.TestFail(
1583 'The given shellball is not a shell script.')
1584 return updater_path