blob: 60e0f48524ac626f6ac20cd9035e3fc9e2052b5c [file] [log] [blame]
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +08005import ctypes
Vic Yangb4e3e742012-06-02 13:17:38 +08006import fdpexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08007import logging
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +08008import os
Vic Yangb4e3e742012-06-02 13:17:38 +08009import pexpect
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080010import re
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080011import sys
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080012import tempfile
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080013import time
14import xmlrpclib
15
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +080016from autotest_lib.client.bin import utils
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080017from autotest_lib.client.common_lib import error
Vic Yangebd6de62012-06-26 14:25:57 +080018from autotest_lib.server.cros.faft_client_attribute import FAFTClientAttribute
Tom Wai-Hong Tam22b77302011-11-03 13:03:48 +080019from autotest_lib.server.cros.servo_test import ServoTest
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080020from autotest_lib.site_utils import lab_test
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080021
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080022dirname = os.path.dirname(sys.modules[__name__].__file__)
23autotest_dir = os.path.abspath(os.path.join(dirname, "..", ".."))
24cros_dir = os.path.join(autotest_dir, "..", "..", "..", "..")
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080025
26class FAFTSequence(ServoTest):
27 """
28 The base class of Fully Automated Firmware Test Sequence.
29
30 Many firmware tests require several reboot cycles and verify the resulted
31 system states. To do that, an Autotest test case should detailly handle
32 every action on each step. It makes the test case hard to read and many
33 duplicated code. The base class FAFTSequence is to solve this problem.
34
35 The actions of one reboot cycle is defined in a dict, namely FAFT_STEP.
36 There are four functions in the FAFT_STEP dict:
37 state_checker: a function to check the current is valid or not,
38 returning True if valid, otherwise, False to break the whole
39 test sequence.
40 userspace_action: a function to describe the action ran in userspace.
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +080041 reboot_action: a function to do reboot, default: sync_and_warm_reboot.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080042 firmware_action: a function to describe the action ran after reboot.
43
Tom Wai-Hong Tam7c17ff22011-10-26 09:44:09 +080044 And configurations:
45 install_deps_after_boot: if True, install the Autotest dependency after
46 boot; otherwise, do nothing. It is for the cases of recovery mode
47 test. The test boots a USB/SD image instead of an internal image.
48 The previous installed Autotest dependency on the internal image
49 is lost. So need to install it again.
50
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080051 The default FAFT_STEP checks nothing in state_checker and does nothing in
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +080052 userspace_action and firmware_action. Its reboot_action is a hardware
53 reboot. You can change the default FAFT_STEP by calling
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080054 self.register_faft_template(FAFT_STEP).
55
56 A FAFT test case consists of several FAFT_STEP's, namely FAFT_SEQUENCE.
57 FAFT_SEQUENCE is an array of FAFT_STEP's. Any missing fields on FAFT_STEP
58 fall back to default.
59
60 In the run_once(), it should register and run FAFT_SEQUENCE like:
61 def run_once(self):
62 self.register_faft_sequence(FAFT_SEQUENCE)
63 self.run_faft_sequnce()
64
65 Note that in the last step, we only run state_checker. The
66 userspace_action, reboot_action, and firmware_action are not executed.
67
68 Attributes:
69 _faft_template: The default FAFT_STEP of each step. The actions would
70 be over-written if the registered FAFT_SEQUENCE is valid.
71 _faft_sequence: The registered FAFT_SEQUENCE.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080072 _customized_ctrl_d_key_command: The customized Ctrl-D key command
73 instead of sending key via servo board.
74 _customized_enter_key_command: The customized Enter key command instead
75 of sending key via servo board.
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +080076 _customized_space_key_command: The customized Space key command instead
77 of sending key via servo board.
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +080078 _customized_rec_reboot_command: The customized recovery reboot command
79 instead of sending key combination of Power + Esc + F3 for
80 triggering recovery reboot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +080081 _install_image_path: The path of Chrome OS test image to be installed.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +080082 _firmware_update: Boolean. True if firmware update needed after
83 installing the image.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +080084 """
85 version = 1
86
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +080087
88 # Mapping of partition number of kernel and rootfs.
89 KERNEL_MAP = {'a':'2', 'b':'4', '2':'2', '4':'4', '3':'2', '5':'4'}
90 ROOTFS_MAP = {'a':'3', 'b':'5', '2':'3', '4':'5', '3':'3', '5':'5'}
91 OTHER_KERNEL_MAP = {'a':'4', 'b':'2', '2':'4', '4':'2', '3':'4', '5':'2'}
92 OTHER_ROOTFS_MAP = {'a':'5', 'b':'3', '2':'5', '4':'3', '3':'5', '5':'3'}
93
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080094 # Delay between power-on and firmware screen.
Tom Wai-Hong Tam66af37b2012-08-01 10:48:42 +080095 FIRMWARE_SCREEN_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080096 # Delay between passing firmware screen and text mode warning screen.
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +080097 TEXT_SCREEN_DELAY = 20
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +080098 # Delay of loading the USB kernel.
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +080099 USB_LOAD_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800100 # Delay between USB plug-out and plug-in.
Tom Wai-Hong Tam9ca742a2011-12-05 15:48:57 +0800101 USB_PLUG_DELAY = 10
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800102 # Delay after running the 'sync' command.
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800103 SYNC_DELAY = 5
Vic Yang59cac9c2012-05-21 15:28:42 +0800104 # Delay for waiting client to return before EC reboot
105 EC_REBOOT_DELAY = 1
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +0800106 # Delay for waiting client to full power off
107 FULL_POWER_OFF_DELAY = 30
Vic Yang59cac9c2012-05-21 15:28:42 +0800108 # Delay between EC reboot and pressing power button
109 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800110 # Delay of EC software sync hash calculating time
111 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800112 # Delay between EC boot and ChromeEC console functional
113 EC_BOOT_DELAY = 0.5
114 # Duration of holding cold_reset to reset device
115 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800116
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800117 # The developer screen timeouts fit our spec.
118 DEV_SCREEN_TIMEOUT = 30
119
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800120 CHROMEOS_MAGIC = "CHROMEOS"
121 CORRUPTED_MAGIC = "CORRUPTD"
122
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800123 # Recovery reason codes, copied from:
124 # vboot_reference/firmware/lib/vboot_nvstorage.h
125 # vboot_reference/firmware/lib/vboot_struct.h
126 RECOVERY_REASON = {
127 # Recovery not requested
128 'NOT_REQUESTED': '0', # 0x00
129 # Recovery requested from legacy utility
130 'LEGACY': '1', # 0x01
131 # User manually requested recovery via recovery button
132 'RO_MANUAL': '2', # 0x02
133 # RW firmware failed signature check
134 'RO_INVALID_RW': '3', # 0x03
135 # S3 resume failed
136 'RO_S3_RESUME': '4', # 0x04
137 # TPM error in read-only firmware
138 'RO_TPM_ERROR': '5', # 0x05
139 # Shared data error in read-only firmware
140 'RO_SHARED_DATA': '6', # 0x06
141 # Test error from S3Resume()
142 'RO_TEST_S3': '7', # 0x07
143 # Test error from LoadFirmwareSetup()
144 'RO_TEST_LFS': '8', # 0x08
145 # Test error from LoadFirmware()
146 'RO_TEST_LF': '9', # 0x09
147 # RW firmware failed signature check
148 'RW_NOT_DONE': '16', # 0x10
149 'RW_DEV_MISMATCH': '17', # 0x11
150 'RW_REC_MISMATCH': '18', # 0x12
151 'RW_VERIFY_KEYBLOCK': '19', # 0x13
152 'RW_KEY_ROLLBACK': '20', # 0x14
153 'RW_DATA_KEY_PARSE': '21', # 0x15
154 'RW_VERIFY_PREAMBLE': '22', # 0x16
155 'RW_FW_ROLLBACK': '23', # 0x17
156 'RW_HEADER_VALID': '24', # 0x18
157 'RW_GET_FW_BODY': '25', # 0x19
158 'RW_HASH_WRONG_SIZE': '26', # 0x1A
159 'RW_VERIFY_BODY': '27', # 0x1B
160 'RW_VALID': '28', # 0x1C
161 # Read-only normal path requested by firmware preamble, but
162 # unsupported by firmware.
163 'RW_NO_RO_NORMAL': '29', # 0x1D
164 # Firmware boot failure outside of verified boot
165 'RO_FIRMWARE': '32', # 0x20
166 # Recovery mode TPM initialization requires a system reboot.
167 # The system was already in recovery mode for some other reason
168 # when this happened.
169 'RO_TPM_REBOOT': '33', # 0x21
170 # Unspecified/unknown error in read-only firmware
171 'RO_UNSPECIFIED': '63', # 0x3F
172 # User manually requested recovery by pressing a key at developer
173 # warning screen.
174 'RW_DEV_SCREEN': '65', # 0x41
175 # No OS kernel detected
176 'RW_NO_OS': '66', # 0x42
177 # OS kernel failed signature check
178 'RW_INVALID_OS': '67', # 0x43
179 # TPM error in rewritable firmware
180 'RW_TPM_ERROR': '68', # 0x44
181 # RW firmware in dev mode, but dev switch is off.
182 'RW_DEV_MISMATCH': '69', # 0x45
183 # Shared data error in rewritable firmware
184 'RW_SHARED_DATA': '70', # 0x46
185 # Test error from LoadKernel()
186 'RW_TEST_LK': '71', # 0x47
187 # No bootable disk found
188 'RW_NO_DISK': '72', # 0x48
189 # Unspecified/unknown error in rewritable firmware
190 'RW_UNSPECIFIED': '127', # 0x7F
191 # DM-verity error
192 'KE_DM_VERITY': '129', # 0x81
193 # Unspecified/unknown error in kernel
194 'KE_UNSPECIFIED': '191', # 0xBF
195 # Recovery mode test from user-mode
196 'US_TEST': '193', # 0xC1
197 # Unspecified/unknown error in user-mode
198 'US_UNSPECIFIED': '255', # 0xFF
199 }
200
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800201 # GBB flags
202 GBB_FLAG_DEV_SCREEN_SHORT_DELAY = 0x00000001
203 GBB_FLAG_LOAD_OPTION_ROMS = 0x00000002
204 GBB_FLAG_ENABLE_ALTERNATE_OS = 0x00000004
205 GBB_FLAG_FORCE_DEV_SWITCH_ON = 0x00000008
206 GBB_FLAG_FORCE_DEV_BOOT_USB = 0x00000010
207 GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK = 0x00000020
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800208 GBB_FLAG_ENTER_TRIGGERS_TONORM = 0x00000040
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800209
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800210 # VbSharedData flags
211 # Copied from vboot_reference/firmware/include/vboot_struct.h
212 VDAT_FLAG_FWB_TRIED = 0x00000001
213 VDAT_FLAG_KERNEL_KEY_VERIFIED = 0x00000002
214 VDAT_FLAG_LF_DEV_SWITCH_ON = 0x00000004
215 VDAT_FLAG_LF_USE_RO_NORMAL = 0x00000008
216 VDAT_FLAG_BOOT_DEV_SWITCH_ON = 0x00000010
217 VDAT_FLAG_BOOT_REC_SWITCH_ON = 0x00000020
218 VDAT_FLAG_BOOT_FIRMWARE_WP_ENABLED = 0x00000040
219 VDAT_FLAG_BOOT_S3_RESUME = 0x00000100
220 VDAT_FLAG_BOOT_RO_NORMAL_SUPPORT = 0x00000200
221 VDAT_FLAG_HONOR_VIRT_DEV_SWITCH = 0x00000400
222 VDAT_FLAG_EC_SOFTWARE_SYNC = 0x00000800
223 VDAT_FLAG_EC_SLOW_UPDATE = 0x00001000
224
Tom Wai-Hong Tame3c72432012-09-05 10:48:31 +0800225 # Firmware preamble flags
226 PREAMBLE_USE_RO_NORMAL = 0x00000001
227
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800228 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800229 _faft_sequence = ()
230
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800231 _customized_ctrl_d_key_command = None
232 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800233 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800234 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800235 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800236 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800237
ctchang38ae4922012-09-03 17:01:16 +0800238 _backup_firmware_sha = ()
239
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800240
241 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
242 # Parse arguments from command line
243 args = {}
244 for arg in cmdline_args:
245 match = re.search("^(\w+)=(.+)", arg)
246 if match:
247 args[match.group(1)] = match.group(2)
248
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800249 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800250 if 'ctrl_d_cmd' in args:
251 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
252 logging.info('Customized Ctrl-D key command: %s' %
253 self._customized_ctrl_d_key_command)
254 if 'enter_cmd' in args:
255 self._customized_enter_key_command = args['enter_cmd']
256 logging.info('Customized Enter key command: %s' %
257 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800258 if 'space_cmd' in args:
259 self._customized_space_key_command = args['space_cmd']
260 logging.info('Customized Space key command: %s' %
261 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800262 if 'rec_reboot_cmd' in args:
263 self._customized_rec_reboot_command = args['rec_reboot_cmd']
264 logging.info('Customized recovery reboot command: %s' %
265 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800266 if 'image' in args:
267 self._install_image_path = args['image']
268 logging.info('Install Chrome OS test image path: %s' %
269 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800270 if 'firmware_update' in args and args['firmware_update'].lower() \
271 not in ('0', 'false', 'no'):
272 if self._install_image_path:
273 self._firmware_update = True
274 logging.info('Also update firmware after installing.')
275 else:
276 logging.warning('Firmware update will not not performed '
277 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800278
279 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
280 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800281 if use_faft:
282 self.client_attr = FAFTClientAttribute(
283 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800284
Gediminas Ramanauskas3297d4f2012-09-10 15:30:10 -0700285 # Setting up key matrix mapping
286 self.servo.set_key_matrix(self.client_attr.key_matrix_layout)
287
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800288
289 def setup(self):
290 """Autotest setup function."""
291 super(FAFTSequence, self).setup()
292 if not self._remote_infos['faft']['used']:
293 raise error.TestError('The use_faft flag should be enabled.')
294 self.register_faft_template({
295 'state_checker': (None),
296 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800297 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800298 'firmware_action': (None)
299 })
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800300 self.clear_set_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON |
301 self.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
302 self.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800303 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800304 self.install_test_image(self._install_image_path,
305 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800306
307
308 def cleanup(self):
309 """Autotest cleanup function."""
310 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800311 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800312 super(FAFTSequence, self).cleanup()
313
314
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800315 def reset_client(self):
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800316 """Reset client, if necessary.
317
318 This method is called when the client is not responsive. It may be
319 caused by the following cases:
320 - network flaky (can be recovered by replugging the Ethernet);
321 - halt on a firmware screen without timeout, e.g. REC_INSERT screen;
322 - corrupted firmware;
323 - corrutped OS image.
324 """
325 # DUT works fine, done.
326 if self._ping_test(self._client.ip, timeout=5):
327 return
328
329 # TODO(waihong@chromium.org): Implement replugging the Ethernet in the
330 # first reset item.
331
332 # DUT may halt on a firmware screen. Try cold reboot.
333 logging.info('Try cold reboot...')
334 self.cold_reboot()
335 try:
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800336 self.wait_for_client()
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +0800337 return
338 except AssertionError:
339 pass
340
341 # DUT may be broken by a corrupted firmware. Restore firmware.
342 # We assume the recovery boot still works fine. Since the recovery
343 # code is in RO region and all FAFT tests don't change the RO region
344 # except GBB.
345 if self.is_firmware_saved():
346 self.ensure_client_in_recovery()
347 logging.info('Try restore the original firmware...')
348 if self.is_firmware_changed():
349 try:
350 self.restore_firmware()
351 return
352 except AssertionError:
353 logging.info('Restoring firmware doesn\'t help.')
354
355 # DUT may be broken by a corrupted OS image. Restore OS image.
356 self.ensure_client_in_recovery()
357 logging.info('Try restore the OS image...')
358 self.faft_client.run_shell_command('chromeos-install --yes')
359 self.sync_and_warm_reboot()
360 self.wait_for_client_offline()
361 try:
362 self.wait_for_client(install_deps=True)
363 logging.info('Successfully restore OS image.')
364 return
365 except AssertionError:
366 logging.info('Restoring OS image doesn\'t help.')
367
368
369 def ensure_client_in_recovery(self):
370 """Ensure client in recovery boot; reboot into it if necessary.
371
372 Raises:
373 error.TestError: if failed to boot the USB image.
374 """
375 # DUT works fine and is already in recovery boot, done.
376 if self._ping_test(self._client.ip, timeout=5):
377 if self.crossystem_checker({'mainfw_type': 'recovery'}):
378 return
379
380 logging.info('Try boot into USB image...')
381 self.servo.enable_usb_hub(host=True)
382 self.enable_rec_mode_and_reboot()
383 self.wait_fw_screen_and_plug_usb()
384 try:
385 self.wait_for_client(install_deps=True)
386 except AssertionError:
387 raise error.TestError('Failed to boot the USB image.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +0800388
389
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800390 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800391 """Assert an USB disk plugged-in on servo and a test image inside.
392
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800393 Args:
394 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
395 If None, it is detected automatically.
396
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800397 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800398 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800399 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800400 if usb_dev:
401 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
402 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700403 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800404 usb_dev = self.servo.probe_host_usb_dev()
405 if not usb_dev:
406 raise error.TestError(
407 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800408
409 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800410 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800411 code = utils.system(
412 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
413 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800414 utils.system('sudo umount %s' % tmp_dir)
415 os.removedirs(tmp_dir)
416 if code != 0:
417 raise error.TestError(
418 'The image in the USB disk should be a test image.')
419
420
Simran Basi741b5d42012-05-18 11:27:15 -0700421 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800422 """Install the test image specied by the path onto the USB and DUT disk.
423
424 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500425 recovery mode. Then runs 'chromeos-install' (and possible
426 chromeos-firmwareupdate') to install it to DUT disk.
427
428 Sample command line:
429
430 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
431 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
432 server/site_tests/firmware_XXXX/control
433
434 This test requires an automated recovery to occur while simulating
435 inserting and removing the usb key from the servo. To allow this the
436 following hardware setup is required:
437 1. servo2 board connected via servoflex.
438 2. USB key inserted in the servo2.
439 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
440 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800441
442 Args:
443 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800444 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800445 """
446 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
447 image_path)
448 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800449
Mike Truty49153d82012-08-21 22:27:30 -0500450 # Reuse the servo method that uses the servo USB key to install
451 # the test image.
452 self.servo.image_to_servo_usb(image_path)
453
454 # DUT is powered off while imaging servo USB.
455 # Now turn it on.
456 self.servo.power_short_press()
457 self.wait_for_client()
458 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
459
460 install_cmd = 'chromeos-install --yes'
461 if firmware_update:
462 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
463
464 self.register_faft_sequence((
465 { # Step 1, request recovery boot
466 'state_checker': (self.crossystem_checker, {
467 'mainfw_type': ('developer', 'normal'),
468 }),
469 'userspace_action': self.faft_client.request_recovery_boot,
470 'firmware_action': self.wait_fw_screen_and_plug_usb,
471 'install_deps_after_boot': True,
472 },
473 { # Step 2, expected recovery boot
474 'state_checker': (self.crossystem_checker, {
475 'mainfw_type': 'recovery',
476 'recovery_reason' : self.RECOVERY_REASON['US_TEST'],
477 }),
478 'userspace_action': (self.faft_client.run_shell_command,
479 install_cmd),
480 'reboot_action': self.cold_reboot,
481 'install_deps_after_boot': True,
482 },
483 { # Step 3, expected normal or developer boot (not recovery)
484 'state_checker': (self.crossystem_checker, {
485 'mainfw_type': ('developer', 'normal')
486 }),
487 },
488 ))
489 self.run_faft_sequence()
490 # 'Unplug' any USB keys in the servo from the dut.
491 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800492
493
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800494 def clear_set_gbb_flags(self, clear_mask, set_mask):
495 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800496
497 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800498 clear_mask: A mask of flags to be cleared.
499 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800500 """
501 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800502 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
503
504 if (gbb_flags != new_flags):
505 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
506 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800507 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800508 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800509 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800510 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800511 if ((gbb_flags ^ new_flags) & self.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800512 self.run_faft_step({
513 'firmware_action': self.wait_fw_screen_and_ctrl_d,
514 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800515
516
Vic Yangb4e3e742012-06-02 13:17:38 +0800517 def _open_uart_pty(self):
518 """Open UART pty and spawn pexpect object.
519
520 Returns:
521 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
522 child is a fdpexpect object tied to it.
523 """
524 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
525 child = fdpexpect.fdspawn(fd)
526 return (fd, child)
527
528
529 def _flush_uart_pty(self, child):
530 """Flush UART output to prevent previous pending message interferring.
531
532 Args:
533 child: The fdpexpect object tied to UART pty.
534 """
535 child.sendline("")
536 while True:
537 try:
538 child.expect(".", timeout=0.01)
539 except pexpect.TIMEOUT:
540 break
541
542
543 def _uart_send(self, child, line):
544 """Flush and send command through UART.
545
546 Args:
547 child: The pexpect object tied to UART pty.
548 line: String to send through UART.
549
550 Raises:
551 error.TestFail: Raised when writing to UART fails.
552 """
553 logging.info("Sending UART command: %s" % line)
554 self._flush_uart_pty(child)
555 if child.sendline(line) != len(line) + 1:
556 raise error.TestFail("Failed to send UART command.")
557
558
559 def send_uart_command(self, command):
560 """Send command through UART.
561
562 This function open UART pty when called, and then command is sent
563 through UART.
564
565 Args:
566 command: The command string to send.
567
568 Raises:
569 error.TestFail: Raised when writing to UART fails.
570 """
571 (fd, child) = self._open_uart_pty()
572 try:
573 self._uart_send(child, command)
574 finally:
575 os.close(fd)
576
577
578 def send_uart_command_get_output(self, command, regex_list, timeout=1):
579 """Send command through UART and wait for response.
580
581 This function waits for response message matching regular expressions.
582
583 Args:
584 command: The command sent.
585 regex_list: List of regular expressions used to match response message.
586 Note, list must be ordered.
587
588 Returns:
589 List of match objects of response message.
590
591 Raises:
592 error.TestFail: If timed out waiting for EC response.
593 """
594 if not isinstance(regex_list, list):
595 regex_list = [regex_list]
596 result_list = []
597 (fd, child) = self._open_uart_pty()
598 try:
599 self._uart_send(child, command)
600 for regex in regex_list:
601 child.expect(regex, timeout=timeout)
602 result_list.append(child.match)
603 except pexpect.TIMEOUT:
604 raise error.TestFail("Timeout waiting for UART response.")
605 finally:
606 os.close(fd)
607 return result_list
608
609
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800610 def check_ec_capability(self, required_cap=[], suppress_warning=False):
Vic Yang4d72cb62012-07-24 11:51:09 +0800611 """Check if current platform has required EC capabilities.
612
613 Args:
614 required_cap: A list containing required EC capabilities. Pass in
615 None to only check for presence of Chrome EC.
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800616 suppress_warning: True to suppress any warning messages.
Vic Yang4d72cb62012-07-24 11:51:09 +0800617
618 Returns:
619 True if requirements are met. Otherwise, False.
620 """
621 if not self.client_attr.chrome_ec:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800622 if not suppress_warning:
623 logging.warn('Requires Chrome EC to run this test.')
Vic Yang4d72cb62012-07-24 11:51:09 +0800624 return False
625
626 for cap in required_cap:
627 if cap not in self.client_attr.ec_capability:
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800628 if not suppress_warning:
629 logging.warn('Requires EC capability "%s" to run this '
630 'test.' % cap)
Vic Yang4d72cb62012-07-24 11:51:09 +0800631 return False
632
633 return True
634
635
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800636 def _parse_crossystem_output(self, lines):
637 """Parse the crossystem output into a dict.
638
639 Args:
640 lines: The list of crossystem output strings.
641
642 Returns:
643 A dict which contains the crossystem keys/values.
644
645 Raises:
646 error.TestError: If wrong format in crossystem output.
647
648 >>> seq = FAFTSequence()
649 >>> seq._parse_crossystem_output([ \
650 "arch = x86 # Platform architecture", \
651 "cros_debug = 1 # OS should allow debug", \
652 ])
653 {'cros_debug': '1', 'arch': 'x86'}
654 >>> seq._parse_crossystem_output([ \
655 "arch=x86", \
656 ])
657 Traceback (most recent call last):
658 ...
659 TestError: Failed to parse crossystem output: arch=x86
660 >>> seq._parse_crossystem_output([ \
661 "arch = x86 # Platform architecture", \
662 "arch = arm # Platform architecture", \
663 ])
664 Traceback (most recent call last):
665 ...
666 TestError: Duplicated crossystem key: arch
667 """
668 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
669 parsed_list = {}
670 for line in lines:
671 matched = re.match(pattern, line.strip())
672 if not matched:
673 raise error.TestError("Failed to parse crossystem output: %s"
674 % line)
675 (name, value) = (matched.group(1), matched.group(2))
676 if name in parsed_list:
677 raise error.TestError("Duplicated crossystem key: %s" % name)
678 parsed_list[name] = value
679 return parsed_list
680
681
682 def crossystem_checker(self, expected_dict):
683 """Check the crossystem values matched.
684
685 Given an expect_dict which describes the expected crossystem values,
686 this function check the current crossystem values are matched or not.
687
688 Args:
689 expected_dict: A dict which contains the expected values.
690
691 Returns:
692 True if the crossystem value matched; otherwise, False.
693 """
694 lines = self.faft_client.run_shell_command_get_output('crossystem')
695 got_dict = self._parse_crossystem_output(lines)
696 for key in expected_dict:
697 if key not in got_dict:
698 logging.info('Expected key "%s" not in crossystem result' % key)
699 return False
700 if isinstance(expected_dict[key], str):
701 if got_dict[key] != expected_dict[key]:
702 logging.info("Expected '%s' value '%s' but got '%s'" %
703 (key, expected_dict[key], got_dict[key]))
704 return False
705 elif isinstance(expected_dict[key], tuple):
706 # Expected value is a tuple of possible actual values.
707 if got_dict[key] not in expected_dict[key]:
708 logging.info("Expected '%s' values %s but got '%s'" %
709 (key, str(expected_dict[key]), got_dict[key]))
710 return False
711 else:
712 logging.info("The expected_dict is neither a str nor a dict.")
713 return False
714 return True
715
716
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800717 def vdat_flags_checker(self, mask, value):
718 """Check the flags from VbSharedData matched.
719
720 This function checks the masked flags from VbSharedData using crossystem
721 are matched the given value.
722
723 Args:
724 mask: A bitmask of flags to be matched.
725 value: An expected value.
726
727 Returns:
728 True if the flags matched; otherwise, False.
729 """
730 lines = self.faft_client.run_shell_command_get_output(
731 'crossystem vdat_flags')
732 vdat_flags = int(lines[0], 16)
733 if vdat_flags & mask != value:
734 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
735 (value, mask, vdat_flags))
736 return False
737 return True
738
739
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800740 def ro_normal_checker(self, expected_fw=None, twostop=False):
741 """Check the current boot uses RO boot.
742
743 Args:
744 expected_fw: A string of expected firmware, 'A', 'B', or
745 None if don't care.
746 twostop: True to expect a TwoStop boot; False to expect a RO boot.
747
748 Returns:
749 True if the currect boot firmware matched and used RO boot;
750 otherwise, False.
751 """
752 crossystem_dict = {'tried_fwb': '0'}
753 if expected_fw:
754 crossystem_dict['mainfw_act'] = expected_fw.upper()
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +0800755 if self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800756 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
757
758 return (self.vdat_flags_checker(
759 self.VDAT_FLAG_LF_USE_RO_NORMAL,
760 0 if twostop else self.VDAT_FLAG_LF_USE_RO_NORMAL) and
761 self.crossystem_checker(crossystem_dict))
762
763
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800764 def root_part_checker(self, expected_part):
765 """Check the partition number of the root device matched.
766
767 Args:
768 expected_part: A string containing the number of the expected root
769 partition.
770
771 Returns:
772 True if the currect root partition number matched; otherwise, False.
773 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800774 part = self.faft_client.get_root_part()[-1]
775 if self.ROOTFS_MAP[expected_part] != part:
776 logging.info("Expected root part %s but got %s" %
777 (self.ROOTFS_MAP[expected_part], part))
778 return False
779 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800780
781
Vic Yang59cac9c2012-05-21 15:28:42 +0800782 def ec_act_copy_checker(self, expected_copy):
783 """Check the EC running firmware copy matches.
784
785 Args:
786 expected_copy: A string containing 'RO', 'A', or 'B' indicating
787 the expected copy of EC running firmware.
788
789 Returns:
790 True if the current EC running copy matches; otherwise, False.
791 """
792 lines = self.faft_client.run_shell_command_get_output('ectool version')
793 pattern = re.compile("Firmware copy: (.*)")
794 for line in lines:
795 matched = pattern.match(line)
796 if matched and matched.group(1) == expected_copy:
797 return True
798 return False
799
800
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800801 def check_root_part_on_non_recovery(self, part):
802 """Check the partition number of root device and on normal/dev boot.
803
804 Returns:
805 True if the root device matched and on normal/dev boot;
806 otherwise, False.
807 """
808 return self.root_part_checker(part) and \
809 self.crossystem_checker({
810 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800811 })
812
813
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800814 def _join_part(self, dev, part):
815 """Return a concatenated string of device and partition number.
816
817 Args:
818 dev: A string of device, e.g.'/dev/sda'.
819 part: A string of partition number, e.g.'3'.
820
821 Returns:
822 A concatenated string of device and partition number, e.g.'/dev/sda3'.
823
824 >>> seq = FAFTSequence()
825 >>> seq._join_part('/dev/sda', '3')
826 '/dev/sda3'
827 >>> seq._join_part('/dev/mmcblk0', '2')
828 '/dev/mmcblk0p2'
829 """
830 if 'mmcblk' in dev:
831 return dev + 'p' + part
832 else:
833 return dev + part
834
835
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800836 def copy_kernel_and_rootfs(self, from_part, to_part):
837 """Copy kernel and rootfs from from_part to to_part.
838
839 Args:
840 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800841 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800842 """
843 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800844 logging.info('Copying kernel from %s to %s. Please wait...' %
845 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800846 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800847 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
848 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
849 logging.info('Copying rootfs from %s to %s. Please wait...' %
850 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800851 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800852 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
853 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800854
855
856 def ensure_kernel_boot(self, part):
857 """Ensure the request kernel boot.
858
859 If not, it duplicates the current kernel to the requested kernel
860 and sets the requested higher priority to ensure it boot.
861
862 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800863 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800864 """
865 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800866 if self.faft_client.diff_kernel_a_b():
867 self.copy_kernel_and_rootfs(
868 from_part=self.OTHER_KERNEL_MAP[part],
869 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800870 self.run_faft_step({
871 'userspace_action': (self.reset_and_prioritize_kernel, part),
872 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800873
874
Vic Yang416f2032012-08-28 10:18:03 +0800875 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800876 """Set hardware write protect pin.
877
878 Args:
879 enable: True if asserting write protect pin. Otherwise, False.
880 """
881 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
882 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800883 self.servo.set('fw_wp', 'on' if enabled else 'off')
884
885
886 def set_EC_write_protect_and_reboot(self, enabled):
887 """Set EC write protect status and reboot to take effect.
888
889 EC write protect is only activated if both hardware write protect pin
890 is asserted and software write protect flag is set. Also, a reboot is
891 required for write protect to take effect.
892
893 Since the software write protect flag cannot be unset if hardware write
894 protect pin is asserted, we need to deasserted the pin first if we are
895 deactivating write protect. Similarly, a reboot is required before we
896 can modify the software flag.
897
898 This method asserts/deasserts hardware write protect pin first, and
899 set corresponding EC software write protect flag.
900
901 Args:
902 enable: True if activating EC write protect. Otherwise, False.
903 """
904 self.set_hardware_write_protect(enabled)
905 if enabled:
906 # Set write protect flag and reboot to take effect.
907 self.send_uart_command("flashwp enable")
908 self.sync_and_ec_reboot()
909 else:
910 # Reboot after deasserting hardware write protect pin to deactivate
911 # write protect. And then remove software write protect flag.
912 self.sync_and_ec_reboot()
913 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800914
915
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800916 def send_ctrl_d_to_dut(self):
917 """Send Ctrl-D key to DUT."""
918 if self._customized_ctrl_d_key_command:
919 logging.info('running the customized Ctrl-D key command')
920 os.system(self._customized_ctrl_d_key_command)
921 else:
922 self.servo.ctrl_d()
923
924
925 def send_enter_to_dut(self):
926 """Send Enter key to DUT."""
927 if self._customized_enter_key_command:
928 logging.info('running the customized Enter key command')
929 os.system(self._customized_enter_key_command)
930 else:
931 self.servo.enter_key()
932
933
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800934 def send_space_to_dut(self):
935 """Send Space key to DUT."""
936 if self._customized_space_key_command:
937 logging.info('running the customized Space key command')
938 os.system(self._customized_space_key_command)
939 else:
940 # Send the alternative key combinaton of space key to servo.
941 self.servo.ctrl_refresh_key()
942
943
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800944 def wait_fw_screen_and_ctrl_d(self):
945 """Wait for firmware warning screen and press Ctrl-D."""
946 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800947 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800948
949
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800950 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
951 """Wait for firmware warning screen and trigger recovery boot."""
952 time.sleep(self.FIRMWARE_SCREEN_DELAY)
953 self.send_enter_to_dut()
954
955 # For Alex/ZGB, there is a dev warning screen in text mode.
956 # Skip it by pressing Ctrl-D.
957 if need_dev_transition:
958 time.sleep(self.TEXT_SCREEN_DELAY)
959 self.send_ctrl_d_to_dut()
960
961
Mike Truty49153d82012-08-21 22:27:30 -0500962 def wait_fw_screen_and_unplug_usb(self):
963 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800964 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800965 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
966 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500967
968
969 def wait_fw_screen_and_plug_usb(self):
970 """Wait for firmware warning screen and then unplug and plug the USB."""
971 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800972 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
973
974
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800975 def wait_fw_screen_and_press_power(self):
976 """Wait for firmware warning screen and press power button."""
977 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800978 # While the firmware screen, the power button probing loop sleeps
979 # 0.25 second on every scan. Use the normal delay (1.2 second) for
980 # power press.
981 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800982
983
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800984 def wait_longer_fw_screen_and_press_power(self):
985 """Wait for firmware screen without timeout and press power button."""
986 time.sleep(self.DEV_SCREEN_TIMEOUT)
987 self.wait_fw_screen_and_press_power()
988
989
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800990 def wait_fw_screen_and_close_lid(self):
991 """Wait for firmware warning screen and close lid."""
992 time.sleep(self.FIRMWARE_SCREEN_DELAY)
993 self.servo.lid_close()
994
995
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800996 def wait_longer_fw_screen_and_close_lid(self):
997 """Wait for firmware screen without timeout and close lid."""
998 time.sleep(self.FIRMWARE_SCREEN_DELAY)
999 self.wait_fw_screen_and_close_lid()
1000
1001
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001002 def setup_tried_fwb(self, tried_fwb):
1003 """Setup for fw B tried state.
1004
1005 It makes sure the system in the requested fw B tried state. If not, it
1006 tries to do so.
1007
1008 Args:
1009 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
1010 """
1011 if tried_fwb:
1012 if not self.crossystem_checker({'tried_fwb': '1'}):
1013 logging.info(
1014 'Firmware is not booted with tried_fwb. Reboot into it.')
1015 self.run_faft_step({
1016 'userspace_action': self.faft_client.set_try_fw_b,
1017 })
1018 else:
1019 if not self.crossystem_checker({'tried_fwb': '0'}):
1020 logging.info(
1021 'Firmware is booted with tried_fwb. Reboot to clear.')
1022 self.run_faft_step({})
1023
1024
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001025 def enable_rec_mode_and_reboot(self):
1026 """Switch to rec mode and reboot.
1027
1028 This method emulates the behavior of the old physical recovery switch,
1029 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
1030 recovery mode, i.e. just press Power + Esc + Refresh.
1031 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001032 if self._customized_rec_reboot_command:
1033 logging.info('running the customized rec reboot command')
1034 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001035 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +08001036 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +08001037 self.servo.set('cold_reset', 'on')
1038 time.sleep(self.COLD_RESET_DELAY)
1039 self.servo.set('cold_reset', 'off')
1040 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +08001041 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +08001042 time.sleep(self.EC_BOOT_DELAY)
1043 self.send_uart_command("hostevent set 0x4000")
1044 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +08001045 else:
1046 self.servo.enable_recovery_mode()
1047 self.cold_reboot()
1048 time.sleep(self.EC_REBOOT_DELAY)
1049 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001050
1051
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001052 def enable_dev_mode_and_reboot(self):
1053 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001054 if self.client_attr.keyboard_dev:
1055 self.enable_keyboard_dev_mode()
1056 else:
1057 self.servo.enable_development_mode()
1058 self.faft_client.run_shell_command(
1059 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001060
1061
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +08001062 def enable_normal_mode_and_reboot(self):
1063 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +08001064 if self.client_attr.keyboard_dev:
1065 self.disable_keyboard_dev_mode()
1066 else:
1067 self.servo.disable_development_mode()
1068 self.faft_client.run_shell_command(
1069 'chromeos-firmwareupdate --mode tonormal && reboot')
1070
1071
1072 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
1073 """Wait for firmware screen and then switch into or out of dev mode.
1074
1075 Args:
1076 dev: True if switching into dev mode. Otherwise, False.
1077 """
1078 time.sleep(self.FIRMWARE_SCREEN_DELAY)
1079 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001080 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001081 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001082 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +08001083 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +08001084 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +08001085
1086
1087 def enable_keyboard_dev_mode(self):
1088 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001089 # Plug out USB disk for preventing recovery boot without warning
1090 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001091 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001092 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001093 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001094 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001095
1096
1097 def disable_keyboard_dev_mode(self):
1098 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001099 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001100 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001101 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001102 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001103 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001104
1105
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001106 def setup_dev_mode(self, dev_mode):
1107 """Setup for development mode.
1108
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001109 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001110 tries to do so.
1111
1112 Args:
1113 dev_mode: True if requested in dev mode; False if normal mode.
1114 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001115 # Change the default firmware_action for dev mode passing the fw screen.
1116 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001117 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1118 else None),
1119 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001120 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001121 if (not self.client_attr.keyboard_dev and
1122 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001123 logging.info('Dev switch is not on. Now switch it on.')
1124 self.servo.enable_development_mode()
1125 if not self.crossystem_checker({'devsw_boot': '1',
1126 'mainfw_type': 'developer'}):
1127 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001128 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001129 'userspace_action': None if self.client_attr.keyboard_dev
1130 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001131 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001132 'reboot_action': self.enable_keyboard_dev_mode if
1133 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001134 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001135 else:
Vic Yange7553162012-06-20 16:20:47 +08001136 if (not self.client_attr.keyboard_dev and
1137 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001138 logging.info('Dev switch is not off. Now switch it off.')
1139 self.servo.disable_development_mode()
1140 if not self.crossystem_checker({'devsw_boot': '0',
1141 'mainfw_type': 'normal'}):
1142 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001143 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001144 'userspace_action': None if self.client_attr.keyboard_dev
1145 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001146 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001147 'reboot_action': self.disable_keyboard_dev_mode if
1148 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001149 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001150
1151
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001152 def setup_kernel(self, part):
1153 """Setup for kernel test.
1154
1155 It makes sure both kernel A and B bootable and the current boot is
1156 the requested kernel part.
1157
1158 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001159 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001160 """
1161 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001162 if self.faft_client.diff_kernel_a_b():
1163 self.copy_kernel_and_rootfs(from_part=part,
1164 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001165 self.reset_and_prioritize_kernel(part)
1166
1167
1168 def reset_and_prioritize_kernel(self, part):
1169 """Make the requested partition highest priority.
1170
1171 This function also reset kerenl A and B to bootable.
1172
1173 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001174 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001175 """
1176 root_dev = self.faft_client.get_root_dev()
1177 # Reset kernel A and B to bootable.
1178 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1179 (self.KERNEL_MAP['a'], root_dev))
1180 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1181 (self.KERNEL_MAP['b'], root_dev))
1182 # Set kernel part highest priority.
1183 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1184 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001185 # Safer to sync and wait until the cgpt status written to the disk.
1186 self.faft_client.run_shell_command('sync')
1187 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001188
1189
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001190 def warm_reboot(self):
1191 """Request a warm reboot.
1192
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001193 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001194 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001195 # Use cold reset if the warm reset is broken.
1196 if self.client_attr.broken_warm_reset:
Gediminas Ramanauskase021e152012-09-04 19:10:59 -07001197 logging.info('broken_warm_reset is True. Cold rebooting instead.')
1198 self.cold_reboot()
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001199 else:
1200 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001201
1202
1203 def cold_reboot(self):
1204 """Request a cold reboot.
1205
1206 A wrapper for underlying servo cold reset.
1207 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001208 if self.client_attr.platform == 'Parrot':
1209 self.servo.set('pwr_button', 'press')
1210 self.servo.set('cold_reset', 'on')
1211 self.servo.set('cold_reset', 'off')
1212 time.sleep(self.POWER_BTN_DELAY)
1213 self.servo.set('pwr_button', 'release')
Tom Wai-Hong Tamb8a91392012-09-27 10:45:32 +08001214 elif self.check_ec_capability(suppress_warning=True):
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001215 # We don't use servo.cold_reset() here because software sync is
1216 # not yet finished, and device may or may not come up after cold
1217 # reset. Pressing power button before firmware comes up solves this.
1218 #
1219 # The correct behavior should be (not work now):
1220 # - If rebooting EC with rec mode on, power on AP and it boots
1221 # into recovery mode.
1222 # - If rebooting EC with rec mode off, power on AP for software
1223 # sync. Then AP checks if lid open or not. If lid open, continue;
1224 # otherwise, shut AP down and need servo for a power button
1225 # press.
1226 self.servo.set('cold_reset', 'on')
1227 self.servo.set('cold_reset', 'off')
1228 time.sleep(self.POWER_BTN_DELAY)
1229 self.servo.power_short_press()
1230 else:
1231 self.servo.cold_reset()
1232
1233
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001234 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001235 """Request the client sync and do a warm reboot.
1236
1237 This is the default reboot action on FAFT.
1238 """
1239 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001240 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001241 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001242
1243
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001244 def sync_and_cold_reboot(self):
1245 """Request the client sync and do a cold reboot.
1246
1247 This reboot action is used to reset EC for recovery mode.
1248 """
1249 self.faft_client.run_shell_command('sync')
1250 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001251 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001252
1253
Vic Yangaeb10392012-08-28 09:25:09 +08001254 def sync_and_ec_reboot(self, args=''):
1255 """Request the client sync and do a EC triggered reboot.
1256
1257 Args:
1258 args: Arguments passed to "ectool reboot_ec". Including:
1259 RO: jump to EC RO firmware.
1260 RW: jump to EC RW firmware.
1261 cold: Cold/hard reboot.
1262 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001263 self.faft_client.run_shell_command('sync')
1264 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001265 # Since EC reboot happens immediately, delay before actual reboot to
1266 # allow FAFT client returning.
1267 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1268 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001269 time.sleep(self.EC_REBOOT_DELAY)
1270 self.check_lid_and_power_on()
1271
1272
Tom Wai-Hong Tamc8f2ca02012-09-14 11:18:01 +08001273 def full_power_off_and_on(self):
1274 """Shutdown the device by pressing power button and power on again."""
1275 # Press power button to trigger Chrome OS normal shutdown process.
1276 self.servo.power_normal_press()
1277 time.sleep(self.FULL_POWER_OFF_DELAY)
1278 # Short press power button to boot DUT again.
1279 self.servo.power_short_press()
1280
1281
Vic Yangf86728a2012-07-30 10:44:07 +08001282 def check_lid_and_power_on(self):
1283 """
1284 On devices with EC software sync, system powers on after EC reboots if
1285 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1286 This method checks lid switch state and presses power button if
1287 necessary.
1288 """
1289 if self.servo.get("lid_open") == "no":
1290 time.sleep(self.SOFTWARE_SYNC_DELAY)
1291 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001292
1293
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001294 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1295 """Modify the kernel header magic in USB stick.
1296
1297 The kernel header magic is the first 8-byte of kernel partition.
1298 We modify it to make it fail on kernel verification check.
1299
1300 Args:
1301 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1302 from_magic: A string of magic which we change it from.
1303 to_magic: A string of magic which we change it to.
1304
1305 Raises:
1306 error.TestError: if failed to change magic.
1307 """
1308 assert len(from_magic) == 8
1309 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001310 # USB image only contains one kernel.
1311 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001312 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1313 current_magic = utils.system_output(read_cmd)
1314 if current_magic == to_magic:
1315 logging.info("The kernel magic is already %s." % current_magic)
1316 return
1317 if current_magic != from_magic:
1318 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1319
1320 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1321 (from_magic, to_magic))
1322 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1323 " 2>/dev/null" % (to_magic, kernel_part))
1324 utils.system(write_cmd)
1325
1326 if utils.system_output(read_cmd) != to_magic:
1327 raise error.TestError("Failed to write new magic.")
1328
1329
1330 def corrupt_usb_kernel(self, usb_dev):
1331 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1332
1333 Args:
1334 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1335 """
1336 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1337 self.CORRUPTED_MAGIC)
1338
1339
1340 def restore_usb_kernel(self, usb_dev):
1341 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1342
1343 Args:
1344 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1345 """
1346 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1347 self.CHROMEOS_MAGIC)
1348
1349
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001350 def _call_action(self, action_tuple, check_status=False):
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001351 """Call the action function with/without arguments.
1352
1353 Args:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001354 action_tuple: A function, or a tuple (function, args, error_msg),
1355 in which, args and error_msg are optional. args is
1356 either a value or a tuple if multiple arguments.
1357 check_status: Check the return value of action function. If not
1358 succeed, raises a TestFail exception.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001359
1360 Returns:
1361 The result value of the action function.
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001362
1363 Raises:
1364 error.TestError: An error when the action function is not callable.
1365 error.TestFail: When check_status=True, action function not succeed.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001366 """
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001367 action = action_tuple
1368 args = ()
1369 error_msg = 'Not succeed'
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001370 if isinstance(action_tuple, tuple):
1371 action = action_tuple[0]
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001372 if len(action_tuple) >= 2:
1373 args = action_tuple[1]
1374 if not isinstance(args, tuple):
1375 args = (args,)
1376 if len(action_tuple) >= 3:
1377 error_msg = action
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001378
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001379 if action is None:
1380 return
1381
1382 if not callable(action):
1383 raise error.TestError('action is not callable!')
1384
1385 info_msg = 'calling %s' % str(action)
1386 if args:
1387 info_msg += ' with args %s' % str(args)
1388 logging.info(info_msg)
1389 ret = action(*args)
1390
1391 if check_status and not ret:
1392 raise error.TestFail('%s: %s returning %s' %
1393 (error_msg, info_msg, str(ret)))
1394 return ret
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001395
1396
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001397 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1398 post_power_action=None):
1399 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1400
1401 Args:
1402 shutdown_action: a function which makes DUT shutdown, like pressing
1403 power key.
1404 pre_power_action: a function which is called before next power on.
1405 post_power_action: a function which is called after next power on.
1406
1407 Raises:
1408 error.TestFail: if the shutdown_action() failed to turn DUT off.
1409 """
1410 self._call_action(shutdown_action)
1411 logging.info('Wait to ensure DUT shut down...')
1412 try:
1413 self.wait_for_client()
1414 raise error.TestFail(
1415 'Should shut the device down after calling %s.' %
1416 str(shutdown_action))
1417 except AssertionError:
1418 logging.info(
1419 'DUT is surely shutdown. We are going to power it on again...')
1420
1421 if pre_power_action:
1422 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001423 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001424 if post_power_action:
1425 self._call_action(post_power_action)
1426
1427
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001428 def register_faft_template(self, template):
1429 """Register FAFT template, the default FAFT_STEP of each step.
1430
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001431 Any missing field falls back to the original faft_template.
1432
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001433 Args:
1434 template: A FAFT_STEP dict.
1435 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001436 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001437
1438
1439 def register_faft_sequence(self, sequence):
1440 """Register FAFT sequence.
1441
1442 Args:
1443 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1444 """
1445 self._faft_sequence = sequence
1446
1447
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001448 def run_faft_step(self, step, no_reboot=False):
1449 """Run a single FAFT step.
1450
1451 Any missing field falls back to faft_template. An empty step means
1452 running the default faft_template.
1453
1454 Args:
1455 step: A FAFT_STEP dict.
1456 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001457
1458 Raises:
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001459 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001460 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001461 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1462 'firmware_action', 'install_deps_after_boot')
1463
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001464 test = {}
1465 test.update(self._faft_template)
1466 test.update(step)
1467
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001468 for key in test:
1469 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001470 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001471
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001472 if test['state_checker']:
Tom Wai-Hong Tamfc700b52012-09-13 21:33:52 +08001473 self._call_action(test['state_checker'], check_status=True)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001474
1475 self._call_action(test['userspace_action'])
1476
1477 # Don't run reboot_action and firmware_action if no_reboot is True.
1478 if not no_reboot:
1479 self._call_action(test['reboot_action'])
1480 self.wait_for_client_offline()
1481 self._call_action(test['firmware_action'])
1482
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001483 try:
1484 if 'install_deps_after_boot' in test:
1485 self.wait_for_client(
1486 install_deps=test['install_deps_after_boot'])
1487 else:
1488 self.wait_for_client()
1489 except AssertionError:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001490 logging.info('wait_for_client() timed out.')
Vic Yang8eaf5ad2012-09-13 14:05:37 +08001491 self.reset_client()
1492 raise
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001493
1494
1495 def run_faft_sequence(self):
1496 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001497 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001498 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001499 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001500 logging.info('======== Running FAFT sequence step %d ========' %
1501 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001502 # Don't reboot in the last step.
1503 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001504 index += 1
ctchang38ae4922012-09-03 17:01:16 +08001505
1506
ctchang38ae4922012-09-03 17:01:16 +08001507 def get_current_firmware_sha(self):
1508 """Get current firmware sha of body and vblock.
1509
1510 Returns:
1511 Current firmware sha follows the order (
1512 vblock_a_sha, body_a_sha, vblock_b_sha, body_b_sha)
1513 """
1514 current_firmware_sha = (self.faft_client.get_firmware_sig_sha('a'),
1515 self.faft_client.get_firmware_sha('a'),
1516 self.faft_client.get_firmware_sig_sha('b'),
1517 self.faft_client.get_firmware_sha('b'))
1518 return current_firmware_sha
1519
1520
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001521 def is_firmware_changed(self):
1522 """Check if the current firmware changed, by comparing its SHA.
ctchang38ae4922012-09-03 17:01:16 +08001523
1524 Returns:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001525 True if it is changed, otherwise Flase.
ctchang38ae4922012-09-03 17:01:16 +08001526 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001527 # Device may not be rebooted after test.
1528 self.faft_client.reload_firmware()
ctchang38ae4922012-09-03 17:01:16 +08001529
1530 current_sha = self.get_current_firmware_sha()
1531
1532 if current_sha == self._backup_firmware_sha:
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001533 return False
ctchang38ae4922012-09-03 17:01:16 +08001534 else:
ctchang38ae4922012-09-03 17:01:16 +08001535 corrupt_VBOOTA = (current_sha[0] != self._backup_firmware_sha[0])
1536 corrupt_FVMAIN = (current_sha[1] != self._backup_firmware_sha[1])
1537 corrupt_VBOOTB = (current_sha[2] != self._backup_firmware_sha[2])
1538 corrupt_FVMAINB = (current_sha[3] != self._backup_firmware_sha[3])
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001539 logging.info("Firmware changed:")
1540 logging.info('VBOOTA is changed: %s' % corrupt_VBOOTA)
1541 logging.info('VBOOTB is changed: %s' % corrupt_VBOOTB)
1542 logging.info('FVMAIN is changed: %s' % corrupt_FVMAIN)
1543 logging.info('FVMAINB is changed: %s' % corrupt_FVMAINB)
1544 return True
ctchang38ae4922012-09-03 17:01:16 +08001545
1546
1547 def backup_firmware(self, suffix='.original'):
1548 """Backup firmware to file, and then send it to host.
1549
1550 Args:
1551 suffix: a string appended to backup file name
1552 """
1553 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001554 self.faft_client.dump_firmware(os.path.join(remote_temp_dir, 'bios'))
1555 self._client.get_file(os.path.join(remote_temp_dir, 'bios'),
1556 os.path.join(self.resultsdir, 'bios' + suffix))
ctchang38ae4922012-09-03 17:01:16 +08001557
1558 self._backup_firmware_sha = self.get_current_firmware_sha()
1559 logging.info('Backup firmware stored in %s with suffix %s' % (
1560 self.resultsdir, suffix))
1561
1562
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001563 def is_firmware_saved(self):
1564 """Check if a firmware saved (called backup_firmware before).
1565
1566 Returns:
1567 True if the firmware is backuped; otherwise False.
1568 """
1569 return self._backup_firmware_sha != ()
1570
1571
ctchang38ae4922012-09-03 17:01:16 +08001572 def restore_firmware(self, suffix='.original'):
1573 """Restore firmware from host in resultsdir.
1574
1575 Args:
1576 suffix: a string appended to backup file name
1577 """
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001578 if not self.is_firmware_changed():
ctchang38ae4922012-09-03 17:01:16 +08001579 return
1580
1581 # Backup current corrupted firmware.
1582 self.backup_firmware(suffix='.corrupt')
1583
1584 # Restore firmware.
1585 remote_temp_dir = self.faft_client.create_temp_dir()
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001586 self._client.send_file(os.path.join(self.resultsdir, 'bios' + suffix),
1587 os.path.join(remote_temp_dir, 'bios'))
ctchang38ae4922012-09-03 17:01:16 +08001588
Chun-ting Chang9380c2c2012-10-05 17:31:05 +08001589 self.faft_client.write_firmware(os.path.join(remote_temp_dir, 'bios'))
Tom Wai-Hong Tame6232342012-09-24 16:18:01 +08001590 self.sync_and_warm_reboot()
1591 self.wait_for_client_offline()
1592 self.wait_for_client()
1593
ctchang38ae4922012-09-03 17:01:16 +08001594 logging.info('Successfully restore firmware.')