blob: 33d06039d3f4f74e9fc5ccfa774ca2d285b0b161 [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 Tam39b93b92012-09-04 16:56:05 +0800208 # VbSharedData flags
209 # Copied from vboot_reference/firmware/include/vboot_struct.h
210 VDAT_FLAG_FWB_TRIED = 0x00000001
211 VDAT_FLAG_KERNEL_KEY_VERIFIED = 0x00000002
212 VDAT_FLAG_LF_DEV_SWITCH_ON = 0x00000004
213 VDAT_FLAG_LF_USE_RO_NORMAL = 0x00000008
214 VDAT_FLAG_BOOT_DEV_SWITCH_ON = 0x00000010
215 VDAT_FLAG_BOOT_REC_SWITCH_ON = 0x00000020
216 VDAT_FLAG_BOOT_FIRMWARE_WP_ENABLED = 0x00000040
217 VDAT_FLAG_BOOT_S3_RESUME = 0x00000100
218 VDAT_FLAG_BOOT_RO_NORMAL_SUPPORT = 0x00000200
219 VDAT_FLAG_HONOR_VIRT_DEV_SWITCH = 0x00000400
220 VDAT_FLAG_EC_SOFTWARE_SYNC = 0x00000800
221 VDAT_FLAG_EC_SLOW_UPDATE = 0x00001000
222
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800223 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800224 _faft_sequence = ()
225
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800226 _customized_ctrl_d_key_command = None
227 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800228 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800229 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800230 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800231 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800232
233
234 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
235 # Parse arguments from command line
236 args = {}
237 for arg in cmdline_args:
238 match = re.search("^(\w+)=(.+)", arg)
239 if match:
240 args[match.group(1)] = match.group(2)
241
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800242 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800243 if 'ctrl_d_cmd' in args:
244 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
245 logging.info('Customized Ctrl-D key command: %s' %
246 self._customized_ctrl_d_key_command)
247 if 'enter_cmd' in args:
248 self._customized_enter_key_command = args['enter_cmd']
249 logging.info('Customized Enter key command: %s' %
250 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800251 if 'space_cmd' in args:
252 self._customized_space_key_command = args['space_cmd']
253 logging.info('Customized Space key command: %s' %
254 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800255 if 'rec_reboot_cmd' in args:
256 self._customized_rec_reboot_command = args['rec_reboot_cmd']
257 logging.info('Customized recovery reboot command: %s' %
258 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800259 if 'image' in args:
260 self._install_image_path = args['image']
261 logging.info('Install Chrome OS test image path: %s' %
262 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800263 if 'firmware_update' in args and args['firmware_update'].lower() \
264 not in ('0', 'false', 'no'):
265 if self._install_image_path:
266 self._firmware_update = True
267 logging.info('Also update firmware after installing.')
268 else:
269 logging.warning('Firmware update will not not performed '
270 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800271
272 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
273 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800274 if use_faft:
275 self.client_attr = FAFTClientAttribute(
276 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800277
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800278
279 def setup(self):
280 """Autotest setup function."""
281 super(FAFTSequence, self).setup()
282 if not self._remote_infos['faft']['used']:
283 raise error.TestError('The use_faft flag should be enabled.')
284 self.register_faft_template({
285 'state_checker': (None),
286 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800287 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800288 'firmware_action': (None)
289 })
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800290 self.clear_set_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON |
291 self.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
292 self.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800293 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800294 self.install_test_image(self._install_image_path,
295 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800296
297
298 def cleanup(self):
299 """Autotest cleanup function."""
300 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800301 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800302 super(FAFTSequence, self).cleanup()
303
304
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800305 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800306 """Assert an USB disk plugged-in on servo and a test image inside.
307
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800308 Args:
309 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
310 If None, it is detected automatically.
311
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800312 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800313 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800314 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800315 if usb_dev:
316 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
317 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700318 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800319 usb_dev = self.servo.probe_host_usb_dev()
320 if not usb_dev:
321 raise error.TestError(
322 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800323
324 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800325 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800326 code = utils.system(
327 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
328 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800329 utils.system('sudo umount %s' % tmp_dir)
330 os.removedirs(tmp_dir)
331 if code != 0:
332 raise error.TestError(
333 'The image in the USB disk should be a test image.')
334
335
Simran Basi741b5d42012-05-18 11:27:15 -0700336 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800337 """Install the test image specied by the path onto the USB and DUT disk.
338
339 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500340 recovery mode. Then runs 'chromeos-install' (and possible
341 chromeos-firmwareupdate') to install it to DUT disk.
342
343 Sample command line:
344
345 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
346 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
347 server/site_tests/firmware_XXXX/control
348
349 This test requires an automated recovery to occur while simulating
350 inserting and removing the usb key from the servo. To allow this the
351 following hardware setup is required:
352 1. servo2 board connected via servoflex.
353 2. USB key inserted in the servo2.
354 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
355 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800356
357 Args:
358 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800359 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800360 """
361 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
362 image_path)
363 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800364
Mike Truty49153d82012-08-21 22:27:30 -0500365 # Reuse the servo method that uses the servo USB key to install
366 # the test image.
367 self.servo.image_to_servo_usb(image_path)
368
369 # DUT is powered off while imaging servo USB.
370 # Now turn it on.
371 self.servo.power_short_press()
372 self.wait_for_client()
373 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
374
375 install_cmd = 'chromeos-install --yes'
376 if firmware_update:
377 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
378
379 self.register_faft_sequence((
380 { # Step 1, request recovery boot
381 'state_checker': (self.crossystem_checker, {
382 'mainfw_type': ('developer', 'normal'),
383 }),
384 'userspace_action': self.faft_client.request_recovery_boot,
385 'firmware_action': self.wait_fw_screen_and_plug_usb,
386 'install_deps_after_boot': True,
387 },
388 { # Step 2, expected recovery boot
389 'state_checker': (self.crossystem_checker, {
390 'mainfw_type': 'recovery',
391 'recovery_reason' : self.RECOVERY_REASON['US_TEST'],
392 }),
393 'userspace_action': (self.faft_client.run_shell_command,
394 install_cmd),
395 'reboot_action': self.cold_reboot,
396 'install_deps_after_boot': True,
397 },
398 { # Step 3, expected normal or developer boot (not recovery)
399 'state_checker': (self.crossystem_checker, {
400 'mainfw_type': ('developer', 'normal')
401 }),
402 },
403 ))
404 self.run_faft_sequence()
405 # 'Unplug' any USB keys in the servo from the dut.
406 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800407
408
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800409 def clear_set_gbb_flags(self, clear_mask, set_mask):
410 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800411
412 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800413 clear_mask: A mask of flags to be cleared.
414 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800415 """
416 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800417 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
418
419 if (gbb_flags != new_flags):
420 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
421 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800422 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800423 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800424 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800425 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800426 if ((gbb_flags ^ new_flags) & self.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800427 self.run_faft_step({
428 'firmware_action': self.wait_fw_screen_and_ctrl_d,
429 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800430
431
Vic Yangb4e3e742012-06-02 13:17:38 +0800432 def _open_uart_pty(self):
433 """Open UART pty and spawn pexpect object.
434
435 Returns:
436 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
437 child is a fdpexpect object tied to it.
438 """
439 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
440 child = fdpexpect.fdspawn(fd)
441 return (fd, child)
442
443
444 def _flush_uart_pty(self, child):
445 """Flush UART output to prevent previous pending message interferring.
446
447 Args:
448 child: The fdpexpect object tied to UART pty.
449 """
450 child.sendline("")
451 while True:
452 try:
453 child.expect(".", timeout=0.01)
454 except pexpect.TIMEOUT:
455 break
456
457
458 def _uart_send(self, child, line):
459 """Flush and send command through UART.
460
461 Args:
462 child: The pexpect object tied to UART pty.
463 line: String to send through UART.
464
465 Raises:
466 error.TestFail: Raised when writing to UART fails.
467 """
468 logging.info("Sending UART command: %s" % line)
469 self._flush_uart_pty(child)
470 if child.sendline(line) != len(line) + 1:
471 raise error.TestFail("Failed to send UART command.")
472
473
474 def send_uart_command(self, command):
475 """Send command through UART.
476
477 This function open UART pty when called, and then command is sent
478 through UART.
479
480 Args:
481 command: The command string to send.
482
483 Raises:
484 error.TestFail: Raised when writing to UART fails.
485 """
486 (fd, child) = self._open_uart_pty()
487 try:
488 self._uart_send(child, command)
489 finally:
490 os.close(fd)
491
492
493 def send_uart_command_get_output(self, command, regex_list, timeout=1):
494 """Send command through UART and wait for response.
495
496 This function waits for response message matching regular expressions.
497
498 Args:
499 command: The command sent.
500 regex_list: List of regular expressions used to match response message.
501 Note, list must be ordered.
502
503 Returns:
504 List of match objects of response message.
505
506 Raises:
507 error.TestFail: If timed out waiting for EC response.
508 """
509 if not isinstance(regex_list, list):
510 regex_list = [regex_list]
511 result_list = []
512 (fd, child) = self._open_uart_pty()
513 try:
514 self._uart_send(child, command)
515 for regex in regex_list:
516 child.expect(regex, timeout=timeout)
517 result_list.append(child.match)
518 except pexpect.TIMEOUT:
519 raise error.TestFail("Timeout waiting for UART response.")
520 finally:
521 os.close(fd)
522 return result_list
523
524
Vic Yang4d72cb62012-07-24 11:51:09 +0800525 def check_ec_capability(self, required_cap=[]):
526 """Check if current platform has required EC capabilities.
527
528 Args:
529 required_cap: A list containing required EC capabilities. Pass in
530 None to only check for presence of Chrome EC.
531
532 Returns:
533 True if requirements are met. Otherwise, False.
534 """
535 if not self.client_attr.chrome_ec:
536 logging.warn('Requires Chrome EC to run this test.')
537 return False
538
539 for cap in required_cap:
540 if cap not in self.client_attr.ec_capability:
541 logging.warn('Requires EC capability "%s" to run this test.' %
542 cap)
543 return False
544
545 return True
546
547
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800548 def _parse_crossystem_output(self, lines):
549 """Parse the crossystem output into a dict.
550
551 Args:
552 lines: The list of crossystem output strings.
553
554 Returns:
555 A dict which contains the crossystem keys/values.
556
557 Raises:
558 error.TestError: If wrong format in crossystem output.
559
560 >>> seq = FAFTSequence()
561 >>> seq._parse_crossystem_output([ \
562 "arch = x86 # Platform architecture", \
563 "cros_debug = 1 # OS should allow debug", \
564 ])
565 {'cros_debug': '1', 'arch': 'x86'}
566 >>> seq._parse_crossystem_output([ \
567 "arch=x86", \
568 ])
569 Traceback (most recent call last):
570 ...
571 TestError: Failed to parse crossystem output: arch=x86
572 >>> seq._parse_crossystem_output([ \
573 "arch = x86 # Platform architecture", \
574 "arch = arm # Platform architecture", \
575 ])
576 Traceback (most recent call last):
577 ...
578 TestError: Duplicated crossystem key: arch
579 """
580 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
581 parsed_list = {}
582 for line in lines:
583 matched = re.match(pattern, line.strip())
584 if not matched:
585 raise error.TestError("Failed to parse crossystem output: %s"
586 % line)
587 (name, value) = (matched.group(1), matched.group(2))
588 if name in parsed_list:
589 raise error.TestError("Duplicated crossystem key: %s" % name)
590 parsed_list[name] = value
591 return parsed_list
592
593
594 def crossystem_checker(self, expected_dict):
595 """Check the crossystem values matched.
596
597 Given an expect_dict which describes the expected crossystem values,
598 this function check the current crossystem values are matched or not.
599
600 Args:
601 expected_dict: A dict which contains the expected values.
602
603 Returns:
604 True if the crossystem value matched; otherwise, False.
605 """
606 lines = self.faft_client.run_shell_command_get_output('crossystem')
607 got_dict = self._parse_crossystem_output(lines)
608 for key in expected_dict:
609 if key not in got_dict:
610 logging.info('Expected key "%s" not in crossystem result' % key)
611 return False
612 if isinstance(expected_dict[key], str):
613 if got_dict[key] != expected_dict[key]:
614 logging.info("Expected '%s' value '%s' but got '%s'" %
615 (key, expected_dict[key], got_dict[key]))
616 return False
617 elif isinstance(expected_dict[key], tuple):
618 # Expected value is a tuple of possible actual values.
619 if got_dict[key] not in expected_dict[key]:
620 logging.info("Expected '%s' values %s but got '%s'" %
621 (key, str(expected_dict[key]), got_dict[key]))
622 return False
623 else:
624 logging.info("The expected_dict is neither a str nor a dict.")
625 return False
626 return True
627
628
Tom Wai-Hong Tam39b93b92012-09-04 16:56:05 +0800629 def vdat_flags_checker(self, mask, value):
630 """Check the flags from VbSharedData matched.
631
632 This function checks the masked flags from VbSharedData using crossystem
633 are matched the given value.
634
635 Args:
636 mask: A bitmask of flags to be matched.
637 value: An expected value.
638
639 Returns:
640 True if the flags matched; otherwise, False.
641 """
642 lines = self.faft_client.run_shell_command_get_output(
643 'crossystem vdat_flags')
644 vdat_flags = int(lines[0], 16)
645 if vdat_flags & mask != value:
646 logging.info("Expected vdat_flags 0x%x mask 0x%x but got 0x%x" %
647 (value, mask, vdat_flags))
648 return False
649 return True
650
651
Tom Wai-Hong Tam3e82e362012-09-05 10:17:55 +0800652 def ro_normal_checker(self, expected_fw=None, twostop=False):
653 """Check the current boot uses RO boot.
654
655 Args:
656 expected_fw: A string of expected firmware, 'A', 'B', or
657 None if don't care.
658 twostop: True to expect a TwoStop boot; False to expect a RO boot.
659
660 Returns:
661 True if the currect boot firmware matched and used RO boot;
662 otherwise, False.
663 """
664 crossystem_dict = {'tried_fwb': '0'}
665 if expected_fw:
666 crossystem_dict['mainfw_act'] = expected_fw.upper()
667 if self.check_ec_capability():
668 crossystem_dict['ecfw_act'] = ('RW' if twostop else 'RO')
669
670 return (self.vdat_flags_checker(
671 self.VDAT_FLAG_LF_USE_RO_NORMAL,
672 0 if twostop else self.VDAT_FLAG_LF_USE_RO_NORMAL) and
673 self.crossystem_checker(crossystem_dict))
674
675
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800676 def root_part_checker(self, expected_part):
677 """Check the partition number of the root device matched.
678
679 Args:
680 expected_part: A string containing the number of the expected root
681 partition.
682
683 Returns:
684 True if the currect root partition number matched; otherwise, False.
685 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800686 part = self.faft_client.get_root_part()[-1]
687 if self.ROOTFS_MAP[expected_part] != part:
688 logging.info("Expected root part %s but got %s" %
689 (self.ROOTFS_MAP[expected_part], part))
690 return False
691 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800692
693
Vic Yang59cac9c2012-05-21 15:28:42 +0800694 def ec_act_copy_checker(self, expected_copy):
695 """Check the EC running firmware copy matches.
696
697 Args:
698 expected_copy: A string containing 'RO', 'A', or 'B' indicating
699 the expected copy of EC running firmware.
700
701 Returns:
702 True if the current EC running copy matches; otherwise, False.
703 """
704 lines = self.faft_client.run_shell_command_get_output('ectool version')
705 pattern = re.compile("Firmware copy: (.*)")
706 for line in lines:
707 matched = pattern.match(line)
708 if matched and matched.group(1) == expected_copy:
709 return True
710 return False
711
712
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800713 def check_root_part_on_non_recovery(self, part):
714 """Check the partition number of root device and on normal/dev boot.
715
716 Returns:
717 True if the root device matched and on normal/dev boot;
718 otherwise, False.
719 """
720 return self.root_part_checker(part) and \
721 self.crossystem_checker({
722 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800723 })
724
725
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800726 def _join_part(self, dev, part):
727 """Return a concatenated string of device and partition number.
728
729 Args:
730 dev: A string of device, e.g.'/dev/sda'.
731 part: A string of partition number, e.g.'3'.
732
733 Returns:
734 A concatenated string of device and partition number, e.g.'/dev/sda3'.
735
736 >>> seq = FAFTSequence()
737 >>> seq._join_part('/dev/sda', '3')
738 '/dev/sda3'
739 >>> seq._join_part('/dev/mmcblk0', '2')
740 '/dev/mmcblk0p2'
741 """
742 if 'mmcblk' in dev:
743 return dev + 'p' + part
744 else:
745 return dev + part
746
747
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800748 def copy_kernel_and_rootfs(self, from_part, to_part):
749 """Copy kernel and rootfs from from_part to to_part.
750
751 Args:
752 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800753 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800754 """
755 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800756 logging.info('Copying kernel from %s to %s. Please wait...' %
757 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800758 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800759 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
760 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
761 logging.info('Copying rootfs from %s to %s. Please wait...' %
762 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800763 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800764 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
765 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800766
767
768 def ensure_kernel_boot(self, part):
769 """Ensure the request kernel boot.
770
771 If not, it duplicates the current kernel to the requested kernel
772 and sets the requested higher priority to ensure it boot.
773
774 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800775 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800776 """
777 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800778 if self.faft_client.diff_kernel_a_b():
779 self.copy_kernel_and_rootfs(
780 from_part=self.OTHER_KERNEL_MAP[part],
781 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800782 self.run_faft_step({
783 'userspace_action': (self.reset_and_prioritize_kernel, part),
784 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800785
786
Vic Yang416f2032012-08-28 10:18:03 +0800787 def set_hardware_write_protect(self, enabled):
Vic Yang2cabf812012-08-28 02:39:04 +0800788 """Set hardware write protect pin.
789
790 Args:
791 enable: True if asserting write protect pin. Otherwise, False.
792 """
793 self.servo.set('fw_wp_vref', self.client_attr.wp_voltage)
794 self.servo.set('fw_wp_en', 'on')
Vic Yang416f2032012-08-28 10:18:03 +0800795 self.servo.set('fw_wp', 'on' if enabled else 'off')
796
797
798 def set_EC_write_protect_and_reboot(self, enabled):
799 """Set EC write protect status and reboot to take effect.
800
801 EC write protect is only activated if both hardware write protect pin
802 is asserted and software write protect flag is set. Also, a reboot is
803 required for write protect to take effect.
804
805 Since the software write protect flag cannot be unset if hardware write
806 protect pin is asserted, we need to deasserted the pin first if we are
807 deactivating write protect. Similarly, a reboot is required before we
808 can modify the software flag.
809
810 This method asserts/deasserts hardware write protect pin first, and
811 set corresponding EC software write protect flag.
812
813 Args:
814 enable: True if activating EC write protect. Otherwise, False.
815 """
816 self.set_hardware_write_protect(enabled)
817 if enabled:
818 # Set write protect flag and reboot to take effect.
819 self.send_uart_command("flashwp enable")
820 self.sync_and_ec_reboot()
821 else:
822 # Reboot after deasserting hardware write protect pin to deactivate
823 # write protect. And then remove software write protect flag.
824 self.sync_and_ec_reboot()
825 self.send_uart_command("flashwp disable")
Vic Yang2cabf812012-08-28 02:39:04 +0800826
827
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800828 def send_ctrl_d_to_dut(self):
829 """Send Ctrl-D key to DUT."""
830 if self._customized_ctrl_d_key_command:
831 logging.info('running the customized Ctrl-D key command')
832 os.system(self._customized_ctrl_d_key_command)
833 else:
834 self.servo.ctrl_d()
835
836
837 def send_enter_to_dut(self):
838 """Send Enter key to DUT."""
839 if self._customized_enter_key_command:
840 logging.info('running the customized Enter key command')
841 os.system(self._customized_enter_key_command)
842 else:
843 self.servo.enter_key()
844
845
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800846 def send_space_to_dut(self):
847 """Send Space key to DUT."""
848 if self._customized_space_key_command:
849 logging.info('running the customized Space key command')
850 os.system(self._customized_space_key_command)
851 else:
852 # Send the alternative key combinaton of space key to servo.
853 self.servo.ctrl_refresh_key()
854
855
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800856 def wait_fw_screen_and_ctrl_d(self):
857 """Wait for firmware warning screen and press Ctrl-D."""
858 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800859 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800860
861
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800862 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
863 """Wait for firmware warning screen and trigger recovery boot."""
864 time.sleep(self.FIRMWARE_SCREEN_DELAY)
865 self.send_enter_to_dut()
866
867 # For Alex/ZGB, there is a dev warning screen in text mode.
868 # Skip it by pressing Ctrl-D.
869 if need_dev_transition:
870 time.sleep(self.TEXT_SCREEN_DELAY)
871 self.send_ctrl_d_to_dut()
872
873
Mike Truty49153d82012-08-21 22:27:30 -0500874 def wait_fw_screen_and_unplug_usb(self):
875 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800876 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800877 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
878 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500879
880
881 def wait_fw_screen_and_plug_usb(self):
882 """Wait for firmware warning screen and then unplug and plug the USB."""
883 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800884 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
885
886
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800887 def wait_fw_screen_and_press_power(self):
888 """Wait for firmware warning screen and press power button."""
889 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800890 # While the firmware screen, the power button probing loop sleeps
891 # 0.25 second on every scan. Use the normal delay (1.2 second) for
892 # power press.
893 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800894
895
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800896 def wait_longer_fw_screen_and_press_power(self):
897 """Wait for firmware screen without timeout and press power button."""
898 time.sleep(self.DEV_SCREEN_TIMEOUT)
899 self.wait_fw_screen_and_press_power()
900
901
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800902 def wait_fw_screen_and_close_lid(self):
903 """Wait for firmware warning screen and close lid."""
904 time.sleep(self.FIRMWARE_SCREEN_DELAY)
905 self.servo.lid_close()
906
907
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800908 def wait_longer_fw_screen_and_close_lid(self):
909 """Wait for firmware screen without timeout and close lid."""
910 time.sleep(self.FIRMWARE_SCREEN_DELAY)
911 self.wait_fw_screen_and_close_lid()
912
913
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800914 def setup_tried_fwb(self, tried_fwb):
915 """Setup for fw B tried state.
916
917 It makes sure the system in the requested fw B tried state. If not, it
918 tries to do so.
919
920 Args:
921 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
922 """
923 if tried_fwb:
924 if not self.crossystem_checker({'tried_fwb': '1'}):
925 logging.info(
926 'Firmware is not booted with tried_fwb. Reboot into it.')
927 self.run_faft_step({
928 'userspace_action': self.faft_client.set_try_fw_b,
929 })
930 else:
931 if not self.crossystem_checker({'tried_fwb': '0'}):
932 logging.info(
933 'Firmware is booted with tried_fwb. Reboot to clear.')
934 self.run_faft_step({})
935
936
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800937 def enable_rec_mode_and_reboot(self):
938 """Switch to rec mode and reboot.
939
940 This method emulates the behavior of the old physical recovery switch,
941 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
942 recovery mode, i.e. just press Power + Esc + Refresh.
943 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800944 if self._customized_rec_reboot_command:
945 logging.info('running the customized rec reboot command')
946 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800947 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800948 # Cold reset to clear EC_IN_RW signal
Vic Yanga7250662012-08-31 04:00:08 +0800949 self.servo.set('cold_reset', 'on')
950 time.sleep(self.COLD_RESET_DELAY)
951 self.servo.set('cold_reset', 'off')
952 time.sleep(self.EC_BOOT_DELAY)
Vic Yang81273092012-08-21 15:57:09 +0800953 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800954 time.sleep(self.EC_BOOT_DELAY)
955 self.send_uart_command("hostevent set 0x4000")
956 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800957 else:
958 self.servo.enable_recovery_mode()
959 self.cold_reboot()
960 time.sleep(self.EC_REBOOT_DELAY)
961 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800962
963
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800964 def enable_dev_mode_and_reboot(self):
965 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800966 if self.client_attr.keyboard_dev:
967 self.enable_keyboard_dev_mode()
968 else:
969 self.servo.enable_development_mode()
970 self.faft_client.run_shell_command(
971 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800972
973
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800974 def enable_normal_mode_and_reboot(self):
975 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800976 if self.client_attr.keyboard_dev:
977 self.disable_keyboard_dev_mode()
978 else:
979 self.servo.disable_development_mode()
980 self.faft_client.run_shell_command(
981 'chromeos-firmwareupdate --mode tonormal && reboot')
982
983
984 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
985 """Wait for firmware screen and then switch into or out of dev mode.
986
987 Args:
988 dev: True if switching into dev mode. Otherwise, False.
989 """
990 time.sleep(self.FIRMWARE_SCREEN_DELAY)
991 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800992 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800993 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800994 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800995 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800996 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800997
998
999 def enable_keyboard_dev_mode(self):
1000 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +08001001 # Plug out USB disk for preventing recovery boot without warning
1002 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +08001003 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +08001004 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001005 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001006 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +08001007
1008
1009 def disable_keyboard_dev_mode(self):
1010 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +08001011 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +08001012 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001013 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +08001014 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +08001015 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001016
1017
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001018 def setup_dev_mode(self, dev_mode):
1019 """Setup for development mode.
1020
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001021 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001022 tries to do so.
1023
1024 Args:
1025 dev_mode: True if requested in dev mode; False if normal mode.
1026 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001027 # Change the default firmware_action for dev mode passing the fw screen.
1028 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001029 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
1030 else None),
1031 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001032 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +08001033 if (not self.client_attr.keyboard_dev and
1034 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001035 logging.info('Dev switch is not on. Now switch it on.')
1036 self.servo.enable_development_mode()
1037 if not self.crossystem_checker({'devsw_boot': '1',
1038 'mainfw_type': 'developer'}):
1039 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001040 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001041 'userspace_action': None if self.client_attr.keyboard_dev
1042 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001043 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001044 'reboot_action': self.enable_keyboard_dev_mode if
1045 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001046 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001047 else:
Vic Yange7553162012-06-20 16:20:47 +08001048 if (not self.client_attr.keyboard_dev and
1049 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001050 logging.info('Dev switch is not off. Now switch it off.')
1051 self.servo.disable_development_mode()
1052 if not self.crossystem_checker({'devsw_boot': '0',
1053 'mainfw_type': 'normal'}):
1054 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001055 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +08001056 'userspace_action': None if self.client_attr.keyboard_dev
1057 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +08001058 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +08001059 'reboot_action': self.disable_keyboard_dev_mode if
1060 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +08001061 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001062
1063
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001064 def setup_kernel(self, part):
1065 """Setup for kernel test.
1066
1067 It makes sure both kernel A and B bootable and the current boot is
1068 the requested kernel part.
1069
1070 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001071 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001072 """
1073 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +08001074 if self.faft_client.diff_kernel_a_b():
1075 self.copy_kernel_and_rootfs(from_part=part,
1076 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001077 self.reset_and_prioritize_kernel(part)
1078
1079
1080 def reset_and_prioritize_kernel(self, part):
1081 """Make the requested partition highest priority.
1082
1083 This function also reset kerenl A and B to bootable.
1084
1085 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001086 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001087 """
1088 root_dev = self.faft_client.get_root_dev()
1089 # Reset kernel A and B to bootable.
1090 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1091 (self.KERNEL_MAP['a'], root_dev))
1092 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
1093 (self.KERNEL_MAP['b'], root_dev))
1094 # Set kernel part highest priority.
1095 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
1096 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001097 # Safer to sync and wait until the cgpt status written to the disk.
1098 self.faft_client.run_shell_command('sync')
1099 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +08001100
1101
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001102 def warm_reboot(self):
1103 """Request a warm reboot.
1104
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001105 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001106 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +08001107 # Use cold reset if the warm reset is broken.
1108 if self.client_attr.broken_warm_reset:
1109 self.servo.cold_reset()
1110 else:
1111 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001112
1113
1114 def cold_reboot(self):
1115 """Request a cold reboot.
1116
1117 A wrapper for underlying servo cold reset.
1118 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001119 if self.client_attr.platform == 'Parrot':
1120 self.servo.set('pwr_button', 'press')
1121 self.servo.set('cold_reset', 'on')
1122 self.servo.set('cold_reset', 'off')
1123 time.sleep(self.POWER_BTN_DELAY)
1124 self.servo.set('pwr_button', 'release')
1125 elif self.check_ec_capability():
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001126 # We don't use servo.cold_reset() here because software sync is
1127 # not yet finished, and device may or may not come up after cold
1128 # reset. Pressing power button before firmware comes up solves this.
1129 #
1130 # The correct behavior should be (not work now):
1131 # - If rebooting EC with rec mode on, power on AP and it boots
1132 # into recovery mode.
1133 # - If rebooting EC with rec mode off, power on AP for software
1134 # sync. Then AP checks if lid open or not. If lid open, continue;
1135 # otherwise, shut AP down and need servo for a power button
1136 # press.
1137 self.servo.set('cold_reset', 'on')
1138 self.servo.set('cold_reset', 'off')
1139 time.sleep(self.POWER_BTN_DELAY)
1140 self.servo.power_short_press()
1141 else:
1142 self.servo.cold_reset()
1143
1144
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001145 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001146 """Request the client sync and do a warm reboot.
1147
1148 This is the default reboot action on FAFT.
1149 """
1150 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001151 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001152 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001153
1154
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001155 def sync_and_cold_reboot(self):
1156 """Request the client sync and do a cold reboot.
1157
1158 This reboot action is used to reset EC for recovery mode.
1159 """
1160 self.faft_client.run_shell_command('sync')
1161 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001162 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001163
1164
Vic Yangaeb10392012-08-28 09:25:09 +08001165 def sync_and_ec_reboot(self, args=''):
1166 """Request the client sync and do a EC triggered reboot.
1167
1168 Args:
1169 args: Arguments passed to "ectool reboot_ec". Including:
1170 RO: jump to EC RO firmware.
1171 RW: jump to EC RW firmware.
1172 cold: Cold/hard reboot.
1173 """
Vic Yang59cac9c2012-05-21 15:28:42 +08001174 self.faft_client.run_shell_command('sync')
1175 time.sleep(self.SYNC_DELAY)
Vic Yangaeb10392012-08-28 09:25:09 +08001176 # Since EC reboot happens immediately, delay before actual reboot to
1177 # allow FAFT client returning.
1178 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec %s)&' %
1179 (self.EC_REBOOT_DELAY, args))
Vic Yangf86728a2012-07-30 10:44:07 +08001180 time.sleep(self.EC_REBOOT_DELAY)
1181 self.check_lid_and_power_on()
1182
1183
1184 def check_lid_and_power_on(self):
1185 """
1186 On devices with EC software sync, system powers on after EC reboots if
1187 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1188 This method checks lid switch state and presses power button if
1189 necessary.
1190 """
1191 if self.servo.get("lid_open") == "no":
1192 time.sleep(self.SOFTWARE_SYNC_DELAY)
1193 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001194
1195
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001196 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1197 """Modify the kernel header magic in USB stick.
1198
1199 The kernel header magic is the first 8-byte of kernel partition.
1200 We modify it to make it fail on kernel verification check.
1201
1202 Args:
1203 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1204 from_magic: A string of magic which we change it from.
1205 to_magic: A string of magic which we change it to.
1206
1207 Raises:
1208 error.TestError: if failed to change magic.
1209 """
1210 assert len(from_magic) == 8
1211 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001212 # USB image only contains one kernel.
1213 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001214 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1215 current_magic = utils.system_output(read_cmd)
1216 if current_magic == to_magic:
1217 logging.info("The kernel magic is already %s." % current_magic)
1218 return
1219 if current_magic != from_magic:
1220 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1221
1222 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1223 (from_magic, to_magic))
1224 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1225 " 2>/dev/null" % (to_magic, kernel_part))
1226 utils.system(write_cmd)
1227
1228 if utils.system_output(read_cmd) != to_magic:
1229 raise error.TestError("Failed to write new magic.")
1230
1231
1232 def corrupt_usb_kernel(self, usb_dev):
1233 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1234
1235 Args:
1236 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1237 """
1238 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1239 self.CORRUPTED_MAGIC)
1240
1241
1242 def restore_usb_kernel(self, usb_dev):
1243 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1244
1245 Args:
1246 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1247 """
1248 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1249 self.CHROMEOS_MAGIC)
1250
1251
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001252 def _call_action(self, action_tuple):
1253 """Call the action function with/without arguments.
1254
1255 Args:
1256 action_tuple: A function, or a tuple which consisted of a function
1257 and its arguments (if any).
1258
1259 Returns:
1260 The result value of the action function.
1261 """
1262 if isinstance(action_tuple, tuple):
1263 action = action_tuple[0]
1264 args = action_tuple[1:]
1265 if callable(action):
1266 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tam2b48cbc2012-08-08 19:58:00 +08001267 str(action), str(args)))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001268 return action(*args)
1269 else:
1270 logging.info('action is not callable!')
1271 else:
1272 action = action_tuple
1273 if action is not None:
1274 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001275 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001276 return action()
1277 else:
1278 logging.info('action is not callable!')
1279
1280 return None
1281
1282
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001283 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1284 post_power_action=None):
1285 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1286
1287 Args:
1288 shutdown_action: a function which makes DUT shutdown, like pressing
1289 power key.
1290 pre_power_action: a function which is called before next power on.
1291 post_power_action: a function which is called after next power on.
1292
1293 Raises:
1294 error.TestFail: if the shutdown_action() failed to turn DUT off.
1295 """
1296 self._call_action(shutdown_action)
1297 logging.info('Wait to ensure DUT shut down...')
1298 try:
1299 self.wait_for_client()
1300 raise error.TestFail(
1301 'Should shut the device down after calling %s.' %
1302 str(shutdown_action))
1303 except AssertionError:
1304 logging.info(
1305 'DUT is surely shutdown. We are going to power it on again...')
1306
1307 if pre_power_action:
1308 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001309 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001310 if post_power_action:
1311 self._call_action(post_power_action)
1312
1313
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001314 def register_faft_template(self, template):
1315 """Register FAFT template, the default FAFT_STEP of each step.
1316
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001317 Any missing field falls back to the original faft_template.
1318
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001319 Args:
1320 template: A FAFT_STEP dict.
1321 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001322 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001323
1324
1325 def register_faft_sequence(self, sequence):
1326 """Register FAFT sequence.
1327
1328 Args:
1329 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1330 """
1331 self._faft_sequence = sequence
1332
1333
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001334 def run_faft_step(self, step, no_reboot=False):
1335 """Run a single FAFT step.
1336
1337 Any missing field falls back to faft_template. An empty step means
1338 running the default faft_template.
1339
1340 Args:
1341 step: A FAFT_STEP dict.
1342 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001343
1344 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001345 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001346 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001347 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001348 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1349 'firmware_action', 'install_deps_after_boot')
1350
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001351 test = {}
1352 test.update(self._faft_template)
1353 test.update(step)
1354
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001355 for key in test:
1356 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001357 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001358
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001359 if test['state_checker']:
1360 if not self._call_action(test['state_checker']):
1361 raise error.TestFail('State checker failed!')
1362
1363 self._call_action(test['userspace_action'])
1364
1365 # Don't run reboot_action and firmware_action if no_reboot is True.
1366 if not no_reboot:
1367 self._call_action(test['reboot_action'])
1368 self.wait_for_client_offline()
1369 self._call_action(test['firmware_action'])
1370
1371 if 'install_deps_after_boot' in test:
1372 self.wait_for_client(
1373 install_deps=test['install_deps_after_boot'])
1374 else:
1375 self.wait_for_client()
1376
1377
1378 def run_faft_sequence(self):
1379 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001380 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001381 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001382 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001383 logging.info('======== Running FAFT sequence step %d ========' %
1384 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001385 # Don't reboot in the last step.
1386 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001387 index += 1