blob: beeefe8cd8ef85055bb8f24f5e2499c19ea5ce30 [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
106 # Delay between EC reboot and pressing power button
107 POWER_BTN_DELAY = 0.5
Vic Yangf86728a2012-07-30 10:44:07 +0800108 # Delay of EC software sync hash calculating time
109 SOFTWARE_SYNC_DELAY = 6
Vic Yanga7250662012-08-31 04:00:08 +0800110 # Delay between EC boot and ChromeEC console functional
111 EC_BOOT_DELAY = 0.5
112 # Duration of holding cold_reset to reset device
113 COLD_RESET_DELAY = 0.1
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800114
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800115 # The developer screen timeouts fit our spec.
116 DEV_SCREEN_TIMEOUT = 30
117
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800118 CHROMEOS_MAGIC = "CHROMEOS"
119 CORRUPTED_MAGIC = "CORRUPTD"
120
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800121 # Recovery reason codes, copied from:
122 # vboot_reference/firmware/lib/vboot_nvstorage.h
123 # vboot_reference/firmware/lib/vboot_struct.h
124 RECOVERY_REASON = {
125 # Recovery not requested
126 'NOT_REQUESTED': '0', # 0x00
127 # Recovery requested from legacy utility
128 'LEGACY': '1', # 0x01
129 # User manually requested recovery via recovery button
130 'RO_MANUAL': '2', # 0x02
131 # RW firmware failed signature check
132 'RO_INVALID_RW': '3', # 0x03
133 # S3 resume failed
134 'RO_S3_RESUME': '4', # 0x04
135 # TPM error in read-only firmware
136 'RO_TPM_ERROR': '5', # 0x05
137 # Shared data error in read-only firmware
138 'RO_SHARED_DATA': '6', # 0x06
139 # Test error from S3Resume()
140 'RO_TEST_S3': '7', # 0x07
141 # Test error from LoadFirmwareSetup()
142 'RO_TEST_LFS': '8', # 0x08
143 # Test error from LoadFirmware()
144 'RO_TEST_LF': '9', # 0x09
145 # RW firmware failed signature check
146 'RW_NOT_DONE': '16', # 0x10
147 'RW_DEV_MISMATCH': '17', # 0x11
148 'RW_REC_MISMATCH': '18', # 0x12
149 'RW_VERIFY_KEYBLOCK': '19', # 0x13
150 'RW_KEY_ROLLBACK': '20', # 0x14
151 'RW_DATA_KEY_PARSE': '21', # 0x15
152 'RW_VERIFY_PREAMBLE': '22', # 0x16
153 'RW_FW_ROLLBACK': '23', # 0x17
154 'RW_HEADER_VALID': '24', # 0x18
155 'RW_GET_FW_BODY': '25', # 0x19
156 'RW_HASH_WRONG_SIZE': '26', # 0x1A
157 'RW_VERIFY_BODY': '27', # 0x1B
158 'RW_VALID': '28', # 0x1C
159 # Read-only normal path requested by firmware preamble, but
160 # unsupported by firmware.
161 'RW_NO_RO_NORMAL': '29', # 0x1D
162 # Firmware boot failure outside of verified boot
163 'RO_FIRMWARE': '32', # 0x20
164 # Recovery mode TPM initialization requires a system reboot.
165 # The system was already in recovery mode for some other reason
166 # when this happened.
167 'RO_TPM_REBOOT': '33', # 0x21
168 # Unspecified/unknown error in read-only firmware
169 'RO_UNSPECIFIED': '63', # 0x3F
170 # User manually requested recovery by pressing a key at developer
171 # warning screen.
172 'RW_DEV_SCREEN': '65', # 0x41
173 # No OS kernel detected
174 'RW_NO_OS': '66', # 0x42
175 # OS kernel failed signature check
176 'RW_INVALID_OS': '67', # 0x43
177 # TPM error in rewritable firmware
178 'RW_TPM_ERROR': '68', # 0x44
179 # RW firmware in dev mode, but dev switch is off.
180 'RW_DEV_MISMATCH': '69', # 0x45
181 # Shared data error in rewritable firmware
182 'RW_SHARED_DATA': '70', # 0x46
183 # Test error from LoadKernel()
184 'RW_TEST_LK': '71', # 0x47
185 # No bootable disk found
186 'RW_NO_DISK': '72', # 0x48
187 # Unspecified/unknown error in rewritable firmware
188 'RW_UNSPECIFIED': '127', # 0x7F
189 # DM-verity error
190 'KE_DM_VERITY': '129', # 0x81
191 # Unspecified/unknown error in kernel
192 'KE_UNSPECIFIED': '191', # 0xBF
193 # Recovery mode test from user-mode
194 'US_TEST': '193', # 0xC1
195 # Unspecified/unknown error in user-mode
196 'US_UNSPECIFIED': '255', # 0xFF
197 }
198
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800199 # GBB flags
200 GBB_FLAG_DEV_SCREEN_SHORT_DELAY = 0x00000001
201 GBB_FLAG_LOAD_OPTION_ROMS = 0x00000002
202 GBB_FLAG_ENABLE_ALTERNATE_OS = 0x00000004
203 GBB_FLAG_FORCE_DEV_SWITCH_ON = 0x00000008
204 GBB_FLAG_FORCE_DEV_BOOT_USB = 0x00000010
205 GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK = 0x00000020
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800206 GBB_FLAG_ENTER_TRIGGERS_TONORM = 0x00000040
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800207
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800208 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800209 _faft_sequence = ()
210
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800211 _customized_ctrl_d_key_command = None
212 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800213 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800214 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800215 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800216 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800217
218
219 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
220 # Parse arguments from command line
221 args = {}
222 for arg in cmdline_args:
223 match = re.search("^(\w+)=(.+)", arg)
224 if match:
225 args[match.group(1)] = match.group(2)
226
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800227 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800228 if 'ctrl_d_cmd' in args:
229 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
230 logging.info('Customized Ctrl-D key command: %s' %
231 self._customized_ctrl_d_key_command)
232 if 'enter_cmd' in args:
233 self._customized_enter_key_command = args['enter_cmd']
234 logging.info('Customized Enter key command: %s' %
235 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800236 if 'space_cmd' in args:
237 self._customized_space_key_command = args['space_cmd']
238 logging.info('Customized Space key command: %s' %
239 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800240 if 'rec_reboot_cmd' in args:
241 self._customized_rec_reboot_command = args['rec_reboot_cmd']
242 logging.info('Customized recovery reboot command: %s' %
243 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800244 if 'image' in args:
245 self._install_image_path = args['image']
246 logging.info('Install Chrome OS test image path: %s' %
247 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800248 if 'firmware_update' in args and args['firmware_update'].lower() \
249 not in ('0', 'false', 'no'):
250 if self._install_image_path:
251 self._firmware_update = True
252 logging.info('Also update firmware after installing.')
253 else:
254 logging.warning('Firmware update will not not performed '
255 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800256
257 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
258 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800259 if use_faft:
260 self.client_attr = FAFTClientAttribute(
261 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800262
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800263
264 def setup(self):
265 """Autotest setup function."""
266 super(FAFTSequence, self).setup()
267 if not self._remote_infos['faft']['used']:
268 raise error.TestError('The use_faft flag should be enabled.')
269 self.register_faft_template({
270 'state_checker': (None),
271 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800272 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800273 'firmware_action': (None)
274 })
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800275 self.clear_set_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON |
276 self.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
277 self.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800278 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800279 self.install_test_image(self._install_image_path,
280 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800281
282
283 def cleanup(self):
284 """Autotest cleanup function."""
285 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800286 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800287 super(FAFTSequence, self).cleanup()
288
289
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800290 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800291 """Assert an USB disk plugged-in on servo and a test image inside.
292
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800293 Args:
294 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
295 If None, it is detected automatically.
296
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800297 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800298 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800299 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800300 if usb_dev:
301 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
302 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700303 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800304 usb_dev = self.servo.probe_host_usb_dev()
305 if not usb_dev:
306 raise error.TestError(
307 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800308
309 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800310 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800311 code = utils.system(
312 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
313 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800314 utils.system('sudo umount %s' % tmp_dir)
315 os.removedirs(tmp_dir)
316 if code != 0:
317 raise error.TestError(
318 'The image in the USB disk should be a test image.')
319
320
Simran Basi741b5d42012-05-18 11:27:15 -0700321 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800322 """Install the test image specied by the path onto the USB and DUT disk.
323
324 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500325 recovery mode. Then runs 'chromeos-install' (and possible
326 chromeos-firmwareupdate') to install it to DUT disk.
327
328 Sample command line:
329
330 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
331 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
332 server/site_tests/firmware_XXXX/control
333
334 This test requires an automated recovery to occur while simulating
335 inserting and removing the usb key from the servo. To allow this the
336 following hardware setup is required:
337 1. servo2 board connected via servoflex.
338 2. USB key inserted in the servo2.
339 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
340 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800341
342 Args:
343 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800344 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800345 """
346 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
347 image_path)
348 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800349
Mike Truty49153d82012-08-21 22:27:30 -0500350 # Reuse the servo method that uses the servo USB key to install
351 # the test image.
352 self.servo.image_to_servo_usb(image_path)
353
354 # DUT is powered off while imaging servo USB.
355 # Now turn it on.
356 self.servo.power_short_press()
357 self.wait_for_client()
358 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
359
360 install_cmd = 'chromeos-install --yes'
361 if firmware_update:
362 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
363
364 self.register_faft_sequence((
365 { # Step 1, request recovery boot
366 'state_checker': (self.crossystem_checker, {
367 'mainfw_type': ('developer', 'normal'),
368 }),
369 'userspace_action': self.faft_client.request_recovery_boot,
370 'firmware_action': self.wait_fw_screen_and_plug_usb,
371 'install_deps_after_boot': True,
372 },
373 { # Step 2, expected recovery boot
374 'state_checker': (self.crossystem_checker, {
375 'mainfw_type': 'recovery',
376 'recovery_reason' : self.RECOVERY_REASON['US_TEST'],
377 }),
378 'userspace_action': (self.faft_client.run_shell_command,
379 install_cmd),
380 'reboot_action': self.cold_reboot,
381 'install_deps_after_boot': True,
382 },
383 { # Step 3, expected normal or developer boot (not recovery)
384 'state_checker': (self.crossystem_checker, {
385 'mainfw_type': ('developer', 'normal')
386 }),
387 },
388 ))
389 self.run_faft_sequence()
390 # 'Unplug' any USB keys in the servo from the dut.
391 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800392
393
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800394 def clear_set_gbb_flags(self, clear_mask, set_mask):
395 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800396
397 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800398 clear_mask: A mask of flags to be cleared.
399 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800400 """
401 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800402 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
403
404 if (gbb_flags != new_flags):
405 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
406 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800407 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800408 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800409 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800410 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800411 if ((gbb_flags ^ new_flags) & self.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800412 self.run_faft_step({
413 'firmware_action': self.wait_fw_screen_and_ctrl_d,
414 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800415
416
Vic Yangb4e3e742012-06-02 13:17:38 +0800417 def _open_uart_pty(self):
418 """Open UART pty and spawn pexpect object.
419
420 Returns:
421 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
422 child is a fdpexpect object tied to it.
423 """
424 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
425 child = fdpexpect.fdspawn(fd)
426 return (fd, child)
427
428
429 def _flush_uart_pty(self, child):
430 """Flush UART output to prevent previous pending message interferring.
431
432 Args:
433 child: The fdpexpect object tied to UART pty.
434 """
435 child.sendline("")
436 while True:
437 try:
438 child.expect(".", timeout=0.01)
439 except pexpect.TIMEOUT:
440 break
441
442
443 def _uart_send(self, child, line):
444 """Flush and send command through UART.
445
446 Args:
447 child: The pexpect object tied to UART pty.
448 line: String to send through UART.
449
450 Raises:
451 error.TestFail: Raised when writing to UART fails.
452 """
453 logging.info("Sending UART command: %s" % line)
454 self._flush_uart_pty(child)
455 if child.sendline(line) != len(line) + 1:
456 raise error.TestFail("Failed to send UART command.")
457
458
459 def send_uart_command(self, command):
460 """Send command through UART.
461
462 This function open UART pty when called, and then command is sent
463 through UART.
464
465 Args:
466 command: The command string to send.
467
468 Raises:
469 error.TestFail: Raised when writing to UART fails.
470 """
471 (fd, child) = self._open_uart_pty()
472 try:
473 self._uart_send(child, command)
474 finally:
475 os.close(fd)
476
477
478 def send_uart_command_get_output(self, command, regex_list, timeout=1):
479 """Send command through UART and wait for response.
480
481 This function waits for response message matching regular expressions.
482
483 Args:
484 command: The command sent.
485 regex_list: List of regular expressions used to match response message.
486 Note, list must be ordered.
487
488 Returns:
489 List of match objects of response message.
490
491 Raises:
492 error.TestFail: If timed out waiting for EC response.
493 """
494 if not isinstance(regex_list, list):
495 regex_list = [regex_list]
496 result_list = []
497 (fd, child) = self._open_uart_pty()
498 try:
499 self._uart_send(child, command)
500 for regex in regex_list:
501 child.expect(regex, timeout=timeout)
502 result_list.append(child.match)
503 except pexpect.TIMEOUT:
504 raise error.TestFail("Timeout waiting for UART response.")
505 finally:
506 os.close(fd)
507 return result_list
508
509
Vic Yang4d72cb62012-07-24 11:51:09 +0800510 def check_ec_capability(self, required_cap=[]):
511 """Check if current platform has required EC capabilities.
512
513 Args:
514 required_cap: A list containing required EC capabilities. Pass in
515 None to only check for presence of Chrome EC.
516
517 Returns:
518 True if requirements are met. Otherwise, False.
519 """
520 if not self.client_attr.chrome_ec:
521 logging.warn('Requires Chrome EC to run this test.')
522 return False
523
524 for cap in required_cap:
525 if cap not in self.client_attr.ec_capability:
526 logging.warn('Requires EC capability "%s" to run this test.' %
527 cap)
528 return False
529
530 return True
531
532
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800533 def _parse_crossystem_output(self, lines):
534 """Parse the crossystem output into a dict.
535
536 Args:
537 lines: The list of crossystem output strings.
538
539 Returns:
540 A dict which contains the crossystem keys/values.
541
542 Raises:
543 error.TestError: If wrong format in crossystem output.
544
545 >>> seq = FAFTSequence()
546 >>> seq._parse_crossystem_output([ \
547 "arch = x86 # Platform architecture", \
548 "cros_debug = 1 # OS should allow debug", \
549 ])
550 {'cros_debug': '1', 'arch': 'x86'}
551 >>> seq._parse_crossystem_output([ \
552 "arch=x86", \
553 ])
554 Traceback (most recent call last):
555 ...
556 TestError: Failed to parse crossystem output: arch=x86
557 >>> seq._parse_crossystem_output([ \
558 "arch = x86 # Platform architecture", \
559 "arch = arm # Platform architecture", \
560 ])
561 Traceback (most recent call last):
562 ...
563 TestError: Duplicated crossystem key: arch
564 """
565 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
566 parsed_list = {}
567 for line in lines:
568 matched = re.match(pattern, line.strip())
569 if not matched:
570 raise error.TestError("Failed to parse crossystem output: %s"
571 % line)
572 (name, value) = (matched.group(1), matched.group(2))
573 if name in parsed_list:
574 raise error.TestError("Duplicated crossystem key: %s" % name)
575 parsed_list[name] = value
576 return parsed_list
577
578
579 def crossystem_checker(self, expected_dict):
580 """Check the crossystem values matched.
581
582 Given an expect_dict which describes the expected crossystem values,
583 this function check the current crossystem values are matched or not.
584
585 Args:
586 expected_dict: A dict which contains the expected values.
587
588 Returns:
589 True if the crossystem value matched; otherwise, False.
590 """
591 lines = self.faft_client.run_shell_command_get_output('crossystem')
592 got_dict = self._parse_crossystem_output(lines)
593 for key in expected_dict:
594 if key not in got_dict:
595 logging.info('Expected key "%s" not in crossystem result' % key)
596 return False
597 if isinstance(expected_dict[key], str):
598 if got_dict[key] != expected_dict[key]:
599 logging.info("Expected '%s' value '%s' but got '%s'" %
600 (key, expected_dict[key], got_dict[key]))
601 return False
602 elif isinstance(expected_dict[key], tuple):
603 # Expected value is a tuple of possible actual values.
604 if got_dict[key] not in expected_dict[key]:
605 logging.info("Expected '%s' values %s but got '%s'" %
606 (key, str(expected_dict[key]), got_dict[key]))
607 return False
608 else:
609 logging.info("The expected_dict is neither a str nor a dict.")
610 return False
611 return True
612
613
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800614 def root_part_checker(self, expected_part):
615 """Check the partition number of the root device matched.
616
617 Args:
618 expected_part: A string containing the number of the expected root
619 partition.
620
621 Returns:
622 True if the currect root partition number matched; otherwise, False.
623 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800624 part = self.faft_client.get_root_part()[-1]
625 if self.ROOTFS_MAP[expected_part] != part:
626 logging.info("Expected root part %s but got %s" %
627 (self.ROOTFS_MAP[expected_part], part))
628 return False
629 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800630
631
Vic Yang59cac9c2012-05-21 15:28:42 +0800632 def ec_act_copy_checker(self, expected_copy):
633 """Check the EC running firmware copy matches.
634
635 Args:
636 expected_copy: A string containing 'RO', 'A', or 'B' indicating
637 the expected copy of EC running firmware.
638
639 Returns:
640 True if the current EC running copy matches; otherwise, False.
641 """
642 lines = self.faft_client.run_shell_command_get_output('ectool version')
643 pattern = re.compile("Firmware copy: (.*)")
644 for line in lines:
645 matched = pattern.match(line)
646 if matched and matched.group(1) == expected_copy:
647 return True
648 return False
649
650
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800651 def check_root_part_on_non_recovery(self, part):
652 """Check the partition number of root device and on normal/dev boot.
653
654 Returns:
655 True if the root device matched and on normal/dev boot;
656 otherwise, False.
657 """
658 return self.root_part_checker(part) and \
659 self.crossystem_checker({
660 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800661 })
662
663
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800664 def _join_part(self, dev, part):
665 """Return a concatenated string of device and partition number.
666
667 Args:
668 dev: A string of device, e.g.'/dev/sda'.
669 part: A string of partition number, e.g.'3'.
670
671 Returns:
672 A concatenated string of device and partition number, e.g.'/dev/sda3'.
673
674 >>> seq = FAFTSequence()
675 >>> seq._join_part('/dev/sda', '3')
676 '/dev/sda3'
677 >>> seq._join_part('/dev/mmcblk0', '2')
678 '/dev/mmcblk0p2'
679 """
680 if 'mmcblk' in dev:
681 return dev + 'p' + part
682 else:
683 return dev + part
684
685
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800686 def copy_kernel_and_rootfs(self, from_part, to_part):
687 """Copy kernel and rootfs from from_part to to_part.
688
689 Args:
690 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800691 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800692 """
693 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800694 logging.info('Copying kernel from %s to %s. Please wait...' %
695 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800696 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800697 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
698 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
699 logging.info('Copying rootfs from %s to %s. Please wait...' %
700 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800701 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800702 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
703 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800704
705
706 def ensure_kernel_boot(self, part):
707 """Ensure the request kernel boot.
708
709 If not, it duplicates the current kernel to the requested kernel
710 and sets the requested higher priority to ensure it boot.
711
712 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800713 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800714 """
715 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800716 if self.faft_client.diff_kernel_a_b():
717 self.copy_kernel_and_rootfs(
718 from_part=self.OTHER_KERNEL_MAP[part],
719 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800720 self.run_faft_step({
721 'userspace_action': (self.reset_and_prioritize_kernel, part),
722 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800723
724
Vic Yang416f2032012-08-28 10:18:03 +0800725 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800726 """Set hardware write protect pin.
727
728 Args:
729 enable: True if asserting write protect pin. Otherwise, False.
730 """
731 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
732 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800733 self.servo.set('fw_wp', 'on' if enabled else 'off')
734
735
736 def set_EC_write_protect_and_reboot(self, enabled):
737 """Set EC write protect status and reboot to take effect.
738
739 EC write protect is only activated if both hardware write protect pin
740 is asserted and software write protect flag is set. Also, a reboot is
741 required for write protect to take effect.
742
743 Since the software write protect flag cannot be unset if hardware write
744 protect pin is asserted, we need to deasserted the pin first if we are
745 deactivating write protect. Similarly, a reboot is required before we
746 can modify the software flag.
747
748 This method asserts/deasserts hardware write protect pin first, and
749 set corresponding EC software write protect flag.
750
751 Args:
752 enable: True if activating EC write protect. Otherwise, False.
753 """
754 self.set_hardware_write_protect(enabled)
755 if enabled:
756 # Set write protect flag and reboot to take effect.
757 self.send_uart_command("flashwp enable")
758 self.sync_and_ec_reboot()
759 else:
760 # Reboot after deasserting hardware write protect pin to deactivate
761 # write protect. And then remove software write protect flag.
762 self.sync_and_ec_reboot()
763 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800764
765
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800766 def send_ctrl_d_to_dut(self):
767 """Send Ctrl-D key to DUT."""
768 if self._customized_ctrl_d_key_command:
769 logging.info('running the customized Ctrl-D key command')
770 os.system(self._customized_ctrl_d_key_command)
771 else:
772 self.servo.ctrl_d()
773
774
775 def send_enter_to_dut(self):
776 """Send Enter key to DUT."""
777 if self._customized_enter_key_command:
778 logging.info('running the customized Enter key command')
779 os.system(self._customized_enter_key_command)
780 else:
781 self.servo.enter_key()
782
783
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800784 def send_space_to_dut(self):
785 """Send Space key to DUT."""
786 if self._customized_space_key_command:
787 logging.info('running the customized Space key command')
788 os.system(self._customized_space_key_command)
789 else:
790 # Send the alternative key combinaton of space key to servo.
791 self.servo.ctrl_refresh_key()
792
793
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800794 def wait_fw_screen_and_ctrl_d(self):
795 """Wait for firmware warning screen and press Ctrl-D."""
796 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800797 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800798
799
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800800 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
801 """Wait for firmware warning screen and trigger recovery boot."""
802 time.sleep(self.FIRMWARE_SCREEN_DELAY)
803 self.send_enter_to_dut()
804
805 # For Alex/ZGB, there is a dev warning screen in text mode.
806 # Skip it by pressing Ctrl-D.
807 if need_dev_transition:
808 time.sleep(self.TEXT_SCREEN_DELAY)
809 self.send_ctrl_d_to_dut()
810
811
Mike Truty49153d82012-08-21 22:27:30 -0500812 def wait_fw_screen_and_unplug_usb(self):
813 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800814 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800815 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
816 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500817
818
819 def wait_fw_screen_and_plug_usb(self):
820 """Wait for firmware warning screen and then unplug and plug the USB."""
821 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800822 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
823
824
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800825 def wait_fw_screen_and_press_power(self):
826 """Wait for firmware warning screen and press power button."""
827 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800828 # While the firmware screen, the power button probing loop sleeps
829 # 0.25 second on every scan. Use the normal delay (1.2 second) for
830 # power press.
831 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800832
833
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800834 def wait_longer_fw_screen_and_press_power(self):
835 """Wait for firmware screen without timeout and press power button."""
836 time.sleep(self.DEV_SCREEN_TIMEOUT)
837 self.wait_fw_screen_and_press_power()
838
839
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800840 def wait_fw_screen_and_close_lid(self):
841 """Wait for firmware warning screen and close lid."""
842 time.sleep(self.FIRMWARE_SCREEN_DELAY)
843 self.servo.lid_close()
844
845
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800846 def wait_longer_fw_screen_and_close_lid(self):
847 """Wait for firmware screen without timeout and close lid."""
848 time.sleep(self.FIRMWARE_SCREEN_DELAY)
849 self.wait_fw_screen_and_close_lid()
850
851
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800852 def setup_tried_fwb(self, tried_fwb):
853 """Setup for fw B tried state.
854
855 It makes sure the system in the requested fw B tried state. If not, it
856 tries to do so.
857
858 Args:
859 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
860 """
861 if tried_fwb:
862 if not self.crossystem_checker({'tried_fwb': '1'}):
863 logging.info(
864 'Firmware is not booted with tried_fwb. Reboot into it.')
865 self.run_faft_step({
866 'userspace_action': self.faft_client.set_try_fw_b,
867 })
868 else:
869 if not self.crossystem_checker({'tried_fwb': '0'}):
870 logging.info(
871 'Firmware is booted with tried_fwb. Reboot to clear.')
872 self.run_faft_step({})
873
874
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800875 def enable_rec_mode_and_reboot(self):
876 """Switch to rec mode and reboot.
877
878 This method emulates the behavior of the old physical recovery switch,
879 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
880 recovery mode, i.e. just press Power + Esc + Refresh.
881 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800882 if self._customized_rec_reboot_command:
883 logging.info('running the customized rec reboot command')
884 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800885 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800886 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800887 self.servo.set('cold_reset', 'on')
888 time.sleep(self.COLD_RESET_DELAY)
889 self.servo.set('cold_reset', 'off')
890 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +0800891 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800892 time.sleep(self.EC_BOOT_DELAY)
893 self.send_uart_command("hostevent set 0x4000")
894 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800895 else:
896 self.servo.enable_recovery_mode()
897 self.cold_reboot()
898 time.sleep(self.EC_REBOOT_DELAY)
899 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800900
901
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800902 def enable_dev_mode_and_reboot(self):
903 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800904 if self.client_attr.keyboard_dev:
905 self.enable_keyboard_dev_mode()
906 else:
907 self.servo.enable_development_mode()
908 self.faft_client.run_shell_command(
909 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800910
911
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800912 def enable_normal_mode_and_reboot(self):
913 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800914 if self.client_attr.keyboard_dev:
915 self.disable_keyboard_dev_mode()
916 else:
917 self.servo.disable_development_mode()
918 self.faft_client.run_shell_command(
919 'chromeos-firmwareupdate --mode tonormal && reboot')
920
921
922 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
923 """Wait for firmware screen and then switch into or out of dev mode.
924
925 Args:
926 dev: True if switching into dev mode. Otherwise, False.
927 """
928 time.sleep(self.FIRMWARE_SCREEN_DELAY)
929 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800930 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800931 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800932 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800933 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800934 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800935
936
937 def enable_keyboard_dev_mode(self):
938 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800939 # Plug out USB disk for preventing recovery boot without warning
940 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800941 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800942 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800943 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800944 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800945
946
947 def disable_keyboard_dev_mode(self):
948 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800949 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800950 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800951 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800952 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800953 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800954
955
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800956 def setup_dev_mode(self, dev_mode):
957 """Setup for development mode.
958
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800959 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800960 tries to do so.
961
962 Args:
963 dev_mode: True if requested in dev mode; False if normal mode.
964 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800965 # Change the default firmware_action for dev mode passing the fw screen.
966 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800967 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
968 else None),
969 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800970 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800971 if (not self.client_attr.keyboard_dev and
972 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800973 logging.info('Dev switch is not on. Now switch it on.')
974 self.servo.enable_development_mode()
975 if not self.crossystem_checker({'devsw_boot': '1',
976 'mainfw_type': 'developer'}):
977 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800978 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800979 'userspace_action': None if self.client_attr.keyboard_dev
980 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800981 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800982 'reboot_action': self.enable_keyboard_dev_mode if
983 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800984 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800985 else:
Vic Yange7553162012-06-20 16:20:47 +0800986 if (not self.client_attr.keyboard_dev and
987 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800988 logging.info('Dev switch is not off. Now switch it off.')
989 self.servo.disable_development_mode()
990 if not self.crossystem_checker({'devsw_boot': '0',
991 'mainfw_type': 'normal'}):
992 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800993 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800994 'userspace_action': None if self.client_attr.keyboard_dev
995 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800996 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800997 'reboot_action': self.disable_keyboard_dev_mode if
998 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800999 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001000
1001
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001002 def setup_kernel(self, part):
1003 """Setup for kernel test.
1004
1005 It makes sure both kernel A and B bootable and the current boot is
1006 the requested kernel part.
1007
1008 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001009 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001010 """
1011 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001012 if self.faft_client.diff_kernel_a_b():
1013 self.copy_kernel_and_rootfs(from_part=part,
1014 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001015 self.reset_and_prioritize_kernel(part)
1016
1017
1018 def reset_and_prioritize_kernel(self, part):
1019 """Make the requested partition highest priority.
1020
1021 This function also reset kerenl A and B to bootable.
1022
1023 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001024 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001025 """
1026 root_dev = self.faft_client.get_root_dev()
1027 # Reset kernel A and B to bootable.
1028 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1029 (self.KERNEL_MAP['a'], root_dev))
1030 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1031 (self.KERNEL_MAP['b'], root_dev))
1032 # Set kernel part highest priority.
1033 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1034 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001035 # Safer to sync and wait until the cgpt status written to the disk.
1036 self.faft_client.run_shell_command('sync')
1037 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001038
1039
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001040 def warm_reboot(self):
1041 """Request a warm reboot.
1042
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001043 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001044 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001045 # Use cold reset if the warm reset is broken.
1046 if self.client_attr.broken_warm_reset:
1047 self.servo.cold_reset()
1048 else:
1049 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001050
1051
1052 def cold_reboot(self):
1053 """Request a cold reboot.
1054
1055 A wrapper for underlying servo cold reset.
1056 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001057 if self.client_attr.platform == 'Parrot':
1058 self.servo.set('pwr_button', 'press')
1059 self.servo.set('cold_reset', 'on')
1060 self.servo.set('cold_reset', 'off')
1061 time.sleep(self.POWER_BTN_DELAY)
1062 self.servo.set('pwr_button', 'release')
1063 elif self.check_ec_capability():
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001064 # We don't use servo.cold_reset() here because software sync is
1065 # not yet finished, and device may or may not come up after cold
1066 # reset. Pressing power button before firmware comes up solves this.
1067 #
1068 # The correct behavior should be (not work now):
1069 # - If rebooting EC with rec mode on, power on AP and it boots
1070 # into recovery mode.
1071 # - If rebooting EC with rec mode off, power on AP for software
1072 # sync. Then AP checks if lid open or not. If lid open, continue;
1073 # otherwise, shut AP down and need servo for a power button
1074 # press.
1075 self.servo.set('cold_reset', 'on')
1076 self.servo.set('cold_reset', 'off')
1077 time.sleep(self.POWER_BTN_DELAY)
1078 self.servo.power_short_press()
1079 else:
1080 self.servo.cold_reset()
1081
1082
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001083 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001084 """Request the client sync and do a warm reboot.
1085
1086 This is the default reboot action on FAFT.
1087 """
1088 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001089 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001090 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001091
1092
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001093 def sync_and_cold_reboot(self):
1094 """Request the client sync and do a cold reboot.
1095
1096 This reboot action is used to reset EC for recovery mode.
1097 """
1098 self.faft_client.run_shell_command('sync')
1099 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001100 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001101
1102
Vic Yangaeb10392012-08-28 09:25:09 +08001103 def sync_and_ec_reboot(self, args=''):
1104 """Request the client sync and do a EC triggered reboot.
1105
1106 Args:
1107 args: Arguments passed to "ectool reboot_ec". Including:
1108 RO: jump to EC RO firmware.
1109 RW: jump to EC RW firmware.
1110 cold: Cold/hard reboot.
1111 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001112 self.faft_client.run_shell_command('sync')
1113 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001114 # Since EC reboot happens immediately, delay before actual reboot to
1115 # allow FAFT client returning.
1116 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1117 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001118 time.sleep(self.EC_REBOOT_DELAY)
1119 self.check_lid_and_power_on()
1120
1121
1122 def check_lid_and_power_on(self):
1123 """
1124 On devices with EC software sync, system powers on after EC reboots if
1125 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1126 This method checks lid switch state and presses power button if
1127 necessary.
1128 """
1129 if self.servo.get("lid_open") == "no":
1130 time.sleep(self.SOFTWARE_SYNC_DELAY)
1131 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001132
1133
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001134 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1135 """Modify the kernel header magic in USB stick.
1136
1137 The kernel header magic is the first 8-byte of kernel partition.
1138 We modify it to make it fail on kernel verification check.
1139
1140 Args:
1141 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1142 from_magic: A string of magic which we change it from.
1143 to_magic: A string of magic which we change it to.
1144
1145 Raises:
1146 error.TestError: if failed to change magic.
1147 """
1148 assert len(from_magic) == 8
1149 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001150 # USB image only contains one kernel.
1151 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001152 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1153 current_magic = utils.system_output(read_cmd)
1154 if current_magic == to_magic:
1155 logging.info("The kernel magic is already %s." % current_magic)
1156 return
1157 if current_magic != from_magic:
1158 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1159
1160 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1161 (from_magic, to_magic))
1162 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1163 " 2>/dev/null" % (to_magic, kernel_part))
1164 utils.system(write_cmd)
1165
1166 if utils.system_output(read_cmd) != to_magic:
1167 raise error.TestError("Failed to write new magic.")
1168
1169
1170 def corrupt_usb_kernel(self, usb_dev):
1171 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1172
1173 Args:
1174 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1175 """
1176 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1177 self.CORRUPTED_MAGIC)
1178
1179
1180 def restore_usb_kernel(self, usb_dev):
1181 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1182
1183 Args:
1184 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1185 """
1186 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1187 self.CHROMEOS_MAGIC)
1188
1189
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001190 def _call_action(self, action_tuple):
1191 """Call the action function with/without arguments.
1192
1193 Args:
1194 action_tuple: A function, or a tuple which consisted of a function
1195 and its arguments (if any).
1196
1197 Returns:
1198 The result value of the action function.
1199 """
1200 if isinstance(action_tuple, tuple):
1201 action = action_tuple[0]
1202 args = action_tuple[1:]
1203 if callable(action):
1204 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tam2b48cbc2012-08-08 19:58:00 +08001205 str(action), str(args)))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001206 return action(*args)
1207 else:
1208 logging.info('action is not callable!')
1209 else:
1210 action = action_tuple
1211 if action is not None:
1212 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001213 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001214 return action()
1215 else:
1216 logging.info('action is not callable!')
1217
1218 return None
1219
1220
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001221 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1222 post_power_action=None):
1223 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1224
1225 Args:
1226 shutdown_action: a function which makes DUT shutdown, like pressing
1227 power key.
1228 pre_power_action: a function which is called before next power on.
1229 post_power_action: a function which is called after next power on.
1230
1231 Raises:
1232 error.TestFail: if the shutdown_action() failed to turn DUT off.
1233 """
1234 self._call_action(shutdown_action)
1235 logging.info('Wait to ensure DUT shut down...')
1236 try:
1237 self.wait_for_client()
1238 raise error.TestFail(
1239 'Should shut the device down after calling %s.' %
1240 str(shutdown_action))
1241 except AssertionError:
1242 logging.info(
1243 'DUT is surely shutdown. We are going to power it on again...')
1244
1245 if pre_power_action:
1246 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001247 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001248 if post_power_action:
1249 self._call_action(post_power_action)
1250
1251
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001252 def register_faft_template(self, template):
1253 """Register FAFT template, the default FAFT_STEP of each step.
1254
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001255 Any missing field falls back to the original faft_template.
1256
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001257 Args:
1258 template: A FAFT_STEP dict.
1259 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001260 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001261
1262
1263 def register_faft_sequence(self, sequence):
1264 """Register FAFT sequence.
1265
1266 Args:
1267 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1268 """
1269 self._faft_sequence = sequence
1270
1271
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001272 def run_faft_step(self, step, no_reboot=False):
1273 """Run a single FAFT step.
1274
1275 Any missing field falls back to faft_template. An empty step means
1276 running the default faft_template.
1277
1278 Args:
1279 step: A FAFT_STEP dict.
1280 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001281
1282 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001283 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001284 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001285 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001286 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1287 'firmware_action', 'install_deps_after_boot')
1288
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001289 test = {}
1290 test.update(self._faft_template)
1291 test.update(step)
1292
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001293 for key in test:
1294 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001295 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001296
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001297 if test['state_checker']:
1298 if not self._call_action(test['state_checker']):
1299 raise error.TestFail('State checker failed!')
1300
1301 self._call_action(test['userspace_action'])
1302
1303 # Don't run reboot_action and firmware_action if no_reboot is True.
1304 if not no_reboot:
1305 self._call_action(test['reboot_action'])
1306 self.wait_for_client_offline()
1307 self._call_action(test['firmware_action'])
1308
1309 if 'install_deps_after_boot' in test:
1310 self.wait_for_client(
1311 install_deps=test['install_deps_after_boot'])
1312 else:
1313 self.wait_for_client()
1314
1315
1316 def run_faft_sequence(self):
1317 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001318 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001319 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001320 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001321 logging.info('======== Running FAFT sequence step %d ========' %
1322 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001323 # Don't reboot in the last step.
1324 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001325 index += 1