aboutsummaryrefslogtreecommitdiffstats
path: root/testhal/STM32/STM32F0xx/PWM-ICU/main.c
diff options
context:
space:
mode:
authorGiovanni Di Sirio <gdisirio@gmail.com>2017-01-11 10:38:11 +0000
committerGiovanni Di Sirio <gdisirio@gmail.com>2017-01-11 10:38:11 +0000
commit72b36371b276d77da9d9654ff6338acc2c25015e (patch)
treeaf0a74d6fa1117beb9213ae7b93b14eb51c04c82 /testhal/STM32/STM32F0xx/PWM-ICU/main.c
parentb4e1ecc760fb1dea0089428a4ba4cdd9510e1cdb (diff)
downloadChibiOS-72b36371b276d77da9d9654ff6338acc2c25015e.tar.gz
ChibiOS-72b36371b276d77da9d9654ff6338acc2c25015e.tar.bz2
ChibiOS-72b36371b276d77da9d9654ff6338acc2c25015e.zip
ADCv1 enhancement.
git-svn-id: svn://svn.code.sf.net/p/chibios/svn/trunk@10031 35acf78f-673a-0410-8e92-d51de3d6d3f4
Diffstat (limited to 'testhal/STM32/STM32F0xx/PWM-ICU/main.c')
0 files changed, 0 insertions, 0 deletions
a id='n123' href='#n123'>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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
#============================================================================
# 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 Xensource Inc.
#============================================================================

import commands
import logging
import os
import re
from xen.xend import uuid as genuuid
from xen.xend import XendAPIStore
from xen.xend.XendBase import XendBase
from xen.xend.XendPIFMetrics import XendPIFMetrics
from xen.xend.XendError import *
from xen.xend import Vifctl
from xen.util import auxbin

log = logging.getLogger("xend.XendPIF")
log.setLevel(logging.TRACE)

MAC_RE = re.compile(':'.join(['[0-9a-f]{2}'] * 6))
IP_IFACE_RE = re.compile(r'^\d+: (\w+):.*mtu (\d+) .* link/\w+ ([0-9a-f:]+)')


Vifctl.network('start')

def linux_phy_to_virt(pif_name):
    return 'eth' + re.sub(r'^[a-z]+', '', pif_name)

def linux_get_phy_ifaces():
    """Returns a list of physical interfaces.

    Identifies PIFs as those that have a interface name starting with
    'peth'.

    See /etc/xen/scripts/network-bridge for how the devices are renamed.

    @rtype: array of 3-element tuple (name, mtu, mac)
    """
    
    ip_cmd = 'ip -o link show'
    rc, output = commands.getstatusoutput(ip_cmd)
    ifaces = {}
    phy_ifaces = []
    if rc == 0:
        # parse all interfaces into (name, mtu, mac)
        for line in output.split('\n'):
            has_if = re.search(IP_IFACE_RE, line)
            if has_if:
                ifaces[has_if.group(1)] = has_if.groups()
                
        # resolve pifs' mac addresses
        for name, mtu, mac in ifaces.values():
            if name.startswith('peth'):
                bridged_ifname = linux_phy_to_virt(name)
                bridged_if = ifaces.get(bridged_ifname)
                bridged_mac = ''
                if bridged_if:
                    bridged_mac = bridged_if[2]
                phy_ifaces.append((name, int(mtu), bridged_mac))
                
    return phy_ifaces

def linux_set_mac(iface, mac):
    if not re.search(MAC_RE, mac):
        return False

    ip_mac_cmd = 'ip link set %s addr %s' % \
                 (linux_phy_to_virt(iface), mac)
    rc, output = commands.getstatusoutput(ip_mac_cmd)
    if rc == 0:
        return True

    return False

def linux_set_mtu(iface, mtu):
    try:
        ip_mtu_cmd = 'ip link set %s mtu %d' % \
                     (linux_phy_to_virt(iface), int(mtu))
        rc, output = commands.getstatusoutput(ip_mtu_cmd)
        if rc == 0:
            return True
        return False
    except ValueError:
        return False

def linux_get_mtu(device):
    return _linux_get_pif_param(device, 'mtu')

def linux_get_mac(device):
    return _linux_get_pif_param(device, 'link/ether')

def _linux_get_pif_param(device, param_name):
    ip_get_dev_data = 'ip link show %s' % device
    rc, output = commands.getstatusoutput(ip_get_dev_data)
    if rc == 0:
        params = output.split(' ')
        for i in xrange(len(params)):
            if params[i] == param_name:
                return params[i+1]
    return ''

def _create_VLAN(dev, vlan):
    rc, _ = commands.getstatusoutput('vconfig add %s %d' %
                                     (dev, vlan))
    if rc != 0:
        return False

    rc, _ = commands.getstatusoutput('ifconfig %s.%d up' %
                                     (dev, vlan))
    return rc == 0

def _destroy_VLAN(dev, vlan):
    rc, _ = commands.getstatusoutput('ifconfig %s.%d down' %
                                     (dev, vlan))
    if rc != 0:
        return False
                                     
    rc, _ = commands.getstatusoutput('vconfig rem %s.%d' %
                                     (dev, vlan))
    return rc == 0

class XendPIF(XendBase):
    """Representation of a Physical Network Interface."""

    def getClass(self):
        return "PIF"

    def getAttrRO(self):
        attrRO = ['network',
                  'host',
                  'metrics',
                  'device',
                  'VLAN']
        return XendBase.getAttrRO() + attrRO
    
    def getAttrRW(self):
        attrRW = ['MAC',
                  'MTU']
        return XendBase.getAttrRW() + attrRW

    def getAttrInst(self):
        attrInst = ['network',
                    'device',
                    'MAC',
                    'MTU',
                    'VLAN']
        return attrInst

    def getMethods(self):
        methods = ['plug',
                   'unplug',
                   'destroy']
        return XendBase.getMethods() + methods

    def getFuncs(self):
        funcs = ['create_VLAN']
        return XendBase.getFuncs() + funcs

    getClass    = classmethod(getClass)
    getAttrRO   = classmethod(getAttrRO)
    getAttrRW   = classmethod(getAttrRW)
    getAttrInst = classmethod(getAttrInst)
    getMethods  = classmethod(getMethods)
    getFuncs    = classmethod(getFuncs)
    
    def create_phy(self, network_uuid, device,
                   MAC, MTU):
        """
        Called when a new physical PIF is found
        Could be a VLAN...
        """
        # Create new uuids
        pif_uuid = genuuid.createString()
        metrics_uuid = genuuid.createString()

        # Create instances
        metrics = XendPIFMetrics(metrics_uuid, pif_uuid)

        # Is this a VLAN?
        VLANdot = device.split(".")
        VLANcolon = device.split(":")

        if len(VLANdot) > 1:
            VLAN = VLANdot[1]
            device = VLANdot[0]
        elif len(VLANcolon) > 1:
            VLAN = VLANcolon[1]
            device = VLANcolon[0] 
        else:
            VLAN = -1
            
        record = {
            'network': network_uuid,
            'device':  device,
            'MAC':     MAC,
            'MTU':     MTU,
            'VLAN':    VLAN
            }
        pif = XendPIF(record, pif_uuid, metrics_uuid)

        return pif_uuid

    def recreate(self, record, uuid):
        """Called on xend start / restart"""        
        pif_uuid = uuid
        metrics_uuid = record['metrics']

        # Create instances
        metrics = XendPIFMetrics(metrics_uuid, pif_uuid)
        pif = XendPIF(record, pif_uuid, metrics_uuid)

        # If physical PIF, check exists
        # If VLAN, create if not exist
        ifs = [dev for dev, _1, _2 in linux_get_phy_ifaces()]
        if pif.get_VLAN() == -1:
            if pif.get_device() not in ifs:
                XendBase.destroy(pif)
                metrics.destroy()
                return None
        else:
            if pif.get_interface_name() not in ifs:
                _create_VLAN(pif.get_device(), pif.get_VLAN())
                pif.plug()

        return pif_uuid

    def create_VLAN(self, device, network_uuid, host_ref, vlan):
        """Exposed via API - create a new VLAN from existing VIF"""
        
        ifs = [name for name, _, _ in linux_get_phy_ifaces()]

        vlan = int(vlan)

        # Check VLAN tag is valid
        if vlan < 0 or vlan >= 4096:
            raise VLANTagInvalid(vlan)
        
        # Check device exists
        if device not in ifs:
            raise InvalidDeviceError(device)

        # Check VLAN doesn't already exist
        if "%s.%d" % (device, vlan) in ifs:
            raise DeviceExistsError("%s.%d" % (device, vlan))

        # Check network ref is valid
        from XendNetwork import XendNetwork
        if network_uuid not in XendNetwork.get_all():
            raise InvalidHandleError("Network", network_uuid)

        # Check host_ref is this host
        import XendNode
        if host_ref != XendNode.instance().get_uuid():
            raise InvalidHandleError("Host", host_ref)

        # Create the VLAN
        _create_VLAN(device, vlan)

        # Create new uuids
        pif_uuid = genuuid.createString()
        metrics_uuid = genuuid.createString()

        # Create the record
        record = {
            "device":  device,
            "MAC":     linux_get_mac('%s.%d' % (device, vlan)),
            "MTU":     linux_get_mtu('%s.%d' % (device, vlan)),
            "network": network_uuid,
            "VLAN":    vlan
            }

        # Create instances
        metrics = XendPIFMetrics(metrics_uuid, pif_uuid)
        pif = XendPIF(record, pif_uuid, metrics_uuid)

        # Not sure if they should be created plugged or not...
        pif.plug()

        XendNode.instance().save_PIFs()
        return pif_uuid

    create_phy  = classmethod(create_phy)
    recreate    = classmethod(recreate)
    create_VLAN = classmethod(create_VLAN)
    
    def __init__(self, record, uuid, metrics_uuid):
        XendBase.__init__(self, uuid, record)
        self.metrics = metrics_uuid

    def plug(self):
        """Plug the PIF into the network"""
        network = XendAPIStore.get(self.network,
                                   "network")
        bridge_name = network.get_name_label()

        from xen.util import Brctl
        Brctl.vif_bridge_add({
            "bridge": bridge_name,
            "vif":    self.get_interface_name()
            })

    def unplug(self):
        """Unplug the PIF from the network"""
        network = XendAPIStore.get(self.network,
                                   "network")
        bridge_name = network.get_name_label()

        from xen.util import Brctl
        Brctl.vif_bridge_rem({
            "bridge": bridge_name,
            "vif":    self.get_interface_name()
            })

    def destroy(self):
        # Figure out if this is a physical device
        if self.get_interface_name() == \
           self.get_device():
            raise PIFIsPhysical()

        self.unplug()

        if _destroy_VLAN(self.get_device(), self.get_VLAN()):
            XendBase.destroy(self)
            import XendNode
            XendNode.instance().save_PIFs()
        else:
            raise NetworkError("Unable to delete VLAN", self.get_uuid())

    def get_interface_name(self):
        if self.get_VLAN() == -1:
            return self.get_device()
        else:
            return "%s.%d" % (self.get_device(), self.get_VLAN())
        
    def get_device(self):