macvtap.c 33.9 KB
Newer Older
1
/*
2
 * Copyright (C) 2010-2011 Red Hat, Inc.
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
 * Copyright (C) 2010 IBM Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * Authors:
 *     Stefan Berger <stefanb@us.ibm.com>
 *
 * Notes:
 * netlink: http://lovezutto.googlepages.com/netlink.pdf
 *          iproute2 package
 *
 */

#include <config.h>

30 31
#include <stdint.h>

32
#if WITH_MACVTAP || WITH_VIRTUALPORT
33

34 35 36
# include <stdio.h>
# include <errno.h>
# include <fcntl.h>
37
# include <c-ctype.h>
38 39
# include <sys/socket.h>
# include <sys/ioctl.h>
40

41 42
# include <linux/if.h>
# include <linux/if_tun.h>
43

44 45 46 47 48
/* Older kernels lacked this enum value.  */
# if !HAVE_DECL_MACVLAN_MODE_PASSTHRU
#  define MACVLAN_MODE_PASSTHRU 8
# endif

49 50 51 52
#endif /* WITH_MACVTAP || WITH_VIRTUALPORT */

#include "util.h"
#include "macvtap.h"
53
#include "network.h"
54

55 56 57 58 59 60
VIR_ENUM_IMPL(virMacvtapMode, VIR_MACVTAP_MODE_LAST,
              "vepa",
              "private",
              "bridge",
              "passthrough")

61 62
#if WITH_MACVTAP || WITH_VIRTUALPORT

63
# include "memory.h"
64
# include "logging.h"
65
# include "interface.h"
66
# include "virterror_internal.h"
67
# include "uuid.h"
E
Eric Blake 已提交
68
# include "virfile.h"
69
# include "netlink.h"
70

71
# define VIR_FROM_THIS VIR_FROM_NET
72

73
# define macvtapError(code, ...)                                           \
74
        virReportErrorHelper(VIR_FROM_NET, code, __FILE__,                 \
75
                             __FUNCTION__, __LINE__, __VA_ARGS__)
76

77 78
# define MACVTAP_NAME_PREFIX	"macvtap"
# define MACVTAP_NAME_PATTERN	"macvtap%d"
79

80 81 82 83 84 85 86
# define MICROSEC_PER_SEC       (1000 * 1000)

# define NLMSGBUF_SIZE  256
# define RATTBUF_SIZE   64

# define STATUS_POLL_TIMEOUT_USEC (10 * MICROSEC_PER_SEC)
# define STATUS_POLL_INTERVL_USEC (MICROSEC_PER_SEC / 8)
87 88


89 90 91 92 93 94
# define LLDPAD_PID_FILE  "/var/run/lldpad.pid"


enum virVirtualPortOp {
    ASSOCIATE = 0x1,
    DISASSOCIATE = 0x2,
95
    PREASSOCIATE = 0x3,
96
    PREASSOCIATE_RR = 0x4,
97
};
98 99


100 101


102 103
# if WITH_MACVTAP

104
/* Open the macvtap's tap device.
105
 * @ifname: Name of the macvtap interface
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
 * @retries : Number of retries in case udev for example may need to be
 *            waited for to create the tap chardev
 * Returns negative value in case of error, the file descriptor otherwise.
 */
static
int openTap(const char *ifname,
            int retries)
{
    FILE *file;
    char path[64];
    int ifindex;
    char tapname[50];
    int tapfd;

    if (snprintf(path, sizeof(path),
                 "/sys/class/net/%s/ifindex", ifname) >= sizeof(path)) {
        virReportSystemError(errno,
                             "%s",
                             _("buffer for ifindex path is too small"));
        return -1;
    }

    file = fopen(path, "r");

    if (!file) {
        virReportSystemError(errno,
                             _("cannot open macvtap file %s to determine "
                               "interface index"), path);
        return -1;
    }

    if (fscanf(file, "%d", &ifindex) != 1) {
        virReportSystemError(errno,
                             "%s",_("cannot determine macvtap's tap device "
                             "interface index"));
141
        VIR_FORCE_FCLOSE(file);
142 143 144
        return -1;
    }

145
    VIR_FORCE_FCLOSE(file);
146 147 148 149 150 151 152 153 154 155

    if (snprintf(tapname, sizeof(tapname),
                 "/dev/tap%d", ifindex) >= sizeof(tapname)) {
        virReportSystemError(errno,
                             "%s",
                             _("internal buffer for tap device is too small"));
        return -1;
    }

    while (1) {
156
        /* may need to wait for udev to be done */
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        tapfd = open(tapname, O_RDWR);
        if (tapfd < 0 && retries > 0) {
            retries--;
            usleep(20000);
            continue;
        }
        break;
    }

    if (tapfd < 0)
        virReportSystemError(errno,
                             _("cannot open macvtap tap device %s"),
                             tapname);

    return tapfd;
}


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
/**
 * configMacvtapTap:
 * @tapfd: file descriptor of the macvtap tap
 * @vnet_hdr: 1 to enable IFF_VNET_HDR, 0 to disable it
 *
 * Returns 0 on success, -1 in case of fatal error, error code otherwise.
 *
 * Turn the IFF_VNET_HDR flag, if requested and available, make sure
 * it's off in the other cases.
 * A fatal error is defined as the VNET_HDR flag being set but it cannot
 * be turned off for some reason. This is reported with -1. Other fatal
 * error is not being able to read the interface flags. In that case the
 * macvtap device should not be used.
 */
static int
configMacvtapTap(int tapfd, int vnet_hdr)
{
    unsigned int features;
    struct ifreq ifreq;
    short new_flags = 0;
    int rc_on_fail = 0;
    const char *errmsg = NULL;

    memset(&ifreq, 0, sizeof(ifreq));

    if (ioctl(tapfd, TUNGETIFF, &ifreq) < 0) {
        virReportSystemError(errno, "%s",
                             _("cannot get interface flags on macvtap tap"));
        return -1;
    }

    new_flags = ifreq.ifr_flags;

    if ((ifreq.ifr_flags & IFF_VNET_HDR) && !vnet_hdr) {
        new_flags = ifreq.ifr_flags & ~IFF_VNET_HDR;
        rc_on_fail = -1;
        errmsg = _("cannot clean IFF_VNET_HDR flag on macvtap tap");
    } else if ((ifreq.ifr_flags & IFF_VNET_HDR) == 0 && vnet_hdr) {
        if (ioctl(tapfd, TUNGETFEATURES, &features) != 0)
            return errno;
        if ((features & IFF_VNET_HDR)) {
            new_flags = ifreq.ifr_flags | IFF_VNET_HDR;
            errmsg = _("cannot set IFF_VNET_HDR flag on macvtap tap");
        }
    }

    if (new_flags != ifreq.ifr_flags) {
        ifreq.ifr_flags = new_flags;
        if (ioctl(tapfd, TUNSETIFF, &ifreq) < 0) {
            virReportSystemError(errno, "%s", errmsg);
            return rc_on_fail;
        }
    }

    return 0;
}


233 234 235 236 237 238 239
static const uint32_t modeMap[VIR_MACVTAP_MODE_LAST] = {
    [VIR_MACVTAP_MODE_VEPA] = MACVLAN_MODE_VEPA,
    [VIR_MACVTAP_MODE_PRIVATE] = MACVLAN_MODE_PRIVATE,
    [VIR_MACVTAP_MODE_BRIDGE] = MACVLAN_MODE_BRIDGE,
    [VIR_MACVTAP_MODE_PASSTHRU] = MACVLAN_MODE_PASSTHRU,
};

S
Stefan Berger 已提交
240 241
/**
 * openMacvtapTap:
242 243 244 245 246 247
 * Create an instance of a macvtap device and open its tap character
 * device.
 * @tgifname: Interface name that the macvtap is supposed to have. May
 *    be NULL if this function is supposed to choose a name
 * @macaddress: The MAC address for the macvtap device
 * @linkdev: The interface name of the NIC to connect to the external bridge
248
 * @mode: int describing the mode for 'bridge', 'vepa', 'private' or 'passthru'.
249 250 251
 * @vnet_hdr: 1 to enable IFF_VNET_HDR, 0 to disable it
 * @vmuuid: The UUID of the VM the macvtap belongs to
 * @virtPortProfile: pointer to object holding the virtual port profile data
252 253 254 255 256
 * @res_ifname: Pointer to a string pointer where the actual name of the
 *     interface will be stored into if everything succeeded. It is up
 *     to the caller to free the string.
 *
 * Returns file descriptor of the tap device in case of success,
257
 * negative value otherwise with error reported.
258 259 260
 *
 */
int
261
openMacvtapTap(const char *tgifname,
262 263
               const unsigned char *macaddress,
               const char *linkdev,
264
               enum virMacvtapMode mode,
265 266 267
               int vnet_hdr,
               const unsigned char *vmuuid,
               virVirtualPortProfileParamsPtr virtPortProfile,
268
               char **res_ifname,
269
               enum virVMOperationType vmOp,
270 271
               char *stateDir,
               virBandwidthPtr bandwidth)
272 273 274 275 276
{
    const char *type = "macvtap";
    int c, rc;
    char ifname[IFNAMSIZ];
    int retries, do_retry = 0;
277
    uint32_t macvtapMode;
278 279 280
    const char *cr_ifname;
    int ifindex;

281 282
    macvtapMode = modeMap[mode];

283 284
    *res_ifname = NULL;

285 286
    VIR_DEBUG("%s: VM OPERATION: %s", __FUNCTION__, virVMOperationTypeToString(vmOp));

287 288 289 290 291 292 293
    /** Note: When using PASSTHROUGH mode with MACVTAP devices the link
     * device's MAC address must be set to the VMs MAC address. In
     * order to not confuse the first switch or bridge in line this MAC
     * address must be reset when the VM is shut down.
     * This is especially important when using SRIOV capable cards that
     * emulate their switch in firmware.
     */
294
    if (mode == VIR_MACVTAP_MODE_PASSTHRU) {
295
        if (ifaceReplaceMacAddress(macaddress, linkdev, stateDir) != 0) {
296 297 298 299
            return -1;
        }
    }

300
    if (tgifname) {
301
        if(ifaceGetIndex(false, tgifname, &ifindex) == 0) {
302 303 304 305 306 307 308 309 310
            if (STRPREFIX(tgifname,
                          MACVTAP_NAME_PREFIX)) {
                goto create_name;
            }
            virReportSystemError(errno,
                                 _("Interface %s already exists"), tgifname);
            return -1;
        }
        cr_ifname = tgifname;
311 312
        rc = ifaceMacvtapLinkAdd(type, macaddress, 6, tgifname, linkdev,
                                 macvtapMode, &do_retry);
313
        if (rc < 0)
314 315 316 317 318 319
            return -1;
    } else {
create_name:
        retries = 5;
        for (c = 0; c < 8192; c++) {
            snprintf(ifname, sizeof(ifname), MACVTAP_NAME_PATTERN, c);
320
            if (ifaceGetIndex(false, ifname, &ifindex) == -ENODEV) {
321 322
                rc = ifaceMacvtapLinkAdd(type, macaddress, 6, ifname, linkdev,
                                         macvtapMode, &do_retry);
323 324 325 326 327 328 329 330 331 332 333
                if (rc == 0)
                    break;

                if (do_retry && --retries)
                    continue;
                return -1;
            }
        }
        cr_ifname = ifname;
    }

334 335 336 337
    if (vpAssociatePortProfileId(cr_ifname,
                                 macaddress,
                                 linkdev,
                                 virtPortProfile,
338
                                 vmuuid, vmOp) != 0) {
339 340 341 342
        rc = -1;
        goto link_del_exit;
    }

343
    rc = ifaceUp(cr_ifname);
344
    if (rc < 0) {
345
        virReportSystemError(errno,
S
Stefan Berger 已提交
346 347 348 349
                             _("cannot 'up' interface %s -- another "
                             "macvtap device may be 'up' and have the same "
                             "MAC address"),
                             cr_ifname);
350
        rc = -1;
351
        goto disassociate_exit;
352 353 354 355
    }

    rc = openTap(cr_ifname, 10);

356 357
    if (rc >= 0) {
        if (configMacvtapTap(rc, vnet_hdr) < 0) {
358
            VIR_FORCE_CLOSE(rc); /* sets rc to -1 */
359
            goto disassociate_exit;
360
        }
361
        *res_ifname = strdup(cr_ifname);
362
    } else
363
        goto disassociate_exit;
364

365 366 367 368 369 370 371 372 373
    if (virBandwidthEnable(bandwidth, cr_ifname) < 0) {
        macvtapError(VIR_ERR_INTERNAL_ERROR,
                     _("cannot set bandwidth limits on %s"),
                     cr_ifname);
        rc = -1;
        goto disassociate_exit;
    }


374 375
    return rc;

376
disassociate_exit:
377 378 379
    vpDisassociatePortProfileId(cr_ifname,
                                macaddress,
                                linkdev,
380 381
                                virtPortProfile,
                                vmOp);
382

383
link_del_exit:
384
    ifaceLinkDel(cr_ifname);
385 386 387 388 389

    return rc;
}


S
Stefan Berger 已提交
390
/**
E
Eric Blake 已提交
391
 * delMacvtap:
S
Stefan Berger 已提交
392
 * @ifname : The name of the macvtap interface
393
 * @linkdev: The interface name of the NIC to connect to the external bridge
394
 * @virtPortProfile: pointer to object holding the virtual port profile data
395
 *
396 397 398
 * Delete an interface given its name. Disassociate
 * it with the switch if port profile parameters
 * were provided.
399
 */
S
Stefan Berger 已提交
400
void
401
delMacvtap(const char *ifname,
402 403
           const unsigned char *macaddr,
           const char *linkdev,
404 405 406
           int mode,
           virVirtualPortProfileParamsPtr virtPortProfile,
           char *stateDir)
407
{
408
    if (mode == VIR_MACVTAP_MODE_PASSTHRU) {
409
        ifaceRestoreMacAddress(linkdev, stateDir);
410 411
    }

412
    if (ifname) {
413 414
        vpDisassociatePortProfileId(ifname, macaddr,
                                    linkdev,
415 416
                                    virtPortProfile,
                                    VIR_VM_OP_DESTROY);
417
        ifaceLinkDel(ifname);
418
    }
419 420
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
# endif /* WITH_MACVTAP */

# ifdef IFLA_PORT_MAX

static struct nla_policy ifla_port_policy[IFLA_PORT_MAX + 1] =
{
  [IFLA_PORT_RESPONSE]      = { .type = NLA_U16 },
};


static uint32_t
getLldpadPid(void) {
    int fd;
    uint32_t pid = 0;

    fd = open(LLDPAD_PID_FILE, O_RDONLY);
    if (fd >= 0) {
        char buffer[10];

        if (saferead(fd, buffer, sizeof(buffer)) <= sizeof(buffer)) {
            unsigned int res;
            char *endptr;

            if (virStrToLong_ui(buffer, &endptr, 10, &res) == 0
                && (*endptr == '\0' || c_isspace(*endptr))
                && res != 0) {
                pid = res;
            } else {
                macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("error parsing pid of lldpad"));
            }
        }
    } else {
        virReportSystemError(errno,
                             _("Error opening file %s"), LLDPAD_PID_FILE);
    }

458
    VIR_FORCE_CLOSE(fd);
459 460 461 462 463

    return pid;
}


464
/**
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
 * getPortProfileStatus
 *
 * tb: top level netlink response attributes + values
 * vf: The virtual function used in the request
 * instanceId: instanceId of the interface (vm uuid in case of 802.1Qbh)
 * is8021Qbg: whether this function is call for 8021Qbg
 * status: pointer to a uint16 where the status will be written into
 *
 * Get the status from the IFLA_PORT_RESPONSE field; Returns 0 in
 * case of success, != 0 otherwise with error having been reported
 */
static int
getPortProfileStatus(struct nlattr **tb, int32_t vf,
                     const unsigned char *instanceId,
                     bool nltarget_kernel,
                     bool is8021Qbg,
                     uint16_t *status)
{
    int rc = 1;
    const char *msg = NULL;
    struct nlattr *tb_port[IFLA_PORT_MAX + 1] = { NULL, };

    if (vf == PORT_SELF_VF && nltarget_kernel) {
        if (tb[IFLA_PORT_SELF]) {
            if (nla_parse_nested(tb_port, IFLA_PORT_MAX, tb[IFLA_PORT_SELF],
                                 ifla_port_policy)) {
                msg = _("error parsing IFLA_PORT_SELF part");
                goto err_exit;
            }
        } else {
            msg = _("IFLA_PORT_SELF is missing");
            goto err_exit;
        }
    } else {
        if (tb[IFLA_VF_PORTS]) {
            int rem;
            bool found = false;
            struct nlattr *tb_vf_ports = { NULL, };

            nla_for_each_nested(tb_vf_ports, tb[IFLA_VF_PORTS], rem) {

                if (nla_type(tb_vf_ports) != IFLA_VF_PORT) {
                    msg = _("error while iterating over IFLA_VF_PORTS part");
                    goto err_exit;
                }

                if (nla_parse_nested(tb_port, IFLA_PORT_MAX, tb_vf_ports,
                                     ifla_port_policy)) {
                    msg = _("error parsing IFLA_VF_PORT part");
                    goto err_exit;
                }

                if (instanceId &&
                    tb_port[IFLA_PORT_INSTANCE_UUID] &&
                    !memcmp(instanceId,
                            (unsigned char *)
                                   RTA_DATA(tb_port[IFLA_PORT_INSTANCE_UUID]),
                            VIR_UUID_BUFLEN) &&
                    tb_port[IFLA_PORT_VF] &&
                    vf == *(uint32_t *)RTA_DATA(tb_port[IFLA_PORT_VF])) {
                        found = true;
                        break;
                }
            }

            if (!found) {
                msg = _("Could not find netlink response with "
                        "expected parameters");
                goto err_exit;
            }
        } else {
            msg = _("IFLA_VF_PORTS is missing");
            goto err_exit;
        }
    }

    if (tb_port[IFLA_PORT_RESPONSE]) {
        *status = *(uint16_t *)RTA_DATA(tb_port[IFLA_PORT_RESPONSE]);
543
        rc = 0;
544
    } else {
545 546 547 548 549 550 551 552
        if (is8021Qbg) {
            /* no in-progress here; may be missing */
            *status = PORT_PROFILE_RESPONSE_INPROGRESS;
            rc = 0;
        } else {
            msg = _("no IFLA_PORT_RESPONSE found in netlink message");
            goto err_exit;
        }
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    }

err_exit:
    if (msg)
        macvtapError(VIR_ERR_INTERNAL_ERROR, "%s", msg);

    return rc;
}


static int
doPortProfileOpSetLink(bool nltarget_kernel,
                       const char *ifname, int ifindex,
                       const unsigned char *macaddr,
                       int vlanid,
                       const char *profileId,
                       struct ifla_port_vsi *portVsi,
                       const unsigned char *instanceId,
                       const unsigned char *hostUUID,
                       int32_t vf,
                       uint8_t op)
{
    int rc = 0;
576
    struct nlmsghdr *resp;
577 578 579 580 581
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = {
        .ifi_family = AF_UNSPEC,
        .ifi_index  = ifindex,
    };
582
    unsigned char *recvbuf = NULL;
583 584
    unsigned int recvbuflen = 0;
    uint32_t pid = 0;
585 586
    struct nl_msg *nl_msg;
    struct nlattr *vfports = NULL, *vfport;
587

588 589 590 591 592
    nl_msg = nlmsg_alloc_simple(RTM_SETLINK, NLM_F_REQUEST);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }
593

594
    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
595 596
        goto buffer_too_small;

597 598 599
    if (ifname &&
        nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
        goto buffer_too_small;
600

601
    if (macaddr || vlanid >= 0) {
602
        struct nlattr *vfinfolist, *vfinfo;
603

604
        if (!(vfinfolist = nla_nest_start(nl_msg, IFLA_VFINFO_LIST)))
605 606
            goto buffer_too_small;

607
        if (!(vfinfo = nla_nest_start(nl_msg, IFLA_VF_INFO)))
608 609
            goto buffer_too_small;

610 611 612 613 614
        if (macaddr) {
            struct ifla_vf_mac ifla_vf_mac = {
                .vf = vf,
                .mac = { 0, },
            };
615

616 617
            memcpy(ifla_vf_mac.mac, macaddr, 6);

618 619
            if (nla_put(nl_msg, IFLA_VF_MAC, sizeof(ifla_vf_mac),
                        &ifla_vf_mac) < 0)
620 621 622 623 624 625 626 627 628 629
                goto buffer_too_small;
        }

        if (vlanid >= 0) {
            struct ifla_vf_vlan ifla_vf_vlan = {
                .vf = vf,
                .vlan = vlanid,
                .qos = 0,
            };

630 631
            if (nla_put(nl_msg, IFLA_VF_VLAN, sizeof(ifla_vf_vlan),
                        &ifla_vf_vlan) < 0)
632 633
                goto buffer_too_small;
        }
634

635 636
        nla_nest_end(nl_msg, vfinfo);
        nla_nest_end(nl_msg, vfinfolist);
637 638 639
    }

    if (vf == PORT_SELF_VF && nltarget_kernel) {
640 641
        if (!(vfport = nla_nest_start(nl_msg, IFLA_PORT_SELF)))
            goto buffer_too_small;
642
    } else {
643
        if (!(vfports = nla_nest_start(nl_msg, IFLA_VF_PORTS)))
644 645 646
            goto buffer_too_small;

        /* begin nesting vfports */
647 648
        if (!(vfport = nla_nest_start(nl_msg, IFLA_VF_PORT)))
            goto buffer_too_small;
649 650 651
    }

    if (profileId) {
652 653
        if (nla_put(nl_msg, IFLA_PORT_PROFILE, strlen(profileId) + 1,
                    profileId) < 0)
654 655 656 657
            goto buffer_too_small;
    }

    if (portVsi) {
658 659
        if (nla_put(nl_msg, IFLA_PORT_VSI_TYPE, sizeof(*portVsi),
                    portVsi) < 0)
660 661 662 663
            goto buffer_too_small;
    }

    if (instanceId) {
664 665
        if (nla_put(nl_msg, IFLA_PORT_INSTANCE_UUID, VIR_UUID_BUFLEN,
                    instanceId) < 0)
666 667 668 669
            goto buffer_too_small;
    }

    if (hostUUID) {
670 671
        if (nla_put(nl_msg, IFLA_PORT_HOST_UUID, VIR_UUID_BUFLEN,
                    hostUUID) < 0)
672 673 674 675
            goto buffer_too_small;
    }

    if (vf != PORT_SELF_VF) {
676
        if (nla_put(nl_msg, IFLA_PORT_VF, sizeof(vf), &vf) < 0)
677 678 679
            goto buffer_too_small;
    }

680
    if (nla_put(nl_msg, IFLA_PORT_REQUEST, sizeof(op), &op) < 0)
681 682 683
        goto buffer_too_small;

    /* end nesting of vport */
684
    nla_nest_end(nl_msg, vfport);
685 686 687

    if (vfports) {
        /* end nesting of vfports */
688
        nla_nest_end(nl_msg, vfports);
689 690 691 692
    }

    if (!nltarget_kernel) {
        pid = getLldpadPid();
693 694 695 696
        if (pid == 0) {
            rc = -1;
            goto err_exit;
        }
697 698
    }

699
    if (nlComm(nl_msg, &recvbuf, &recvbuflen, pid) < 0) {
700 701 702
        rc = -1;
        goto err_exit;
    }
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

    if (recvbuflen < NLMSG_LENGTH(0) || recvbuf == NULL)
        goto malformed_resp;

    resp = (struct nlmsghdr *)recvbuf;

    switch (resp->nlmsg_type) {
    case NLMSG_ERROR:
        err = (struct nlmsgerr *)NLMSG_DATA(resp);
        if (resp->nlmsg_len < NLMSG_LENGTH(sizeof(*err)))
            goto malformed_resp;

        if (err->error) {
            virReportSystemError(-err->error,
                _("error during virtual port configuration of ifindex %d"),
                ifindex);
            rc = -1;
        }
        break;

    case NLMSG_DONE:
        break;

    default:
        goto malformed_resp;
    }

730 731 732
err_exit:
    nlmsg_free(nl_msg);

733 734 735 736 737
    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
738 739
    nlmsg_free(nl_msg);

740 741 742 743 744 745
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("malformed netlink response message"));
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
746 747
    nlmsg_free(nl_msg);

748
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
749
                 _("allocated netlink buffer is too small"));
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    return -1;
}


static int
doPortProfileOpCommon(bool nltarget_kernel,
                      const char *ifname, int ifindex,
                      const unsigned char *macaddr,
                      int vlanid,
                      const char *profileId,
                      struct ifla_port_vsi *portVsi,
                      const unsigned char *instanceId,
                      const unsigned char *hostUUID,
                      int32_t vf,
                      uint8_t op)
{
    int rc;
767
    unsigned char *recvbuf = NULL;
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    struct nlattr *tb[IFLA_MAX + 1] = { NULL , };
    int repeats = STATUS_POLL_TIMEOUT_USEC / STATUS_POLL_INTERVL_USEC;
    uint16_t status = 0;
    bool is8021Qbg = (profileId == NULL);

    rc = doPortProfileOpSetLink(nltarget_kernel,
                                ifname, ifindex,
                                macaddr,
                                vlanid,
                                profileId,
                                portVsi,
                                instanceId,
                                hostUUID,
                                vf,
                                op);

    if (rc) {
        macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("sending of PortProfileRequest failed."));
        return rc;
    }

    while (--repeats >= 0) {
791 792
        rc = ifaceMacvtapLinkDump(nltarget_kernel, NULL, ifindex, tb,
                                  &recvbuf, getLldpadPid);
793 794 795 796 797 798 799 800 801 802
        if (rc)
            goto err_exit;
        rc = getPortProfileStatus(tb, vf, instanceId, nltarget_kernel,
                                  is8021Qbg, &status);
        if (rc)
            goto err_exit;
        if (status == PORT_PROFILE_RESPONSE_SUCCESS ||
            status == PORT_VDP_RESPONSE_SUCCESS) {
            break;
        } else if (status == PORT_PROFILE_RESPONSE_INPROGRESS) {
803
            /* keep trying... */
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
        } else {
            virReportSystemError(EINVAL,
                    _("error %d during port-profile setlink on "
                      "interface %s (%d)"),
                    status, ifname, ifindex);
            rc = 1;
            break;
        }

        usleep(STATUS_POLL_INTERVL_USEC);

        VIR_FREE(recvbuf);
    }

    if (status == PORT_PROFILE_RESPONSE_INPROGRESS) {
        macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("port-profile setlink timed out"));
        rc = -ETIMEDOUT;
    }

err_exit:
    VIR_FREE(recvbuf);

    return rc;
}

# endif /* IFLA_PORT_MAX */


# ifdef IFLA_VF_PORT_MAX

static int
getPhysdevAndVlan(const char *ifname, int *root_ifindex, char *root_ifname,
                  int *vlanid)
{
    int ret;
    unsigned int nth;
    int ifindex = -1;

    *vlanid = -1;
    while (1) {
        if ((ret = ifaceGetNthParent(ifindex, ifname, 1,
                                     root_ifindex, root_ifname, &nth)))
            return ret;
        if (nth == 0)
            break;
        if (*vlanid == -1) {
851
            if (ifaceGetVlanID(root_ifname, vlanid) < 0)
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
                *vlanid = -1;
        }

        ifindex = *root_ifindex;
        ifname = NULL;
    }

    return 0;
}

# endif

static int
doPortProfileOp8021Qbg(const char *ifname,
                       const unsigned char *macaddr,
                       const virVirtualPortProfileParamsPtr virtPort,
                       enum virVirtualPortOp virtPortOp)
{
    int rc;

# ifndef IFLA_VF_PORT_MAX

    (void)ifname;
    (void)macaddr;
    (void)virtPort;
    (void)virtPortOp;
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Kernel VF Port support was missing at compile time."));
    rc = 1;

# else /* IFLA_VF_PORT_MAX */

    int op = PORT_REQUEST_ASSOCIATE;
    struct ifla_port_vsi portVsi = {
        .vsi_mgr_id       = virtPort->u.virtPort8021Qbg.managerID,
        .vsi_type_version = virtPort->u.virtPort8021Qbg.typeIDVersion,
    };
    bool nltarget_kernel = false;
    int vlanid;
    int physdev_ifindex = 0;
    char physdev_ifname[IFNAMSIZ] = { 0, };
    int vf = PORT_SELF_VF;

    if (getPhysdevAndVlan(ifname, &physdev_ifindex, physdev_ifname,
                          &vlanid) != 0) {
        rc = 1;
        goto err_exit;
    }

    if (vlanid < 0)
        vlanid = 0;

    portVsi.vsi_type_id[2] = virtPort->u.virtPort8021Qbg.typeID >> 16;
    portVsi.vsi_type_id[1] = virtPort->u.virtPort8021Qbg.typeID >> 8;
    portVsi.vsi_type_id[0] = virtPort->u.virtPort8021Qbg.typeID;

    switch (virtPortOp) {
909 910 911
    case PREASSOCIATE:
        op = PORT_REQUEST_PREASSOCIATE;
        break;
912 913 914 915 916 917 918 919
    case ASSOCIATE:
        op = PORT_REQUEST_ASSOCIATE;
        break;
    case DISASSOCIATE:
        op = PORT_REQUEST_DISASSOCIATE;
        break;
    default:
        macvtapError(VIR_ERR_INTERNAL_ERROR,
920
                     _("operation type %d not supported"), virtPortOp);
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
        rc = 1;
        goto err_exit;
    }

    rc = doPortProfileOpCommon(nltarget_kernel,
                               physdev_ifname, physdev_ifindex,
                               macaddr,
                               vlanid,
                               NULL,
                               &portVsi,
                               virtPort->u.virtPort8021Qbg.instanceID,
                               NULL,
                               vf,
                               op);

err_exit:

# endif /* IFLA_VF_PORT_MAX */

    return rc;
}


# ifdef IFLA_VF_PORT_MAX
static int
946 947 948
getPhysfnDev(const char *linkdev,
             int32_t *vf,
             char **physfndev)
949 950 951
{
    int rc = 0;

952
    if (ifaceIsVirtualFunction(linkdev)) {
953

954 955
        /* if linkdev is SR-IOV VF, then set vf = VF index */
        /* and set linkdev = PF device */
956

957 958 959
        rc = ifaceGetPhysicalFunction(linkdev, physfndev);
        if (!rc)
            rc = ifaceGetVirtualFunctionIndex(*physfndev, linkdev, vf);
960 961 962 963 964 965 966
    } else {

        /* Not SR-IOV VF: physfndev is linkdev and VF index
         * refers to linkdev self
         */

        *vf = PORT_SELF_VF;
R
Roopa Prabhu 已提交
967 968 969 970 971
        *physfndev = strdup(linkdev);
        if (!*physfndev) {
            virReportOOMError();
            rc = -1;
        }
972 973 974 975 976 977 978 979
    }

    return rc;
}
# endif /* IFLA_VF_PORT_MAX */

static int
doPortProfileOp8021Qbh(const char *ifname,
980
                       const unsigned char *macaddr,
981 982 983 984 985 986 987 988 989
                       const virVirtualPortProfileParamsPtr virtPort,
                       const unsigned char *vm_uuid,
                       enum virVirtualPortOp virtPortOp)
{
    int rc;

# ifndef IFLA_VF_PORT_MAX

    (void)ifname;
990
    (void)macaddr;
991 992 993 994 995 996 997 998 999
    (void)virtPort;
    (void)vm_uuid;
    (void)virtPortOp;
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("Kernel VF Port support was missing at compile time."));
    rc = 1;

# else /* IFLA_VF_PORT_MAX */

1000
    char *physfndev = NULL;
1001 1002 1003 1004 1005 1006
    unsigned char hostuuid[VIR_UUID_BUFLEN];
    int32_t vf;
    bool nltarget_kernel = true;
    int ifindex;
    int vlanid = -1;

1007
    rc = getPhysfnDev(ifname, &vf, &physfndev);
1008 1009 1010
    if (rc)
        goto err_exit;

1011
    if (ifaceGetIndex(true, physfndev, &ifindex) < 0) {
1012 1013 1014 1015 1016
        rc = 1;
        goto err_exit;
    }

    switch (virtPortOp) {
1017
    case PREASSOCIATE_RR:
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    case ASSOCIATE:
        rc = virGetHostUUID(hostuuid);
        if (rc)
            goto err_exit;

        rc = doPortProfileOpCommon(nltarget_kernel, NULL, ifindex,
                                   macaddr,
                                   vlanid,
                                   virtPort->u.virtPort8021Qbh.profileID,
                                   NULL,
                                   vm_uuid,
                                   hostuuid,
                                   vf,
1031 1032 1033
                                   (virtPortOp == PREASSOCIATE_RR) ?
                                    PORT_REQUEST_PREASSOCIATE_RR
                                    : PORT_REQUEST_ASSOCIATE);
1034 1035 1036 1037
        if (rc == -ETIMEDOUT)
            /* Association timed out, disassociate */
            doPortProfileOpCommon(nltarget_kernel, NULL, ifindex,
                                  NULL,
1038
                                  vlanid,
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
                                  NULL,
                                  NULL,
                                  NULL,
                                  NULL,
                                  vf,
                                  PORT_REQUEST_DISASSOCIATE);
        break;

    case DISASSOCIATE:
        rc = doPortProfileOpCommon(nltarget_kernel, NULL, ifindex,
                                   NULL,
1050
                                   vlanid,
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   vf,
                                   PORT_REQUEST_DISASSOCIATE);
        break;

    default:
        macvtapError(VIR_ERR_INTERNAL_ERROR,
                     _("operation type %d not supported"), virtPortOp);
        rc = 1;
    }

err_exit:
1066
    VIR_FREE(physfndev);
1067 1068 1069 1070 1071 1072 1073 1074

# endif /* IFLA_VF_PORT_MAX */

    return rc;
}

/**
 * vpAssociatePortProfile
1075 1076 1077 1078
 *
 * @macvtap_ifname: The name of the macvtap device
 * @virtPort: pointer to the object holding port profile parameters
 * @vmuuid : the UUID of the virtual machine
1079
 * @vmOp : The VM operation (i.e., create, no-op)
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
 *
 * Associate a port on a swtich with a profile. This function
 * may notify a kernel driver or an external daemon to run
 * the setup protocol. If profile parameters were not supplied
 * by the user, then this function returns without doing
 * anything.
 *
 * Returns 0 in case of success, != 0 otherwise with error
 * having been reported.
 */
1090 1091 1092 1093 1094
int
vpAssociatePortProfileId(const char *macvtap_ifname,
                         const unsigned char *macvtap_macaddr,
                         const char *linkdev,
                         const virVirtualPortProfileParamsPtr virtPort,
1095 1096
                         const unsigned char *vmuuid,
                         enum virVMOperationType vmOp)
1097 1098
{
    int rc = 0;
1099

1100 1101 1102
    VIR_DEBUG("Associating port profile '%p' on link device '%s'",
              virtPort, macvtap_ifname);

1103 1104
    VIR_DEBUG("%s: VM OPERATION: %s", __FUNCTION__, virVMOperationTypeToString(vmOp));

1105
    if (!virtPort || vmOp == VIR_VM_OP_NO_OP)
1106 1107
        return 0;

1108 1109 1110 1111 1112 1113
    switch (virtPort->virtPortType) {
    case VIR_VIRTUALPORT_NONE:
    case VIR_VIRTUALPORT_TYPE_LAST:
        break;

    case VIR_VIRTUALPORT_8021QBG:
1114
        rc = doPortProfileOp8021Qbg(macvtap_ifname, macvtap_macaddr,
1115 1116 1117 1118
                                    virtPort,
                                    (vmOp == VIR_VM_OP_MIGRATE_IN_START)
                                      ? PREASSOCIATE
                                      : ASSOCIATE);
1119 1120 1121
        break;

    case VIR_VIRTUALPORT_8021QBH:
1122 1123 1124 1125 1126
        rc = doPortProfileOp8021Qbh(linkdev, macvtap_macaddr,
                                    virtPort, vmuuid,
                                    (vmOp == VIR_VM_OP_MIGRATE_IN_START)
                                      ? PREASSOCIATE_RR
                                      : ASSOCIATE);
1127 1128
        if (vmOp != VIR_VM_OP_MIGRATE_IN_START && !rc)
            ifaceUp(linkdev);
1129 1130 1131 1132 1133 1134 1135 1136
        break;
    }

    return rc;
}


/**
1137
 * vpDisassociatePortProfile
1138 1139
 *
 * @macvtap_ifname: The name of the macvtap device
1140 1141
 * @macvtap_macaddr : The MAC address of the macvtap
 * @linkdev: The link device in case of macvtap
1142 1143 1144 1145 1146
 * @virtPort: point to object holding port profile parameters
 *
 * Returns 0 in case of success, != 0 otherwise with error
 * having been reported.
 */
1147 1148 1149 1150
int
vpDisassociatePortProfileId(const char *macvtap_ifname,
                            const unsigned char *macvtap_macaddr,
                            const char *linkdev,
1151 1152
                            const virVirtualPortProfileParamsPtr virtPort,
                            enum virVMOperationType vmOp)
1153 1154
{
    int rc = 0;
1155

1156 1157 1158
    VIR_DEBUG("Disassociating port profile id '%p' on link device '%s' ",
              virtPort, macvtap_ifname);

1159 1160
    VIR_DEBUG("%s: VM OPERATION: %s", __FUNCTION__, virVMOperationTypeToString(vmOp));

1161 1162 1163
    if (!virtPort)
       return 0;

1164 1165 1166 1167 1168 1169
    switch (virtPort->virtPortType) {
    case VIR_VIRTUALPORT_NONE:
    case VIR_VIRTUALPORT_TYPE_LAST:
        break;

    case VIR_VIRTUALPORT_8021QBG:
1170 1171
        rc = doPortProfileOp8021Qbg(macvtap_ifname, macvtap_macaddr,
                                    virtPort, DISASSOCIATE);
1172 1173 1174
        break;

    case VIR_VIRTUALPORT_8021QBH:
1175 1176 1177
        /* avoid disassociating twice */
        if (vmOp == VIR_VM_OP_MIGRATE_IN_FINISH)
            break;
1178
        ifaceDown(linkdev);
1179 1180
        rc = doPortProfileOp8021Qbh(linkdev, macvtap_macaddr,
                                    virtPort, NULL, DISASSOCIATE);
1181 1182 1183 1184 1185
        break;
    }

    return rc;
}
1186

1187
#endif /* WITH_MACVTAP || WITH_VIRTUALPORT */
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

VIR_ENUM_IMPL(virVMOperation, VIR_VM_OP_LAST,
    "create",
    "save",
    "restore",
    "destroy",
    "migrate out",
    "migrate in start",
    "migrate in finish",
    "no-op")