blob: 02939728165d404e7b69fa6e3bb0c46e8c322989 [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 Yang611dd852012-08-02 15:36:31 +0800110 # Delay between EC boot and EC console functional
111 EC_BOOT_DELAY = 2
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800112
Tom Wai-Hong Tam51ef2e12012-07-27 15:04:12 +0800113 # The developer screen timeouts fit our spec.
114 DEV_SCREEN_TIMEOUT = 30
115
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800116 CHROMEOS_MAGIC = "CHROMEOS"
117 CORRUPTED_MAGIC = "CORRUPTD"
118
Tom Wai-Hong Tamf954d172011-12-08 17:14:15 +0800119 # Recovery reason codes, copied from:
120 # vboot_reference/firmware/lib/vboot_nvstorage.h
121 # vboot_reference/firmware/lib/vboot_struct.h
122 RECOVERY_REASON = {
123 # Recovery not requested
124 'NOT_REQUESTED': '0', # 0x00
125 # Recovery requested from legacy utility
126 'LEGACY': '1', # 0x01
127 # User manually requested recovery via recovery button
128 'RO_MANUAL': '2', # 0x02
129 # RW firmware failed signature check
130 'RO_INVALID_RW': '3', # 0x03
131 # S3 resume failed
132 'RO_S3_RESUME': '4', # 0x04
133 # TPM error in read-only firmware
134 'RO_TPM_ERROR': '5', # 0x05
135 # Shared data error in read-only firmware
136 'RO_SHARED_DATA': '6', # 0x06
137 # Test error from S3Resume()
138 'RO_TEST_S3': '7', # 0x07
139 # Test error from LoadFirmwareSetup()
140 'RO_TEST_LFS': '8', # 0x08
141 # Test error from LoadFirmware()
142 'RO_TEST_LF': '9', # 0x09
143 # RW firmware failed signature check
144 'RW_NOT_DONE': '16', # 0x10
145 'RW_DEV_MISMATCH': '17', # 0x11
146 'RW_REC_MISMATCH': '18', # 0x12
147 'RW_VERIFY_KEYBLOCK': '19', # 0x13
148 'RW_KEY_ROLLBACK': '20', # 0x14
149 'RW_DATA_KEY_PARSE': '21', # 0x15
150 'RW_VERIFY_PREAMBLE': '22', # 0x16
151 'RW_FW_ROLLBACK': '23', # 0x17
152 'RW_HEADER_VALID': '24', # 0x18
153 'RW_GET_FW_BODY': '25', # 0x19
154 'RW_HASH_WRONG_SIZE': '26', # 0x1A
155 'RW_VERIFY_BODY': '27', # 0x1B
156 'RW_VALID': '28', # 0x1C
157 # Read-only normal path requested by firmware preamble, but
158 # unsupported by firmware.
159 'RW_NO_RO_NORMAL': '29', # 0x1D
160 # Firmware boot failure outside of verified boot
161 'RO_FIRMWARE': '32', # 0x20
162 # Recovery mode TPM initialization requires a system reboot.
163 # The system was already in recovery mode for some other reason
164 # when this happened.
165 'RO_TPM_REBOOT': '33', # 0x21
166 # Unspecified/unknown error in read-only firmware
167 'RO_UNSPECIFIED': '63', # 0x3F
168 # User manually requested recovery by pressing a key at developer
169 # warning screen.
170 'RW_DEV_SCREEN': '65', # 0x41
171 # No OS kernel detected
172 'RW_NO_OS': '66', # 0x42
173 # OS kernel failed signature check
174 'RW_INVALID_OS': '67', # 0x43
175 # TPM error in rewritable firmware
176 'RW_TPM_ERROR': '68', # 0x44
177 # RW firmware in dev mode, but dev switch is off.
178 'RW_DEV_MISMATCH': '69', # 0x45
179 # Shared data error in rewritable firmware
180 'RW_SHARED_DATA': '70', # 0x46
181 # Test error from LoadKernel()
182 'RW_TEST_LK': '71', # 0x47
183 # No bootable disk found
184 'RW_NO_DISK': '72', # 0x48
185 # Unspecified/unknown error in rewritable firmware
186 'RW_UNSPECIFIED': '127', # 0x7F
187 # DM-verity error
188 'KE_DM_VERITY': '129', # 0x81
189 # Unspecified/unknown error in kernel
190 'KE_UNSPECIFIED': '191', # 0xBF
191 # Recovery mode test from user-mode
192 'US_TEST': '193', # 0xC1
193 # Unspecified/unknown error in user-mode
194 'US_UNSPECIFIED': '255', # 0xFF
195 }
196
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800197 # GBB flags
198 GBB_FLAG_DEV_SCREEN_SHORT_DELAY = 0x00000001
199 GBB_FLAG_LOAD_OPTION_ROMS = 0x00000002
200 GBB_FLAG_ENABLE_ALTERNATE_OS = 0x00000004
201 GBB_FLAG_FORCE_DEV_SWITCH_ON = 0x00000008
202 GBB_FLAG_FORCE_DEV_BOOT_USB = 0x00000010
203 GBB_FLAG_DISABLE_FW_ROLLBACK_CHECK = 0x00000020
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800204 GBB_FLAG_ENTER_TRIGGERS_TONORM = 0x00000040
Tom Wai-Hong Tam1e40fa12012-07-25 16:22:24 +0800205
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800206 _faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800207 _faft_sequence = ()
208
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800209 _customized_ctrl_d_key_command = None
210 _customized_enter_key_command = None
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800211 _customized_space_key_command = None
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800212 _customized_rec_reboot_command = None
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800213 _install_image_path = None
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800214 _firmware_update = False
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800215
216
217 def initialize(self, host, cmdline_args, use_pyauto=False, use_faft=False):
218 # Parse arguments from command line
219 args = {}
220 for arg in cmdline_args:
221 match = re.search("^(\w+)=(.+)", arg)
222 if match:
223 args[match.group(1)] = match.group(2)
224
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800225 # Keep the arguments which will be used later.
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800226 if 'ctrl_d_cmd' in args:
227 self._customized_ctrl_d_key_command = args['ctrl_d_cmd']
228 logging.info('Customized Ctrl-D key command: %s' %
229 self._customized_ctrl_d_key_command)
230 if 'enter_cmd' in args:
231 self._customized_enter_key_command = args['enter_cmd']
232 logging.info('Customized Enter key command: %s' %
233 self._customized_enter_key_command)
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800234 if 'space_cmd' in args:
235 self._customized_space_key_command = args['space_cmd']
236 logging.info('Customized Space key command: %s' %
237 self._customized_space_key_command)
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800238 if 'rec_reboot_cmd' in args:
239 self._customized_rec_reboot_command = args['rec_reboot_cmd']
240 logging.info('Customized recovery reboot command: %s' %
241 self._customized_rec_reboot_command)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800242 if 'image' in args:
243 self._install_image_path = args['image']
244 logging.info('Install Chrome OS test image path: %s' %
245 self._install_image_path)
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800246 if 'firmware_update' in args and args['firmware_update'].lower() \
247 not in ('0', 'false', 'no'):
248 if self._install_image_path:
249 self._firmware_update = True
250 logging.info('Also update firmware after installing.')
251 else:
252 logging.warning('Firmware update will not not performed '
253 'since no image is specified.')
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800254
255 super(FAFTSequence, self).initialize(host, cmdline_args, use_pyauto,
256 use_faft)
Vic Yangebd6de62012-06-26 14:25:57 +0800257 if use_faft:
258 self.client_attr = FAFTClientAttribute(
259 self.faft_client.get_platform_name())
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800260
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800261
262 def setup(self):
263 """Autotest setup function."""
264 super(FAFTSequence, self).setup()
265 if not self._remote_infos['faft']['used']:
266 raise error.TestError('The use_faft flag should be enabled.')
267 self.register_faft_template({
268 'state_checker': (None),
269 'userspace_action': (None),
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +0800270 'reboot_action': (self.sync_and_warm_reboot),
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800271 'firmware_action': (None)
272 })
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800273 self.clear_set_gbb_flags(self.GBB_FLAG_FORCE_DEV_SWITCH_ON |
274 self.GBB_FLAG_DEV_SCREEN_SHORT_DELAY,
275 self.GBB_FLAG_ENTER_TRIGGERS_TONORM)
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800276 if self._install_image_path:
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800277 self.install_test_image(self._install_image_path,
278 self._firmware_update)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800279
280
281 def cleanup(self):
282 """Autotest cleanup function."""
283 self._faft_sequence = ()
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +0800284 self._faft_template = {}
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800285 super(FAFTSequence, self).cleanup()
286
287
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800288 def assert_test_image_in_usb_disk(self, usb_dev=None):
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800289 """Assert an USB disk plugged-in on servo and a test image inside.
290
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800291 Args:
292 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
293 If None, it is detected automatically.
294
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800295 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800296 error.TestError: if USB disk not detected or not a test image.
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800297 """
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800298 if usb_dev:
299 assert self.servo.get('usb_mux_sel1') == 'servo_sees_usbkey'
300 else:
Vadim Bendeburycacf29f2012-07-30 17:49:11 -0700301 self.servo.enable_usb_hub(host=True)
Tom Wai-Hong Tam91f49822011-12-28 15:44:15 +0800302 usb_dev = self.servo.probe_host_usb_dev()
303 if not usb_dev:
304 raise error.TestError(
305 'An USB disk should be plugged in the servo board.')
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800306
307 tmp_dir = tempfile.mkdtemp()
Tom Wai-Hong Tamb0e80852011-12-07 16:15:06 +0800308 utils.system('sudo mount -r -t ext2 %s3 %s' % (usb_dev, tmp_dir))
Tom Wai-Hong Tame77459e2011-11-03 17:19:46 +0800309 code = utils.system(
310 'grep -qE "(Test Build|testimage-channel)" %s/etc/lsb-release' %
311 tmp_dir, ignore_status=True)
Tom Wai-Hong Tam76c75072011-10-25 18:00:12 +0800312 utils.system('sudo umount %s' % tmp_dir)
313 os.removedirs(tmp_dir)
314 if code != 0:
315 raise error.TestError(
316 'The image in the USB disk should be a test image.')
317
318
Simran Basi741b5d42012-05-18 11:27:15 -0700319 def install_test_image(self, image_path=None, firmware_update=False):
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800320 """Install the test image specied by the path onto the USB and DUT disk.
321
322 The method first copies the image to USB disk and reboots into it via
Mike Truty49153d82012-08-21 22:27:30 -0500323 recovery mode. Then runs 'chromeos-install' (and possible
324 chromeos-firmwareupdate') to install it to DUT disk.
325
326 Sample command line:
327
328 run_remote_tests.sh --servo --board=daisy --remote=w.x.y.z \
329 --args="image=/tmp/chromiumos_test_image.bin firmware_update=True" \
330 server/site_tests/firmware_XXXX/control
331
332 This test requires an automated recovery to occur while simulating
333 inserting and removing the usb key from the servo. To allow this the
334 following hardware setup is required:
335 1. servo2 board connected via servoflex.
336 2. USB key inserted in the servo2.
337 3. servo2 connected to the dut via dut_hub_in in the usb 2.0 slot.
338 4. network connected via usb dongle in the dut in usb 3.0 slot.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800339
340 Args:
341 image_path: Path on the host to the test image.
Tom Wai-Hong Tam1a3ff742012-01-11 16:36:46 +0800342 firmware_update: Also update the firmware after installing.
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800343 """
344 build_ver, build_hash = lab_test.VerifyImageAndGetId(cros_dir,
345 image_path)
346 logging.info('Processing build: %s %s' % (build_ver, build_hash))
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800347
Mike Truty49153d82012-08-21 22:27:30 -0500348 # Reuse the servo method that uses the servo USB key to install
349 # the test image.
350 self.servo.image_to_servo_usb(image_path)
351
352 # DUT is powered off while imaging servo USB.
353 # Now turn it on.
354 self.servo.power_short_press()
355 self.wait_for_client()
356 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
357
358 install_cmd = 'chromeos-install --yes'
359 if firmware_update:
360 install_cmd += ' && chromeos-firmwareupdate --mode recovery'
361
362 self.register_faft_sequence((
363 { # Step 1, request recovery boot
364 'state_checker': (self.crossystem_checker, {
365 'mainfw_type': ('developer', 'normal'),
366 }),
367 'userspace_action': self.faft_client.request_recovery_boot,
368 'firmware_action': self.wait_fw_screen_and_plug_usb,
369 'install_deps_after_boot': True,
370 },
371 { # Step 2, expected recovery boot
372 'state_checker': (self.crossystem_checker, {
373 'mainfw_type': 'recovery',
374 'recovery_reason' : self.RECOVERY_REASON['US_TEST'],
375 }),
376 'userspace_action': (self.faft_client.run_shell_command,
377 install_cmd),
378 'reboot_action': self.cold_reboot,
379 'install_deps_after_boot': True,
380 },
381 { # Step 3, expected normal or developer boot (not recovery)
382 'state_checker': (self.crossystem_checker, {
383 'mainfw_type': ('developer', 'normal')
384 }),
385 },
386 ))
387 self.run_faft_sequence()
388 # 'Unplug' any USB keys in the servo from the dut.
389 self.servo.disable_usb_hub()
Tom Wai-Hong Tam40fd9472012-01-09 17:11:02 +0800390
391
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800392 def clear_set_gbb_flags(self, clear_mask, set_mask):
393 """Clear and set the GBB flags in the current flashrom.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800394
395 Args:
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800396 clear_mask: A mask of flags to be cleared.
397 set_mask: A mask of flags to be set.
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800398 """
399 gbb_flags = self.faft_client.get_gbb_flags()
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800400 new_flags = gbb_flags & ctypes.c_uint32(~clear_mask).value | set_mask
401
402 if (gbb_flags != new_flags):
403 logging.info('Change the GBB flags from 0x%x to 0x%x.' %
404 (gbb_flags, new_flags))
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800405 self.faft_client.run_shell_command(
Tom Wai-Hong Tamfda76e22012-08-08 17:19:10 +0800406 '/usr/share/vboot/bin/set_gbb_flags.sh 0x%x' % new_flags)
Tom Wai-Hong Tamc1c4deb2012-07-26 14:28:11 +0800407 self.faft_client.reload_firmware()
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800408 # If changing FORCE_DEV_SWITCH_ON flag, reboot to get a clear state
Tom Wai-Hong Tamfa3142e2012-08-16 11:53:58 +0800409 if ((gbb_flags ^ new_flags) & self.GBB_FLAG_FORCE_DEV_SWITCH_ON):
Tom Wai-Hong Tama2481922012-08-08 17:24:42 +0800410 self.run_faft_step({
411 'firmware_action': self.wait_fw_screen_and_ctrl_d,
412 })
Tom Wai-Hong Tam15ce5812012-07-26 14:14:18 +0800413
414
Vic Yangb4e3e742012-06-02 13:17:38 +0800415 def _open_uart_pty(self):
416 """Open UART pty and spawn pexpect object.
417
418 Returns:
419 Tuple (fd, child): fd is the file descriptor of opened UART pty, and
420 child is a fdpexpect object tied to it.
421 """
422 fd = os.open(self.servo.get("uart1_pty"), os.O_RDWR | os.O_NONBLOCK)
423 child = fdpexpect.fdspawn(fd)
424 return (fd, child)
425
426
427 def _flush_uart_pty(self, child):
428 """Flush UART output to prevent previous pending message interferring.
429
430 Args:
431 child: The fdpexpect object tied to UART pty.
432 """
433 child.sendline("")
434 while True:
435 try:
436 child.expect(".", timeout=0.01)
437 except pexpect.TIMEOUT:
438 break
439
440
441 def _uart_send(self, child, line):
442 """Flush and send command through UART.
443
444 Args:
445 child: The pexpect object tied to UART pty.
446 line: String to send through UART.
447
448 Raises:
449 error.TestFail: Raised when writing to UART fails.
450 """
451 logging.info("Sending UART command: %s" % line)
452 self._flush_uart_pty(child)
453 if child.sendline(line) != len(line) + 1:
454 raise error.TestFail("Failed to send UART command.")
455
456
457 def send_uart_command(self, command):
458 """Send command through UART.
459
460 This function open UART pty when called, and then command is sent
461 through UART.
462
463 Args:
464 command: The command string to send.
465
466 Raises:
467 error.TestFail: Raised when writing to UART fails.
468 """
469 (fd, child) = self._open_uart_pty()
470 try:
471 self._uart_send(child, command)
472 finally:
473 os.close(fd)
474
475
476 def send_uart_command_get_output(self, command, regex_list, timeout=1):
477 """Send command through UART and wait for response.
478
479 This function waits for response message matching regular expressions.
480
481 Args:
482 command: The command sent.
483 regex_list: List of regular expressions used to match response message.
484 Note, list must be ordered.
485
486 Returns:
487 List of match objects of response message.
488
489 Raises:
490 error.TestFail: If timed out waiting for EC response.
491 """
492 if not isinstance(regex_list, list):
493 regex_list = [regex_list]
494 result_list = []
495 (fd, child) = self._open_uart_pty()
496 try:
497 self._uart_send(child, command)
498 for regex in regex_list:
499 child.expect(regex, timeout=timeout)
500 result_list.append(child.match)
501 except pexpect.TIMEOUT:
502 raise error.TestFail("Timeout waiting for UART response.")
503 finally:
504 os.close(fd)
505 return result_list
506
507
Vic Yang4d72cb62012-07-24 11:51:09 +0800508 def check_ec_capability(self, required_cap=[]):
509 """Check if current platform has required EC capabilities.
510
511 Args:
512 required_cap: A list containing required EC capabilities. Pass in
513 None to only check for presence of Chrome EC.
514
515 Returns:
516 True if requirements are met. Otherwise, False.
517 """
518 if not self.client_attr.chrome_ec:
519 logging.warn('Requires Chrome EC to run this test.')
520 return False
521
522 for cap in required_cap:
523 if cap not in self.client_attr.ec_capability:
524 logging.warn('Requires EC capability "%s" to run this test.' %
525 cap)
526 return False
527
528 return True
529
530
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +0800531 def _parse_crossystem_output(self, lines):
532 """Parse the crossystem output into a dict.
533
534 Args:
535 lines: The list of crossystem output strings.
536
537 Returns:
538 A dict which contains the crossystem keys/values.
539
540 Raises:
541 error.TestError: If wrong format in crossystem output.
542
543 >>> seq = FAFTSequence()
544 >>> seq._parse_crossystem_output([ \
545 "arch = x86 # Platform architecture", \
546 "cros_debug = 1 # OS should allow debug", \
547 ])
548 {'cros_debug': '1', 'arch': 'x86'}
549 >>> seq._parse_crossystem_output([ \
550 "arch=x86", \
551 ])
552 Traceback (most recent call last):
553 ...
554 TestError: Failed to parse crossystem output: arch=x86
555 >>> seq._parse_crossystem_output([ \
556 "arch = x86 # Platform architecture", \
557 "arch = arm # Platform architecture", \
558 ])
559 Traceback (most recent call last):
560 ...
561 TestError: Duplicated crossystem key: arch
562 """
563 pattern = "^([^ =]*) *= *(.*[^ ]) *# [^#]*$"
564 parsed_list = {}
565 for line in lines:
566 matched = re.match(pattern, line.strip())
567 if not matched:
568 raise error.TestError("Failed to parse crossystem output: %s"
569 % line)
570 (name, value) = (matched.group(1), matched.group(2))
571 if name in parsed_list:
572 raise error.TestError("Duplicated crossystem key: %s" % name)
573 parsed_list[name] = value
574 return parsed_list
575
576
577 def crossystem_checker(self, expected_dict):
578 """Check the crossystem values matched.
579
580 Given an expect_dict which describes the expected crossystem values,
581 this function check the current crossystem values are matched or not.
582
583 Args:
584 expected_dict: A dict which contains the expected values.
585
586 Returns:
587 True if the crossystem value matched; otherwise, False.
588 """
589 lines = self.faft_client.run_shell_command_get_output('crossystem')
590 got_dict = self._parse_crossystem_output(lines)
591 for key in expected_dict:
592 if key not in got_dict:
593 logging.info('Expected key "%s" not in crossystem result' % key)
594 return False
595 if isinstance(expected_dict[key], str):
596 if got_dict[key] != expected_dict[key]:
597 logging.info("Expected '%s' value '%s' but got '%s'" %
598 (key, expected_dict[key], got_dict[key]))
599 return False
600 elif isinstance(expected_dict[key], tuple):
601 # Expected value is a tuple of possible actual values.
602 if got_dict[key] not in expected_dict[key]:
603 logging.info("Expected '%s' values %s but got '%s'" %
604 (key, str(expected_dict[key]), got_dict[key]))
605 return False
606 else:
607 logging.info("The expected_dict is neither a str nor a dict.")
608 return False
609 return True
610
611
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800612 def root_part_checker(self, expected_part):
613 """Check the partition number of the root device matched.
614
615 Args:
616 expected_part: A string containing the number of the expected root
617 partition.
618
619 Returns:
620 True if the currect root partition number matched; otherwise, False.
621 """
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800622 part = self.faft_client.get_root_part()[-1]
623 if self.ROOTFS_MAP[expected_part] != part:
624 logging.info("Expected root part %s but got %s" %
625 (self.ROOTFS_MAP[expected_part], part))
626 return False
627 return True
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800628
629
Vic Yang59cac9c2012-05-21 15:28:42 +0800630 def ec_act_copy_checker(self, expected_copy):
631 """Check the EC running firmware copy matches.
632
633 Args:
634 expected_copy: A string containing 'RO', 'A', or 'B' indicating
635 the expected copy of EC running firmware.
636
637 Returns:
638 True if the current EC running copy matches; otherwise, False.
639 """
640 lines = self.faft_client.run_shell_command_get_output('ectool version')
641 pattern = re.compile("Firmware copy: (.*)")
642 for line in lines:
643 matched = pattern.match(line)
644 if matched and matched.group(1) == expected_copy:
645 return True
646 return False
647
648
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800649 def check_root_part_on_non_recovery(self, part):
650 """Check the partition number of root device and on normal/dev boot.
651
652 Returns:
653 True if the root device matched and on normal/dev boot;
654 otherwise, False.
655 """
656 return self.root_part_checker(part) and \
657 self.crossystem_checker({
658 'mainfw_type': ('normal', 'developer'),
Tom Wai-Hong Tam07278c22012-02-08 16:53:00 +0800659 })
660
661
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800662 def _join_part(self, dev, part):
663 """Return a concatenated string of device and partition number.
664
665 Args:
666 dev: A string of device, e.g.'/dev/sda'.
667 part: A string of partition number, e.g.'3'.
668
669 Returns:
670 A concatenated string of device and partition number, e.g.'/dev/sda3'.
671
672 >>> seq = FAFTSequence()
673 >>> seq._join_part('/dev/sda', '3')
674 '/dev/sda3'
675 >>> seq._join_part('/dev/mmcblk0', '2')
676 '/dev/mmcblk0p2'
677 """
678 if 'mmcblk' in dev:
679 return dev + 'p' + part
680 else:
681 return dev + part
682
683
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800684 def copy_kernel_and_rootfs(self, from_part, to_part):
685 """Copy kernel and rootfs from from_part to to_part.
686
687 Args:
688 from_part: A string of partition number to be copied from.
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800689 to_part: A string of partition number to be copied to.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800690 """
691 root_dev = self.faft_client.get_root_dev()
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800692 logging.info('Copying kernel from %s to %s. Please wait...' %
693 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800694 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800695 (self._join_part(root_dev, self.KERNEL_MAP[from_part]),
696 self._join_part(root_dev, self.KERNEL_MAP[to_part])))
697 logging.info('Copying rootfs from %s to %s. Please wait...' %
698 (from_part, to_part))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800699 self.faft_client.run_shell_command('dd if=%s of=%s bs=4M' %
Tom Wai-Hong Tamf2103be2011-11-10 07:26:56 +0800700 (self._join_part(root_dev, self.ROOTFS_MAP[from_part]),
701 self._join_part(root_dev, self.ROOTFS_MAP[to_part])))
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800702
703
704 def ensure_kernel_boot(self, part):
705 """Ensure the request kernel boot.
706
707 If not, it duplicates the current kernel to the requested kernel
708 and sets the requested higher priority to ensure it boot.
709
710 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800711 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800712 """
713 if not self.root_part_checker(part):
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800714 if self.faft_client.diff_kernel_a_b():
715 self.copy_kernel_and_rootfs(
716 from_part=self.OTHER_KERNEL_MAP[part],
717 to_part=part)
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800718 self.run_faft_step({
719 'userspace_action': (self.reset_and_prioritize_kernel, part),
720 })
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800721
722
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800723 def send_ctrl_d_to_dut(self):
724 """Send Ctrl-D key to DUT."""
725 if self._customized_ctrl_d_key_command:
726 logging.info('running the customized Ctrl-D key command')
727 os.system(self._customized_ctrl_d_key_command)
728 else:
729 self.servo.ctrl_d()
730
731
732 def send_enter_to_dut(self):
733 """Send Enter key to DUT."""
734 if self._customized_enter_key_command:
735 logging.info('running the customized Enter key command')
736 os.system(self._customized_enter_key_command)
737 else:
738 self.servo.enter_key()
739
740
Tom Wai-Hong Tam9e61e662012-08-01 15:10:07 +0800741 def send_space_to_dut(self):
742 """Send Space key to DUT."""
743 if self._customized_space_key_command:
744 logging.info('running the customized Space key command')
745 os.system(self._customized_space_key_command)
746 else:
747 # Send the alternative key combinaton of space key to servo.
748 self.servo.ctrl_refresh_key()
749
750
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800751 def wait_fw_screen_and_ctrl_d(self):
752 """Wait for firmware warning screen and press Ctrl-D."""
753 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam1db43832011-12-09 10:50:56 +0800754 self.send_ctrl_d_to_dut()
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800755
756
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800757 def wait_fw_screen_and_trigger_recovery(self, need_dev_transition=False):
758 """Wait for firmware warning screen and trigger recovery boot."""
759 time.sleep(self.FIRMWARE_SCREEN_DELAY)
760 self.send_enter_to_dut()
761
762 # For Alex/ZGB, there is a dev warning screen in text mode.
763 # Skip it by pressing Ctrl-D.
764 if need_dev_transition:
765 time.sleep(self.TEXT_SCREEN_DELAY)
766 self.send_ctrl_d_to_dut()
767
768
Mike Truty49153d82012-08-21 22:27:30 -0500769 def wait_fw_screen_and_unplug_usb(self):
770 """Wait for firmware warning screen and then unplug the servo USB."""
Tom Wai-Hong Tama79574c2012-02-07 09:29:03 +0800771 time.sleep(self.USB_LOAD_DELAY)
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800772 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
773 time.sleep(self.USB_PLUG_DELAY)
Mike Truty49153d82012-08-21 22:27:30 -0500774
775
776 def wait_fw_screen_and_plug_usb(self):
777 """Wait for firmware warning screen and then unplug and plug the USB."""
778 self.wait_fw_screen_and_unplug_usb()
Tom Wai-Hong Tam5d2f4702011-12-06 10:42:31 +0800779 self.servo.set('usb_mux_sel1', 'dut_sees_usbkey')
780
781
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800782 def wait_fw_screen_and_press_power(self):
783 """Wait for firmware warning screen and press power button."""
784 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tam7317c042012-08-14 11:59:06 +0800785 # While the firmware screen, the power button probing loop sleeps
786 # 0.25 second on every scan. Use the normal delay (1.2 second) for
787 # power press.
788 self.servo.power_normal_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800789
790
Tom Wai-Hong Tam4f5e5922012-07-27 16:23:15 +0800791 def wait_longer_fw_screen_and_press_power(self):
792 """Wait for firmware screen without timeout and press power button."""
793 time.sleep(self.DEV_SCREEN_TIMEOUT)
794 self.wait_fw_screen_and_press_power()
795
796
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800797 def wait_fw_screen_and_close_lid(self):
798 """Wait for firmware warning screen and close lid."""
799 time.sleep(self.FIRMWARE_SCREEN_DELAY)
800 self.servo.lid_close()
801
802
Tom Wai-Hong Tam473cfa72012-07-27 17:16:57 +0800803 def wait_longer_fw_screen_and_close_lid(self):
804 """Wait for firmware screen without timeout and close lid."""
805 time.sleep(self.FIRMWARE_SCREEN_DELAY)
806 self.wait_fw_screen_and_close_lid()
807
808
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800809 def setup_tried_fwb(self, tried_fwb):
810 """Setup for fw B tried state.
811
812 It makes sure the system in the requested fw B tried state. If not, it
813 tries to do so.
814
815 Args:
816 tried_fwb: True if requested in tried_fwb=1; False if tried_fwb=0.
817 """
818 if tried_fwb:
819 if not self.crossystem_checker({'tried_fwb': '1'}):
820 logging.info(
821 'Firmware is not booted with tried_fwb. Reboot into it.')
822 self.run_faft_step({
823 'userspace_action': self.faft_client.set_try_fw_b,
824 })
825 else:
826 if not self.crossystem_checker({'tried_fwb': '0'}):
827 logging.info(
828 'Firmware is booted with tried_fwb. Reboot to clear.')
829 self.run_faft_step({})
830
831
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800832 def enable_rec_mode_and_reboot(self):
833 """Switch to rec mode and reboot.
834
835 This method emulates the behavior of the old physical recovery switch,
836 i.e. switch ON + reboot + switch OFF, and the new keyboard controlled
837 recovery mode, i.e. just press Power + Esc + Refresh.
838 """
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800839 if self._customized_rec_reboot_command:
840 logging.info('running the customized rec reboot command')
841 os.system(self._customized_rec_reboot_command)
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800842 elif self.client_attr.chrome_ec:
Vic Yang81273092012-08-21 15:57:09 +0800843 # Cold reset to clear EC_IN_RW signal
844 self.servo.cold_reset()
845 self.send_uart_command("reboot ap-off")
Vic Yang611dd852012-08-02 15:36:31 +0800846 time.sleep(self.EC_BOOT_DELAY)
847 self.send_uart_command("hostevent set 0x4000")
848 self.servo.power_short_press()
Tom Wai-Hong Tamac943172012-08-01 10:38:39 +0800849 else:
850 self.servo.enable_recovery_mode()
851 self.cold_reboot()
852 time.sleep(self.EC_REBOOT_DELAY)
853 self.servo.disable_recovery_mode()
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800854
855
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800856 def enable_dev_mode_and_reboot(self):
857 """Switch to developer mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800858 if self.client_attr.keyboard_dev:
859 self.enable_keyboard_dev_mode()
860 else:
861 self.servo.enable_development_mode()
862 self.faft_client.run_shell_command(
863 'chromeos-firmwareupdate --mode todev && reboot')
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800864
865
Tom Wai-Hong Tam0b9e6d72012-07-31 20:54:06 +0800866 def enable_normal_mode_and_reboot(self):
867 """Switch to normal mode and reboot."""
Vic Yange7553162012-06-20 16:20:47 +0800868 if self.client_attr.keyboard_dev:
869 self.disable_keyboard_dev_mode()
870 else:
871 self.servo.disable_development_mode()
872 self.faft_client.run_shell_command(
873 'chromeos-firmwareupdate --mode tonormal && reboot')
874
875
876 def wait_fw_screen_and_switch_keyboard_dev_mode(self, dev):
877 """Wait for firmware screen and then switch into or out of dev mode.
878
879 Args:
880 dev: True if switching into dev mode. Otherwise, False.
881 """
882 time.sleep(self.FIRMWARE_SCREEN_DELAY)
883 if dev:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800884 self.send_ctrl_d_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800885 else:
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800886 self.send_enter_to_dut()
Tom Wai-Hong Tam1408f172012-07-31 15:06:21 +0800887 time.sleep(self.FIRMWARE_SCREEN_DELAY)
Tom Wai-Hong Tamfe314ac2012-07-25 14:14:17 +0800888 self.send_enter_to_dut()
Vic Yange7553162012-06-20 16:20:47 +0800889
890
891 def enable_keyboard_dev_mode(self):
892 logging.info("Enabling keyboard controlled developer mode")
Tom Wai-Hong Tamf1a17d72012-07-26 11:39:52 +0800893 # Plug out USB disk for preventing recovery boot without warning
894 self.servo.set('usb_mux_sel1', 'servo_sees_usbkey')
Vic Yange7553162012-06-20 16:20:47 +0800895 # Rebooting EC with rec mode on. Should power on AP.
Tom Wai-Hong Tama373f802012-07-31 21:16:48 +0800896 self.enable_rec_mode_and_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800897 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800898 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=True)
Vic Yange7553162012-06-20 16:20:47 +0800899
900
901 def disable_keyboard_dev_mode(self):
902 logging.info("Disabling keyboard controlled developer mode")
Tom Wai-Hong Tamb0b3f412012-08-13 17:17:06 +0800903 if not self.client_attr.chrome_ec:
Vic Yang611dd852012-08-02 15:36:31 +0800904 self.servo.disable_recovery_mode()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800905 self.cold_reboot()
Tom Wai-Hong Tam8c54eb82012-08-01 10:31:07 +0800906 self.wait_for_client_offline()
Vic Yange7553162012-06-20 16:20:47 +0800907 self.wait_fw_screen_and_switch_keyboard_dev_mode(dev=False)
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +0800908
909
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800910 def setup_dev_mode(self, dev_mode):
911 """Setup for development mode.
912
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800913 It makes sure the system in the requested normal/dev mode. If not, it
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800914 tries to do so.
915
916 Args:
917 dev_mode: True if requested in dev mode; False if normal mode.
918 """
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800919 # Change the default firmware_action for dev mode passing the fw screen.
920 self.register_faft_template({
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800921 'firmware_action': (self.wait_fw_screen_and_ctrl_d if dev_mode
922 else None),
923 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800924 if dev_mode:
Vic Yange7553162012-06-20 16:20:47 +0800925 if (not self.client_attr.keyboard_dev and
926 not self.crossystem_checker({'devsw_cur': '1'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800927 logging.info('Dev switch is not on. Now switch it on.')
928 self.servo.enable_development_mode()
929 if not self.crossystem_checker({'devsw_boot': '1',
930 'mainfw_type': 'developer'}):
931 logging.info('System is not in dev mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800932 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800933 'userspace_action': None if self.client_attr.keyboard_dev
934 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800935 'chromeos-firmwareupdate --mode todev && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800936 'reboot_action': self.enable_keyboard_dev_mode if
937 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800938 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800939 else:
Vic Yange7553162012-06-20 16:20:47 +0800940 if (not self.client_attr.keyboard_dev and
941 not self.crossystem_checker({'devsw_cur': '0'})):
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800942 logging.info('Dev switch is not off. Now switch it off.')
943 self.servo.disable_development_mode()
944 if not self.crossystem_checker({'devsw_boot': '0',
945 'mainfw_type': 'normal'}):
946 logging.info('System is not in normal mode. Reboot into it.')
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800947 self.run_faft_step({
Vic Yange7553162012-06-20 16:20:47 +0800948 'userspace_action': None if self.client_attr.keyboard_dev
949 else (self.faft_client.run_shell_command,
Tom Wai-Hong Tamc7ecfca2011-12-06 11:12:31 +0800950 'chromeos-firmwareupdate --mode tonormal && reboot'),
Vic Yange7553162012-06-20 16:20:47 +0800951 'reboot_action': self.disable_keyboard_dev_mode if
952 self.client_attr.keyboard_dev else None,
Tom Wai-Hong Tamfd590c92011-11-25 11:50:57 +0800953 })
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800954
955
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800956 def setup_kernel(self, part):
957 """Setup for kernel test.
958
959 It makes sure both kernel A and B bootable and the current boot is
960 the requested kernel part.
961
962 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800963 part: A string of kernel partition number or 'a'/'b'.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800964 """
965 self.ensure_kernel_boot(part)
Tom Wai-Hong Tam622d0ba2012-08-15 16:29:05 +0800966 if self.faft_client.diff_kernel_a_b():
967 self.copy_kernel_and_rootfs(from_part=part,
968 to_part=self.OTHER_KERNEL_MAP[part])
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800969 self.reset_and_prioritize_kernel(part)
970
971
972 def reset_and_prioritize_kernel(self, part):
973 """Make the requested partition highest priority.
974
975 This function also reset kerenl A and B to bootable.
976
977 Args:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +0800978 part: A string of partition number to be prioritized.
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800979 """
980 root_dev = self.faft_client.get_root_dev()
981 # Reset kernel A and B to bootable.
982 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
983 (self.KERNEL_MAP['a'], root_dev))
984 self.faft_client.run_shell_command('cgpt add -i%s -P1 -S1 -T0 %s' %
985 (self.KERNEL_MAP['b'], root_dev))
986 # Set kernel part highest priority.
987 self.faft_client.run_shell_command('cgpt prioritize -i%s %s' %
988 (self.KERNEL_MAP[part], root_dev))
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +0800989 # Safer to sync and wait until the cgpt status written to the disk.
990 self.faft_client.run_shell_command('sync')
991 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tamcfda61f2011-11-02 17:41:01 +0800992
993
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800994 def warm_reboot(self):
995 """Request a warm reboot.
996
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800997 A wrapper for underlying servo warm reset.
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +0800998 """
Tom Wai-Hong Tamb06f0802012-07-31 16:27:50 +0800999 # Use cold reset if the warm reset is broken.
1000 if self.client_attr.broken_warm_reset:
1001 self.servo.cold_reset()
1002 else:
1003 self.servo.warm_reset()
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001004
1005
1006 def cold_reboot(self):
1007 """Request a cold reboot.
1008
1009 A wrapper for underlying servo cold reset.
1010 """
Tom Wai-Hong Tama276d0a2012-08-22 11:15:17 +08001011 if self.client_attr.platform == 'Parrot':
1012 self.servo.set('pwr_button', 'press')
1013 self.servo.set('cold_reset', 'on')
1014 self.servo.set('cold_reset', 'off')
1015 time.sleep(self.POWER_BTN_DELAY)
1016 self.servo.set('pwr_button', 'release')
1017 elif self.check_ec_capability():
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001018 # We don't use servo.cold_reset() here because software sync is
1019 # not yet finished, and device may or may not come up after cold
1020 # reset. Pressing power button before firmware comes up solves this.
1021 #
1022 # The correct behavior should be (not work now):
1023 # - If rebooting EC with rec mode on, power on AP and it boots
1024 # into recovery mode.
1025 # - If rebooting EC with rec mode off, power on AP for software
1026 # sync. Then AP checks if lid open or not. If lid open, continue;
1027 # otherwise, shut AP down and need servo for a power button
1028 # press.
1029 self.servo.set('cold_reset', 'on')
1030 self.servo.set('cold_reset', 'off')
1031 time.sleep(self.POWER_BTN_DELAY)
1032 self.servo.power_short_press()
1033 else:
1034 self.servo.cold_reset()
1035
1036
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001037 def sync_and_warm_reboot(self):
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001038 """Request the client sync and do a warm reboot.
1039
1040 This is the default reboot action on FAFT.
1041 """
1042 self.faft_client.run_shell_command('sync')
Tom Wai-Hong Tam6a863ba2011-12-08 10:13:28 +08001043 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001044 self.warm_reboot()
Tom Wai-Hong Tamf1e34972011-11-02 17:07:04 +08001045
1046
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001047 def sync_and_cold_reboot(self):
1048 """Request the client sync and do a cold reboot.
1049
1050 This reboot action is used to reset EC for recovery mode.
1051 """
1052 self.faft_client.run_shell_command('sync')
1053 time.sleep(self.SYNC_DELAY)
Tom Wai-Hong Tam7ad99ab2012-07-30 19:30:51 +08001054 self.cold_reboot()
Tom Wai-Hong Tamb21b6b42012-07-26 10:46:30 +08001055
1056
Vic Yang59cac9c2012-05-21 15:28:42 +08001057 def sync_and_ec_reboot(self):
1058 """Request the client sync and do a EC triggered reboot."""
1059 self.faft_client.run_shell_command('sync')
1060 time.sleep(self.SYNC_DELAY)
1061 self.faft_client.run_shell_command('(sleep %d; ectool reboot_ec)&' %
1062 self.EC_REBOOT_DELAY)
Vic Yangf86728a2012-07-30 10:44:07 +08001063 time.sleep(self.EC_REBOOT_DELAY)
1064 self.check_lid_and_power_on()
1065
1066
1067 def check_lid_and_power_on(self):
1068 """
1069 On devices with EC software sync, system powers on after EC reboots if
1070 lid is open. Otherwise, the EC shuts down CPU after about 3 seconds.
1071 This method checks lid switch state and presses power button if
1072 necessary.
1073 """
1074 if self.servo.get("lid_open") == "no":
1075 time.sleep(self.SOFTWARE_SYNC_DELAY)
1076 self.servo.power_short_press()
Vic Yang59cac9c2012-05-21 15:28:42 +08001077
1078
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001079 def _modify_usb_kernel(self, usb_dev, from_magic, to_magic):
1080 """Modify the kernel header magic in USB stick.
1081
1082 The kernel header magic is the first 8-byte of kernel partition.
1083 We modify it to make it fail on kernel verification check.
1084
1085 Args:
1086 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1087 from_magic: A string of magic which we change it from.
1088 to_magic: A string of magic which we change it to.
1089
1090 Raises:
1091 error.TestError: if failed to change magic.
1092 """
1093 assert len(from_magic) == 8
1094 assert len(to_magic) == 8
Tom Wai-Hong Tama1d9a0f2011-12-23 09:13:33 +08001095 # USB image only contains one kernel.
1096 kernel_part = self._join_part(usb_dev, self.KERNEL_MAP['a'])
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001097 read_cmd = "sudo dd if=%s bs=8 count=1 2>/dev/null" % kernel_part
1098 current_magic = utils.system_output(read_cmd)
1099 if current_magic == to_magic:
1100 logging.info("The kernel magic is already %s." % current_magic)
1101 return
1102 if current_magic != from_magic:
1103 raise error.TestError("Invalid kernel image on USB: wrong magic.")
1104
1105 logging.info('Modify the kernel magic in USB, from %s to %s.' %
1106 (from_magic, to_magic))
1107 write_cmd = ("echo -n '%s' | sudo dd of=%s oflag=sync conv=notrunc "
1108 " 2>/dev/null" % (to_magic, kernel_part))
1109 utils.system(write_cmd)
1110
1111 if utils.system_output(read_cmd) != to_magic:
1112 raise error.TestError("Failed to write new magic.")
1113
1114
1115 def corrupt_usb_kernel(self, usb_dev):
1116 """Corrupt USB kernel by modifying its magic from CHROMEOS to CORRUPTD.
1117
1118 Args:
1119 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1120 """
1121 self._modify_usb_kernel(usb_dev, self.CHROMEOS_MAGIC,
1122 self.CORRUPTED_MAGIC)
1123
1124
1125 def restore_usb_kernel(self, usb_dev):
1126 """Restore USB kernel by modifying its magic from CORRUPTD to CHROMEOS.
1127
1128 Args:
1129 usb_dev: A string of USB stick path on the host, like '/dev/sdc'.
1130 """
1131 self._modify_usb_kernel(usb_dev, self.CORRUPTED_MAGIC,
1132 self.CHROMEOS_MAGIC)
1133
1134
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001135 def _call_action(self, action_tuple):
1136 """Call the action function with/without arguments.
1137
1138 Args:
1139 action_tuple: A function, or a tuple which consisted of a function
1140 and its arguments (if any).
1141
1142 Returns:
1143 The result value of the action function.
1144 """
1145 if isinstance(action_tuple, tuple):
1146 action = action_tuple[0]
1147 args = action_tuple[1:]
1148 if callable(action):
1149 logging.info('calling %s with parameter %s' % (
Tom Wai-Hong Tam2b48cbc2012-08-08 19:58:00 +08001150 str(action), str(args)))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001151 return action(*args)
1152 else:
1153 logging.info('action is not callable!')
1154 else:
1155 action = action_tuple
1156 if action is not None:
1157 if callable(action):
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001158 logging.info('calling %s' % str(action))
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001159 return action()
1160 else:
1161 logging.info('action is not callable!')
1162
1163 return None
1164
1165
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001166 def run_shutdown_process(self, shutdown_action, pre_power_action=None,
1167 post_power_action=None):
1168 """Run shutdown_action(), which makes DUT shutdown, and power it on.
1169
1170 Args:
1171 shutdown_action: a function which makes DUT shutdown, like pressing
1172 power key.
1173 pre_power_action: a function which is called before next power on.
1174 post_power_action: a function which is called after next power on.
1175
1176 Raises:
1177 error.TestFail: if the shutdown_action() failed to turn DUT off.
1178 """
1179 self._call_action(shutdown_action)
1180 logging.info('Wait to ensure DUT shut down...')
1181 try:
1182 self.wait_for_client()
1183 raise error.TestFail(
1184 'Should shut the device down after calling %s.' %
1185 str(shutdown_action))
1186 except AssertionError:
1187 logging.info(
1188 'DUT is surely shutdown. We are going to power it on again...')
1189
1190 if pre_power_action:
1191 self._call_action(pre_power_action)
Tom Wai-Hong Tam610262a2012-01-12 14:16:53 +08001192 self.servo.power_short_press()
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001193 if post_power_action:
1194 self._call_action(post_power_action)
1195
1196
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001197 def register_faft_template(self, template):
1198 """Register FAFT template, the default FAFT_STEP of each step.
1199
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001200 Any missing field falls back to the original faft_template.
1201
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001202 Args:
1203 template: A FAFT_STEP dict.
1204 """
Tom Wai-Hong Tam109f63c2011-12-08 14:58:27 +08001205 self._faft_template.update(template)
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001206
1207
1208 def register_faft_sequence(self, sequence):
1209 """Register FAFT sequence.
1210
1211 Args:
1212 sequence: A FAFT_SEQUENCE array which consisted of FAFT_STEP dicts.
1213 """
1214 self._faft_sequence = sequence
1215
1216
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001217 def run_faft_step(self, step, no_reboot=False):
1218 """Run a single FAFT step.
1219
1220 Any missing field falls back to faft_template. An empty step means
1221 running the default faft_template.
1222
1223 Args:
1224 step: A FAFT_STEP dict.
1225 no_reboot: True to prevent running reboot_action and firmware_action.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001226
1227 Raises:
Tom Wai-Hong Tama9c1a502011-11-10 06:39:26 +08001228 error.TestFail: An error when the test failed.
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001229 error.TestError: An error when the given step is not valid.
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001230 """
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001231 FAFT_STEP_KEYS = ('state_checker', 'userspace_action', 'reboot_action',
1232 'firmware_action', 'install_deps_after_boot')
1233
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001234 test = {}
1235 test.update(self._faft_template)
1236 test.update(step)
1237
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001238 for key in test:
1239 if key not in FAFT_STEP_KEYS:
Tom Wai-Hong Tam78709592011-12-19 11:16:50 +08001240 raise error.TestError('Invalid key in FAFT step: %s', key)
Tom Wai-Hong Tamd8445dc2011-12-15 09:00:04 +08001241
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001242 if test['state_checker']:
1243 if not self._call_action(test['state_checker']):
1244 raise error.TestFail('State checker failed!')
1245
1246 self._call_action(test['userspace_action'])
1247
1248 # Don't run reboot_action and firmware_action if no_reboot is True.
1249 if not no_reboot:
1250 self._call_action(test['reboot_action'])
1251 self.wait_for_client_offline()
1252 self._call_action(test['firmware_action'])
1253
1254 if 'install_deps_after_boot' in test:
1255 self.wait_for_client(
1256 install_deps=test['install_deps_after_boot'])
1257 else:
1258 self.wait_for_client()
1259
1260
1261 def run_faft_sequence(self):
1262 """Run FAFT sequence which was previously registered."""
Tom Wai-Hong Tama70f0fe2011-09-02 18:28:47 +08001263 sequence = self._faft_sequence
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001264 index = 1
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001265 for step in sequence:
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001266 logging.info('======== Running FAFT sequence step %d ========' %
1267 index)
Tom Wai-Hong Tam2c50dff2011-11-11 07:01:01 +08001268 # Don't reboot in the last step.
1269 self.run_faft_step(step, no_reboot=(step is sequence[-1]))
Tom Wai-Hong Tame8f291a2011-12-08 22:03:53 +08001270 index += 1