aboutsummaryrefslogtreecommitdiffstats
path: root/testhal/STM32L1xx/EXT/mcuconf.h
blob: a75fb49cf7f4471501cf3a16604ddb2f5c23d7b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
    ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
                 2011 Giovanni Di Sirio.

    This file is part of ChibiOS/RT.

    ChibiOS/RT is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    ChibiOS/RT is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 * STM32L1xx drivers configuration.
 * The following settings override the default settings present in
 * the various device driver implementation headers.
 * Note that the settings for each driver only have effect if the whole
 * driver is enabled in halconf.h.
 *
 * IRQ priorities:
 * 15...0       Lowest...Highest.
 *
 * DMA priorities:
 * 0...3        Lowest...Highest.
 */

/*
 * HAL driver system settings.
 */
#define STM32_NO_INIT                       FALSE
#define STM32_VOS                           STM32_VOS_1P8
#define STM32_HSI_ENABLED                   TRUE
#define STM32_LSI_ENABLED                   TRUE
#define STM32_HSE_ENABLED                   FALSE
#define STM32_LSE_ENABLED                   TRUE
#define STM32_ADC_CLOCK_ENABLED             TRUE
#define STM32_USB_CLOCK_ENABLED             TRUE
#define STM32_MSIRANGE                      STM32_MSIRANGE_2M
#define STM32_SW                            STM32_SW_PLL
#define STM32_PLLSRC                        STM32_PLLSRC_HSI
#define STM32_PLLMUL_VALUE                  6
#define STM32_PLLDIV_VALUE                  3
#define STM32_HPRE                          STM32_HPRE_DIV1
#define STM32_PPRE1                         STM32_PPRE1_DIV1
#define STM32_PPRE2                         STM32_PPRE2_DIV1
#define STM32_MCOSEL                        STM32_MCOSEL_NOCLOCK
#define STM32_MCOPRE                        STM32_MCOPRE_DIV1
#define STM32_RTCSEL                        STM32_RTCSEL_LSE
#define STM32_RTCPRE                        STM32_RTCPRE_DIV2

/*
 * ADC driver system settings.
 */
#define STM32_ADC_USE_ADC1                  TRUE
#define STM32_ADC_ADC1_DMA_PRIORITY         2
#define STM32_ADC_IRQ_PRIORITY              5
#define STM32_ADC_ADC1_DMA_IRQ_PRIORITY     5

/*
 * CAN driver system settings.
 */
#define STM32_CAN_USE_CAN1                  TRUE
#define STM32_CAN_CAN1_IRQ_PRIORITY         11

/*
 * EXT driver system settings.
 */
#define STM32_EXT_EXTI0_IRQ_PRIORITY        6
#define STM32_EXT_EXTI1_IRQ_PRIORITY        6
#define STM32_EXT_EXTI2_IRQ_PRIORITY        6
#define STM32_EXT_EXTI3_IRQ_PRIORITY        6
#define STM32_EXT_EXTI4_IRQ_PRIORITY        6
#define STM32_EXT_EXTI5_9_IRQ_PRIORITY      6
#define STM32_EXT_EXTI10_15_IRQ_PRIORITY    6
#define STM32_EXT_EXTI16_IRQ_PRIORITY       6
#define STM32_EXT_EXTI17_IRQ_PRIORITY       6
#define STM32_EXT_EXTI18_IRQ_PRIORITY       6
#define STM32_EXT_EXTI19_IRQ_PRIORITY       6

/*
 * GPT driver system settings.
 */
#define STM32_GPT_USE_TIM1                  FALSE
#define STM32_GPT_USE_TIM2                  TRUE
#define STM32_GPT_USE_TIM3                  TRUE
#define STM32_GPT_USE_TIM4                  TRUE
#define STM32_GPT_USE_TIM5                  FALSE
#define STM32_GPT_USE_TIM8                  FALSE
#define STM32_GPT_TIM1_IRQ_PRIORITY         7
#define STM32_GPT_TIM2_IRQ_PRIORITY         7
#define STM32_GPT_TIM3_IRQ_PRIORITY         7
#define STM32_GPT_TIM4_IRQ_PRIORITY         7
#define STM32_GPT_TIM5_IRQ_PRIORITY         7
#define STM32_GPT_TIM8_IRQ_PRIORITY         7

/*
 * ICU driver system settings.
 */
#define STM32_ICU_USE_TIM1                  FALSE
#define STM32_ICU_USE_TIM2                  FALSE
#define STM32_ICU_USE_TIM3                  FALSE
#define STM32_ICU_USE_TIM4                  FALSE
#define STM32_ICU_USE_TIM5                  FALSE
#define STM32_ICU_USE_TIM8                  FALSE
#define STM32_ICU_TIM1_IRQ_PRIORITY         7
#define STM32_ICU_TIM2_IRQ_PRIORITY         7
#define STM32_ICU_TIM3_IRQ_PRIORITY         7
#define STM32_ICU_TIM4_IRQ_PRIORITY         7
#define STM32_ICU_TIM5_IRQ_PRIORITY         7
#define STM32_ICU_TIM8_IRQ_PRIORITY         7

/*
 * PWM driver system settings.
 */
#define STM32_PWM_USE_ADVANCED              FALSE
#define STM32_PWM_USE_TIM1                  FALSE
#define STM32_PWM_USE_TIM2                  FALSE
#define STM32_PWM_USE_TIM3                  FALSE
#define STM32_PWM_USE_TIM4                  FALSE
#define STM32_PWM_USE_TIM5                  FALSE
#define STM32_PWM_USE_TIM8                  FALSE
#define STM32_PWM_TIM1_IRQ_PRIORITY         7
#define STM32_PWM_TIM2_IRQ_PRIORITY         7
#define STM32_PWM_TIM3_IRQ_PRIORITY         7
#define STM32_PWM_TIM4_IRQ_PRIORITY         7
#define STM32_PWM_TIM5_IRQ_PRIORITY         7
#define STM32_PWM_TIM8_IRQ_PRIORITY         7

/*
 * SERIAL driver system settings.
 */
#define STM32_SERIAL_USE_USART1             TRUE
#define STM32_SERIAL_USE_USART2             FALSE
#define STM32_SERIAL_USE_USART3             FALSE
#define STM32_SERIAL_USE_UART4              FALSE
#define STM32_SERIAL_USE_UART5              FALSE
#define STM32_SERIAL_USE_USART6             FALSE
#define STM32_SERIAL_USART1_PRIORITY        12
#define STM32_SERIAL_USART2_PRIORITY        12
#define STM32_SERIAL_USART3_PRIORITY        12
#define STM32_SERIAL_UART4_PRIORITY         12
#define STM32_SERIAL_UART5_PRIORITY         12
#define STM32_SERIAL_USART6_PRIORITY        12

/*
 * SPI driver system settings.
 */
#define STM32_SPI_USE_SPI1                  TRUE
#define STM32_SPI_USE_SPI2                  TRUE
#define STM32_SPI_USE_SPI3                  FALSE
#define STM32_SPI_SPI1_DMA_PRIORITY         1
#define STM32_SPI_SPI2_DMA_PRIORITY         1
#define STM32_SPI_SPI3_DMA_PRIORITY         1
#define STM32_SPI_SPI1_IRQ_PRIORITY         10
#define STM32_SPI_SPI2_IRQ_PRIORITY         10
#define STM32_SPI_SPI3_IRQ_PRIORITY         10
#define STM32_SPI_DMA_ERROR_HOOK(spip)      chSysHalt()

/*
 * UART driver system settings.
 */
#define STM32_UART_USE_USART1               FALSE
#define STM32_UART_USE_USART2               TRUE
#define STM32_UART_USE_USART3               FALSE
#define STM32_UART_USART1_IRQ_PRIORITY      12
#define STM32_UART_USART2_IRQ_PRIORITY      12
#define STM32_UART_USART3_IRQ_PRIORITY      12
#define STM32_UART_USART1_DMA_PRIORITY      0
#define STM32_UART_USART2_DMA_PRIORITY      0
#define STM32_UART_USART3_DMA_PRIORITY      0
#define STM32_UART_DMA_ERROR_HOOK(uartp)    chSysHalt()

/*
 * USB driver system settings.
 */
#define STM32_USB_USE_USB1                  TRUE
#define STM32_USB_LOW_POWER_ON_SUSPEND      FALSE
#define STM32_USB_USB1_HP_IRQ_PRIORITY      6
#define STM32_USB_USB1_LP_IRQ_PRIORITY      14
/* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#============================================================================
# Copyright (C) 2006,2007 International Business Machines Corp.
# Author: Stefan Berger <stefanb@us.ibm.com>
#============================================================================

import re
import os, stat
import tempfile
import shutil
import threading

from xen.xend.XendLogging import log
from xen.util import mkdir
import xen.util.xsm.xsm as security

#
# Functions for modifying entries in the bootloader, i.e. adding
# a module to boot the system with a policy.
#

def get_default_title():
    """ See description in Bootloader class below """
    return __bootloader.get_default_title()


def get_boot_policies():
    """ See description in Bootloader class below """
    return __bootloader.get_boot_policies()


def add_boot_policy(index, binpolname):
    """ See description in Bootloader class below """
    return __bootloader.add_boot_policy(index, binpolname)


def rm_policy_from_boottitle(index, unamelist):
    """ See description in Bootloader class below """
    return __bootloader.rm_policy_from_boottitle(index, unamelist)


def set_kernel_attval(index, att, val):
    """ See description in Bootloader class below """
    return __bootloader.set_kernel_attval(index, att, val)


def get_kernel_val(index, att):
    """ See description in Bootloader class below """
    return __bootloader.get_kernel_val(index, att)


def set_boot_policy(title_idx, filename):
    boottitles = get_boot_policies()
    for key in boottitles.iterkeys():
        boottitles[key] += ".bin"
    if boottitles.has_key(title_idx):
        rm_policy_from_boottitle(title_idx, [ boottitles[title_idx] ])
    rc = add_boot_policy(title_idx, filename)
    return rc


def loads_default_policy(filename):
    """ Determine whether the given policy is loaded by the default boot title """
    policy = get_default_policy()
    if policy:
        polfile = policy + ".bin"
        if     polfile == filename or \
           "/"+polfile == filename:
            return True
    return False


def get_default_policy():
    """ Get the name of the policy loaded by the default boot title """
    title = get_default_title()
    policies = get_boot_policies()
    return policies.get(title)


def set_default_boot_policy(filename):
    """ Set the boot policy in the default title to the given name. """
    title = get_default_title()
    return set_boot_policy(title, filename)


def __is_bootdir_mounted():
    """
       Determine whether the boot partition /boot is mounted or not
    """
    rc = False
    file = open("/proc/mounts")
    for line in file:
        tmp = line.split(" ")
        if tmp[1] == "/boot":
            rc = True
            break
    return rc

def get_prefix():
    if __is_bootdir_mounted():
        return "/"
    else:
        return "/boot/"



class Bootloader:
    """ Bootloader class that real bootloader implementations must overwrite """
    def __init__(self):
        pass

    def probe(self):
        """ Test whether this implementation of a bootloader is supported on the
            local system """
        return True

    def get_default_title(self):
        """ Get the index (starting with 0) of the default boot title
            This number is read from the grub configuration file.
            In case of an error '-1' is returned
            @rtype: int
            @return: the index of the default boot title
        """
        return None

    def get_boot_policies(self):
        """ Get a dictionary of policies that the system is booting with.
            @rtype: dict
            @return: dictionary of boot titles where the keys are the
                     indices of the boot titles
        """
        return {}

    def add_boot_policy(self, index, binpolname):
        """ Add the binary policy for automatic loading when
            booting the system. Add it to the boot title at index
            'index'.
        """
        return False

    def rm_policy_from_boottitle(self, index, unamelist):
        """ Remove a policy from the given title. A list of possible policies
            must be given to detect what module to remove
        """
        return False

    def set_kernel_attval(self, index, att, val):
        """
            Append an attribut/value pair to the kernel line.
            @param index : The index of the title to modify
            @param att   : The attribute to add
            @param val   : The value to add. If no value or the special value
                           '<>' is given, then the attribute will be removed.
                           If an empty value is given, then only the attribute
                           is added in the format "att", otherwise "att=val"
                           is added.
        """
        return False

    def get_kernel_val(self, index, att):
        """
            Get an attribute's value from the kernel line.
            @param index : The index of the title to get the attribute/value from
            @param att   : The attribute to read the value of
        """
        return None


class Grub(Bootloader):
    """ Implementation for manipulating bootloader entries in grub according
        to the 'Bootloader' class interface """

    def __init__(self):
        self.__bootfile_lock = threading.RLock()
        self.title_re = re.compile("\s*title\s", re.IGNORECASE)
        self.module_re = re.compile("\s+module\s", re.IGNORECASE)
        self.policy_re = re.compile(".*\.bin", re.IGNORECASE)
        self.kernel_re = re.compile("\s*kernel\s", re.IGNORECASE)
        Bootloader.__init__(self)

    def probe(self):
        try:
            boot_file = self.__get_bootfile()
        except:
            return False
        return True


    def __get_bootfile(self):
        """ Get the name of the bootfile """
        boot_file = "/boot/grub/grub.conf"
        alt_boot_file = "/boot/grub/menu.lst"

        if not os.path.isfile(boot_file):
            #take alternate boot file instead
            boot_file = alt_boot_file

        #follow symlink since menue.lst might be linked to grub.conf
        if not os.path.exists(boot_file):
            raise IOError("Boot file \'%s\' not found." % boot_file)

        if stat.S_ISLNK(os.lstat(boot_file)[stat.ST_MODE]):
            new_name = os.readlink(boot_file)
            if new_name[0] == "/":
                boot_file = new_name
            else:
                path = boot_file.split('/')
                path[len(path)-1] = new_name
                boot_file = '/'.join(path)
        if not os.path.exists(boot_file):
            raise IOError("Boot file \'%s\' not found." % boot_file)
        return boot_file


    def get_default_title(self):
        """ Get the index (starting with 0) of the default boot title
            This number is read from the grub configuration file.
            In case of an error '-1' is returned
            @rtype: int
            @return: the index of the default boot title
        """
        def_re = re.compile("default", re.IGNORECASE)
        default = None
        try:
            boot_file = self.__get_bootfile()
        except:
            return default
        try:
            self.__bootfile_lock.acquire()
            grub_fd = open(boot_file)
            for line in grub_fd:
                line = line.rstrip()
                if def_re.match(line):
                    #remove 'default='
                    line = line.lstrip()[8:]
                    default = int(line)
                    break
        finally:
            self.__bootfile_lock.release()
        return default


    def get_boot_policies(self):
        """ Get a dictionary of policies that the system is booting with.
            @rtype: dict
            @return: dictionary of boot titles where the keys are the
                     indices of the boot titles
        """
        policies = {}
        within_title = 0
        idx = -1
        try:
            boot_file = self.__get_bootfile()
        except:
            return policies
        try:
            self.__bootfile_lock.acquire()

            grub_fd = open(boot_file)
            for line in grub_fd:
                if self.title_re.match(line):
                    within_title = 1
                    idx = idx + 1
                if within_title and self.module_re.match(line):
                    if self.policy_re.match(line):
                        start = line.find("module")
                        pol = line[start+6:]
                        pol = pol.strip()
                        if pol[0] == '/':
                            pol = pol[1:]
                        if pol[0:5] == "boot/":
                            pol = pol[5:]
                        if pol.endswith(".bin"):
                            pol = pol[:-4]
                        policies[idx] = pol
        finally:
            self.__bootfile_lock.release()
        return policies


    def add_boot_policy(self, index, binpolname):
        """ Add the binary policy for automatic loading when
            booting the system. Add it to the boot title at index
            'index'.
        """
        ctr = 0
        module_line = ""
        within_title = 0
        found = False
        try:
            boot_file = self.__get_bootfile()
        except:
            return False
        try:
            self.__bootfile_lock.acquire()
            grub_fd = open(boot_file)
            (tmp_fd, tmp_grub) = tempfile.mkstemp()
            for line in grub_fd:
                if self.title_re.match(line):
                    if module_line != "" and not found:
                        os.write(tmp_fd, module_line)
                        found = True

                    if ctr == index:
                        within_title = 1
                    else:
                        within_title = 0
                    ctr = ctr + 1
                elif within_title and self.module_re.match(line):
                    start = line.find("module")
                    l = line[start+6:len(line)]
                    l = l.lstrip()
                    if l[0] == '/':
                        prefix = "/"
                    else:
                        prefix = ""
                    prefix = get_prefix()
                    module_line = "\tmodule %s%s\n" % (prefix,binpolname)
                else:
                    if module_line != "" and not found:
                        os.write(tmp_fd, module_line)
                        found = True

                os.write(tmp_fd, line)

            if module_line != "" and not found:
                if ord(line[-1]) not in [ 10 ]:
                    os.write(tmp_fd, '\n')
                os.write(tmp_fd, module_line)
                found = True

            shutil.move(boot_file, boot_file+"_save")
            shutil.copyfile(tmp_grub, boot_file)
            os.close(tmp_fd)
            try:
                os.remove(tmp_grub)
            except:
                pass
        finally:
            self.__bootfile_lock.release()
        return found


    def rm_policy_from_boottitle(self, index, unamelist):
        """ Remove a policy from the given title. A list of possible policies
            must be given to detect what module to remove
        """
        found = False
        ctr = 0
        within_title = 0

        prefix = get_prefix()
        namelist = [prefix+name for name in unamelist]

        try:
            boot_file = self.__get_bootfile()
        except:
            return False
        try:
            self.__bootfile_lock.acquire()

            grub_fd = open(boot_file)
            (tmp_fd, tmp_grub) = tempfile.mkstemp()
            for line in grub_fd:
                omit_line = False
                if self.title_re.match(line):
                    if ctr == index:
                        within_title = 1
                    else:
                        within_title = 0
                    ctr = ctr + 1
                if within_title and self.module_re.match(line):
                    if self.policy_re.match(line):
                        start = line.find("module")
                        pol = line[start+6:len(line)]
                        pol = pol.strip()
                        if pol in namelist:
                            omit_line = True
                            found = True
                if not omit_line:
                    os.write(tmp_fd, line)
            if found:
                shutil.move(boot_file, boot_file+"_save")
                shutil.copyfile(tmp_grub, boot_file)
            os.close(tmp_fd)
            try:
                os.remove(tmp_grub)
            except:
                pass
        finally:
            self.__bootfile_lock.release()
        return found


    def set_kernel_attval(self, index, att, val):
        """
            Append an attribut/value pair to the kernel line.
            @param index : The index of the title to modify
            @param att   : The attribute to add
            @param val   : The value to add. If no value or the special value
                           '<>' is given, then the attribute will be removed.
                           If an empty value is given, then only the attribute
                           is added in the format "att", otherwise "att=val"
                           is added.
        """
        found = False
        ctr = 0
        within_title = 0
        try:
            boot_file = self.__get_bootfile()
        except:
            False
        try:
            self.__bootfile_lock.acquire()

            grub_fd = open(boot_file)
            (tmp_fd, tmp_grub) = tempfile.mkstemp()
            for line in grub_fd:
                if self.title_re.match(line):
                    if ctr == index:
                        within_title = 1
                    else:
                        within_title = 0
                    ctr = ctr + 1
                if within_title and self.kernel_re.match(line):
                    nitems = []
                    items = line.split(" ")
                    i = 0
                    while i < len(items):
                        el = items[i].split("=",1)
                        if el[0] != att:
                            nitems.append(items[i].rstrip("\n"))
                        i += 1
                    if val == "":
                        nitems.append("%s" % (att))
                    elif val != None and val != "<>":
                        nitems.append("%s=%s" % (att,val))
                    line = " ".join(nitems) + "\n"
                os.write(tmp_fd, line)
            shutil.move(boot_file, boot_file+"_save")
            shutil.copyfile(tmp_grub, boot_file)
            os.close(tmp_fd)
            try:
                os.remove(tmp_grub)
            except:
                pass
        finally:
            self.__bootfile_lock.release()
        return found


    def get_kernel_val(self, index, att):
        """
            Get an attribute's value from the kernel line.
            @param index : The index of the title to get the attribute/value from
            @param att   : The attribute to read the value of
        """
        ctr = 0
        within_title = 0
        try:
            boot_file = self.__get_bootfile()
        except:
            return None
        try:
            self.__bootfile_lock.acquire()

            grub_fd = open(boot_file)
            for line in grub_fd:
                if self.title_re.match(line):
                    if ctr == index:
                        within_title = 1
                    else:
                        within_title = 0
                    ctr = ctr + 1
                if within_title and self.kernel_re.match(line):
                    line = line.strip()
                    items = line.split(" ")
                    i = 0
                    while i < len(items):
                        el = items[i].split("=",1)
                        if el[0] == att:
                            if len(el) == 1:
                                return "<>"
                            return el[1]
                        i += 1
        finally:
            self.__bootfile_lock.release()
        return None # Not found

class LatePolicyLoader(Bootloader):
    """ A fake bootloader file that holds the policy to load automatically
        once xend has started up and the Domain-0 label to set. """
    def __init__(self):
        self.__bootfile_lock = threading.RLock()
        self.PATH = security.security_dir_prefix
        self.FILENAME = self.PATH + "/xen_boot_policy"
        self.DEFAULT_TITLE = "ANY"
        self.POLICY_ATTR = "POLICY"
        Bootloader.__init__(self)

    def probe(self):
        try:
            _dir=os.path.dirname(self.FILENAME)
            mkdir.parents(_dir, stat.S_IRWXU)
        except:
            return False
        return True

    def get_default_title(self):
        return self.DEFAULT_TITLE

    def get_boot_policies(self):
        policies = {}
        try:
            self.__bootfile_lock.acquire()

            res = self.__loadcontent()

            pol = res.get( self.POLICY_ATTR )
            if pol:
                policies.update({ self.DEFAULT_TITLE : pol })

        finally:
            self.__bootfile_lock.release()

        return policies

    def add_boot_policy(self, index, binpolname):
        try:
            self.__bootfile_lock.acquire()

            res = self.__loadcontent()
            if binpolname.endswith(".bin"):
                binpolname = binpolname[0:-4]
            res[ self.POLICY_ATTR ] = binpolname
            self.__writecontent(res)
        finally:
            self.__bootfile_lock.release()

        return True

    def rm_policy_from_boottitle(self, index, unamelist):
        try:
            self.__bootfile_lock.acquire()

            res = self.__loadcontent()
            if self.POLICY_ATTR in res:
                del(res[self.POLICY_ATTR])
            self.__writecontent(res)
        finally:
            self.__bootfile_lock.release()

        return True

    def set_kernel_attval(self, index, att, val):
        try:
            self.__bootfile_lock.acquire()

            res = self.__loadcontent()
            res[att] = val
            self.__writecontent(res)
        finally:
            self.__bootfile_lock.release()

        return True

    def get_kernel_val(self, index, att):
        try:
            self.__bootfile_lock.acquire()

            res = self.__loadcontent()
            return res.get(att)
        finally:
            self.__bootfile_lock.release()

    def __loadcontent(self):
        res={}
        try:
            file = open(self.FILENAME)
            for line in file:
                tmp = line.split("=",1)
                if len(tmp) == 2:
                   res[tmp[0]] = tmp[1].strip()
            file.close()
        except:
            pass

        return res

    def __writecontent(self, items):
        rc = True
        try:
            file = open(self.FILENAME,"w")
            if file:
                for key, value in items.items():
                    file.write("%s=%s\n" % (str(key),str(value)))
                file.close()
        except:
            rc = False

        return rc


__bootloader = Bootloader()

def init():
    global __bootloader
    grub = Grub()
    if grub.probe() == True:
        __bootloader = grub
    else:
        late = LatePolicyLoader()
        if late.probe() == True:
            __bootloader = late