1#!/usr/bin/python
2#
3# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7import logging, os, random
8from autotest_lib.client.bin import utils, test
9from autotest_lib.client.common_lib import error
10
11class kernel_VbootContextEC(test.test):
12    '''Run the vboot context ec test.'''
13    version = 1
14
15    dts_node_path = ('/proc/device-tree/firmware'
16                     '/chromeos/nonvolatile-context-storage')
17    sys_vbootcontext_path = '/sys/bus/platform/drivers/cros-ec-vbc/'
18
19    def run_once(self):
20        arch = utils.get_arch()
21        if not arch.startswith('arm'):
22            logging.info('Skip test for non-ARM arch %s', arch)
23            return
24
25        media = utils.read_file(self.dts_node_path).strip('\n\x00')
26        if media != 'cros-ec':
27            logging.info('Skip test: Vboot Context storage media is "%s"',
28                    media)
29            return
30
31        sysfs_entry = None
32        for name in os.listdir(self.sys_vbootcontext_path):
33            if name.startswith('cros-ec-vbc'):
34                sysfs_entry = os.path.join(self.sys_vbootcontext_path, name,
35                        'vboot_context')
36                break
37        else:
38            raise error.TestFail('Could not find sysfs entry under %s',
39                    self.sys_vbootcontext_path)
40
41        # Retrieve Vboot Context
42        vboot_context = utils.system_output('mosys nvram vboot read').strip()
43        try:
44            # Test read
45            vc_expect = vboot_context
46            vc_got = utils.read_file(sysfs_entry).strip('\n\x00')
47            if vc_got != vc_expect:
48                raise error.TestFail('Could not read Vboot Context: '
49                                     'Expect "%s" but got "%s"' %
50                                     (vc_expect, vc_got))
51            # Test write of a random hex string
52            vc_expect = ''.join(random.choice('0123456789abcdef')
53                                for _ in xrange(32))
54            utils.open_write_close(sysfs_entry, vc_expect)
55            vc_got = utils.system_output('mosys nvram vboot read').strip()
56            if vc_got != vc_expect:
57                raise error.TestFail('Could not write Vboot Context: '
58                                     'Expect "%s" but got "%s"' %
59                                     (vc_expect, vc_got))
60        finally:
61            # Restore Vboot Context
62            utils.run('mosys nvram vboot write "%s"' % vboot_context)
63