macvtap.c 42.6 KB
Newer Older
1
/*
2
 * Copyright (C) 2010 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
#if WITH_MACVTAP || WITH_VIRTUALPORT
31

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

40 41 42 43
# include <linux/if.h>
# include <linux/netlink.h>
# include <linux/rtnetlink.h>
# include <linux/if_tun.h>
44

45 46
# include <netlink/msg.h>

47 48
# include "util.h"
# include "memory.h"
49
# include "logging.h"
50
# include "macvtap.h"
51
# include "interface.h"
52 53
# include "conf/domain_conf.h"
# include "virterror_internal.h"
54
# include "uuid.h"
55
# include "files.h"
56

57
# define VIR_FROM_THIS VIR_FROM_NET
58

59 60 61
# define macvtapError(code, ...)                                           \
        virReportErrorHelper(NULL, VIR_FROM_NET, code, __FILE__,           \
                             __FUNCTION__, __LINE__, __VA_ARGS__)
62

63 64
# define MACVTAP_NAME_PREFIX	"macvtap"
# define MACVTAP_NAME_PATTERN	"macvtap%d"
65

66 67 68 69 70 71 72 73 74
# define MICROSEC_PER_SEC       (1000 * 1000)

# define NLMSGBUF_SIZE  256
# define RATTBUF_SIZE   64

# define NETLINK_ACK_TIMEOUT_S  2

# define STATUS_POLL_TIMEOUT_USEC (10 * MICROSEC_PER_SEC)
# define STATUS_POLL_INTERVL_USEC (MICROSEC_PER_SEC / 8)
75 76


77 78 79 80 81 82 83
# define LLDPAD_PID_FILE  "/var/run/lldpad.pid"


enum virVirtualPortOp {
    ASSOCIATE = 0x1,
    DISASSOCIATE = 0x2,
};
84 85


86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
static int nlOpen(void)
{
    int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    if (fd < 0)
        virReportSystemError(errno,
                             "%s",_("cannot open netlink socket"));
    return fd;
}


/**
 * nlComm:
 * @nlmsg: pointer to netlink message
 * @respbuf: pointer to pointer where response buffer will be allocated
 * @respbuflen: pointer to integer holding the size of the response buffer
 *      on return of the function.
102
 * @nl_pid: the pid of the process to talk to, i.e., pid = 0 for kernel
103 104 105 106 107 108 109
 *
 * Send the given message to the netlink layer and receive response.
 * Returns 0 on success, -1 on error. In case of error, no response
 * buffer will be returned.
 */
static
int nlComm(struct nlmsghdr *nlmsg,
110 111
           char **respbuf, unsigned int *respbuflen,
           int nl_pid)
112 113 114 115
{
    int rc = 0;
    struct sockaddr_nl nladdr = {
            .nl_family = AF_NETLINK,
116
            .nl_pid    = nl_pid,
117 118 119 120 121
            .nl_groups = 0,
    };
    int rcvChunkSize = 1024; // expecting less than that
    int rcvoffset = 0;
    ssize_t nbytes;
122 123 124 125
    struct timeval tv = {
        .tv_sec = NETLINK_ACK_TIMEOUT_S,
    };
    fd_set readfds;
126
    int fd = nlOpen();
127
    int n;
128 129 130 131

    if (fd < 0)
        return -1;

132
    nlmsg->nlmsg_pid = getpid();
133 134 135 136 137 138 139 140 141 142 143
    nlmsg->nlmsg_flags |= NLM_F_ACK;

    nbytes = sendto(fd, (void *)nlmsg, nlmsg->nlmsg_len, 0,
                    (struct sockaddr *)&nladdr, sizeof(nladdr));
    if (nbytes < 0) {
        virReportSystemError(errno,
                             "%s", _("cannot send to netlink socket"));
        rc = -1;
        goto err_exit;
    }

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    n = select(fd + 1, &readfds, NULL, NULL, &tv);
    if (n <= 0) {
        if (n < 0)
            virReportSystemError(errno, "%s",
                                 _("error in select call"));
        if (n == 0)
            virReportSystemError(ETIMEDOUT, "%s",
                                 _("no valid netlink response was received"));
        rc = -1;
        goto err_exit;
    }

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
    while (1) {
        if (VIR_REALLOC_N(*respbuf, rcvoffset+rcvChunkSize) < 0) {
            virReportOOMError();
            rc = -1;
            goto err_exit;
        }

        socklen_t addrlen = sizeof(nladdr);
        nbytes = recvfrom(fd, &((*respbuf)[rcvoffset]), rcvChunkSize, 0,
                          (struct sockaddr *)&nladdr, &addrlen);
        if (nbytes < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
            virReportSystemError(errno, "%s",
                                 _("error receiving from netlink socket"));
            rc = -1;
            goto err_exit;
        }
        rcvoffset += nbytes;
        break;
    }
    *respbuflen = rcvoffset;

err_exit:
    if (rc == -1) {
        VIR_FREE(*respbuf);
        *respbuf = NULL;
        *respbuflen = 0;
    }

189
    VIR_FORCE_CLOSE(fd);
190 191 192 193
    return rc;
}


194 195
# if WITH_MACVTAP

196
static int
197
link_add(const char *type,
198 199 200 201 202 203 204
         const unsigned char *macaddress, int macaddrsize,
         const char *ifname,
         const char *srcdev,
         uint32_t macvlan_mode,
         int *retry)
{
    int rc = 0;
205
    struct nlmsghdr *resp;
206
    struct nlmsgerr *err;
207
    struct ifinfomsg ifinfo = { .ifi_family = AF_UNSPEC };
208 209
    int ifindex;
    char *recvbuf = NULL;
210
    unsigned int recvbuflen;
211 212
    struct nl_msg *nl_msg;
    struct nlattr *linkinfo, *info_data;
213

214
    if (ifaceGetIndex(true, srcdev, &ifindex) != 0)
215 216 217 218
        return -1;

    *retry = 0;

219 220 221 222 223 224
    nl_msg = nlmsg_alloc_simple(RTM_NEWLINK,
                                NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }
225

226
    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
227 228
        goto buffer_too_small;

229
    if (nla_put_u32(nl_msg, IFLA_LINK, ifindex) < 0)
230 231
        goto buffer_too_small;

232
    if (nla_put(nl_msg, IFLA_ADDRESS, macaddrsize, macaddress) < 0)
233 234
        goto buffer_too_small;

235 236 237
    if (ifname &&
        nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
        goto buffer_too_small;
238

239
    if (!(linkinfo = nla_nest_start(nl_msg, IFLA_LINKINFO)))
240 241
        goto buffer_too_small;

242
    if (nla_put(nl_msg, IFLA_INFO_KIND, strlen(type), type) < 0)
243 244 245
        goto buffer_too_small;

    if (macvlan_mode > 0) {
246
        if (!(info_data = nla_nest_start(nl_msg, IFLA_INFO_DATA)))
247 248
            goto buffer_too_small;

249 250
        if (nla_put(nl_msg, IFLA_MACVLAN_MODE, sizeof(macvlan_mode),
                    &macvlan_mode) < 0)
251 252
            goto buffer_too_small;

253
        nla_nest_end(nl_msg, info_data);
254 255
    }

256
    nla_nest_end(nl_msg, linkinfo);
257

258 259 260 261
    if (nlComm(nlmsg_hdr(nl_msg), &recvbuf, &recvbuflen, 0) < 0) {
        rc = -1;
        goto err_exit;
    }
262 263 264 265 266 267 268 269 270 271 272 273

    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;

274
        switch (err->error) {
275 276

        case 0:
277
            break;
278

279
        case -EEXIST:
280 281
            *retry = 1;
            rc = -1;
282
            break;
283 284 285 286 287 288 289

        default:
            virReportSystemError(-err->error,
                                 _("error creating %s type of interface"),
                                 type);
            rc = -1;
        }
290
        break;
291 292

    case NLMSG_DONE:
293
        break;
294 295 296 297 298

    default:
        goto malformed_resp;
    }

299 300 301
err_exit:
    nlmsg_free(nl_msg);

302 303 304 305 306
    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
307 308
    nlmsg_free(nl_msg);

309 310
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("malformed netlink response message"));
311 312 313 314
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
315 316
    nlmsg_free(nl_msg);

317
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
318
                 _("allocated netlink buffer is too small"));
319 320 321 322 323
    return -1;
}


static int
324
link_del(const char *ifname)
325 326
{
    int rc = 0;
327
    struct nlmsghdr *resp;
328 329 330
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = { .ifi_family = AF_UNSPEC };
    char *recvbuf = NULL;
331
    unsigned int recvbuflen;
332
    struct nl_msg *nl_msg;
333

334 335 336 337 338 339
    nl_msg = nlmsg_alloc_simple(RTM_DELLINK,
                                NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }
340

341
    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
342 343
        goto buffer_too_small;

344
    if (nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
345 346
        goto buffer_too_small;

347 348 349 350
    if (nlComm(nlmsg_hdr(nl_msg), &recvbuf, &recvbuflen, 0) < 0) {
        rc = -1;
        goto err_exit;
    }
351 352 353 354 355 356 357 358 359 360 361 362

    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;

363
        if (err->error) {
364 365
            virReportSystemError(-err->error,
                                 _("error destroying %s interface"),
366
                                 ifname);
367 368
            rc = -1;
        }
369
        break;
370 371

    case NLMSG_DONE:
372
        break;
373 374 375 376 377

    default:
        goto malformed_resp;
    }

378 379 380
err_exit:
    nlmsg_free(nl_msg);

381 382 383 384 385
    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
386 387
    nlmsg_free(nl_msg);

388 389
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("malformed netlink response message"));
390 391 392 393
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
394 395
    nlmsg_free(nl_msg);

396
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
397
                 _("allocated netlink buffer is too small"));
398 399 400 401 402
    return -1;
}


/* Open the macvtap's tap device.
403
 * @ifname: Name of the macvtap interface
404 405 406 407 408 409 410 411 412 413 414 415 416 417 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 458 459 460 461 462 463 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
 * @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"));
        fclose(file);
        return -1;
    }

    fclose(file);

    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) {
        // may need to wait for udev to be done
        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;
}


static uint32_t
macvtapModeFromInt(enum virDomainNetdevMacvtapType mode)
{
    switch (mode) {
    case VIR_DOMAIN_NETDEV_MACVTAP_MODE_PRIVATE:
        return MACVLAN_MODE_PRIVATE;

    case VIR_DOMAIN_NETDEV_MACVTAP_MODE_BRIDGE:
        return MACVLAN_MODE_BRIDGE;

    case VIR_DOMAIN_NETDEV_MACVTAP_MODE_VEPA:
    default:
        return MACVLAN_MODE_VEPA;
    }
}


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 543 544 545 546 547
/**
 * 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;
}


S
Stefan Berger 已提交
548 549
/**
 * openMacvtapTap:
550 551 552 553 554 555
 * 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
556 557 558 559
 * @mode: int describing the mode for 'bridge', 'vepa' or 'private'.
 * @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
560 561 562 563 564
 * @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,
565
 * negative value otherwise with error reported.
566 567 568
 *
 */
int
569
openMacvtapTap(const char *tgifname,
570 571 572
               const unsigned char *macaddress,
               const char *linkdev,
               int mode,
573 574 575 576
               int vnet_hdr,
               const unsigned char *vmuuid,
               virVirtualPortProfileParamsPtr virtPortProfile,
               char **res_ifname)
577 578 579 580 581 582 583 584 585 586 587 588
{
    const char *type = "macvtap";
    int c, rc;
    char ifname[IFNAMSIZ];
    int retries, do_retry = 0;
    uint32_t macvtapMode = macvtapModeFromInt(mode);
    const char *cr_ifname;
    int ifindex;

    *res_ifname = NULL;

    if (tgifname) {
589
        if(ifaceGetIndex(false, tgifname, &ifindex) == 0) {
590 591 592 593 594 595 596 597 598
            if (STRPREFIX(tgifname,
                          MACVTAP_NAME_PREFIX)) {
                goto create_name;
            }
            virReportSystemError(errno,
                                 _("Interface %s already exists"), tgifname);
            return -1;
        }
        cr_ifname = tgifname;
599
        rc = link_add(type, macaddress, 6, tgifname, linkdev,
600 601 602 603 604 605 606 607
                      macvtapMode, &do_retry);
        if (rc)
            return -1;
    } else {
create_name:
        retries = 5;
        for (c = 0; c < 8192; c++) {
            snprintf(ifname, sizeof(ifname), MACVTAP_NAME_PATTERN, c);
608
            if (ifaceGetIndex(false, ifname, &ifindex) == ENODEV) {
609
                rc = link_add(type, macaddress, 6, ifname, linkdev,
610 611 612 613 614 615 616 617 618 619 620 621
                              macvtapMode, &do_retry);
                if (rc == 0)
                    break;

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

622 623 624 625 626
    if (vpAssociatePortProfileId(cr_ifname,
                                 macaddress,
                                 linkdev,
                                 virtPortProfile,
                                 vmuuid) != 0) {
627 628 629 630
        rc = -1;
        goto link_del_exit;
    }

631
    rc = ifaceUp(cr_ifname);
632 633
    if (rc != 0) {
        virReportSystemError(errno,
S
Stefan Berger 已提交
634 635 636 637
                             _("cannot 'up' interface %s -- another "
                             "macvtap device may be 'up' and have the same "
                             "MAC address"),
                             cr_ifname);
638
        rc = -1;
639
        goto disassociate_exit;
640 641 642 643
    }

    rc = openTap(cr_ifname, 10);

644 645
    if (rc >= 0) {
        if (configMacvtapTap(rc, vnet_hdr) < 0) {
646
            VIR_FORCE_CLOSE(rc); /* sets rc to -1 */
647
            goto disassociate_exit;
648
        }
649
        *res_ifname = strdup(cr_ifname);
650
    } else
651
        goto disassociate_exit;
652 653 654

    return rc;

655
disassociate_exit:
656 657 658 659
    vpDisassociatePortProfileId(cr_ifname,
                                macaddress,
                                linkdev,
                                virtPortProfile);
660

661
link_del_exit:
S
Stefan Berger 已提交
662
    link_del(cr_ifname);
663 664 665 666 667

    return rc;
}


S
Stefan Berger 已提交
668
/**
E
Eric Blake 已提交
669
 * delMacvtap:
S
Stefan Berger 已提交
670
 * @ifname : The name of the macvtap interface
671
 * @linkdev: The interface name of the NIC to connect to the external bridge
672
 * @virtPortProfile: pointer to object holding the virtual port profile data
673
 *
674 675 676
 * Delete an interface given its name. Disassociate
 * it with the switch if port profile parameters
 * were provided.
677
 */
S
Stefan Berger 已提交
678
void
679
delMacvtap(const char *ifname,
680 681
           const unsigned char *macaddr,
           const char *linkdev,
682
           virVirtualPortProfileParamsPtr virtPortProfile)
683
{
684
    if (ifname) {
685 686 687
        vpDisassociatePortProfileId(ifname, macaddr,
                                    linkdev,
                                    virtPortProfile);
688 689
        link_del(ifname);
    }
690 691
}

692 693 694 695 696 697 698 699 700 701 702 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 730 731 732 733
# endif /* WITH_MACVTAP */

# ifdef IFLA_PORT_MAX

static struct nla_policy ifla_policy[IFLA_MAX + 1] =
{
  [IFLA_VF_PORTS] = { .type = NLA_NESTED },
};

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);
    }

734
    VIR_FORCE_CLOSE(fd);
735 736 737 738 739 740 741 742 743 744

    return pid;
}


static int
link_dump(bool nltarget_kernel, const char *ifname, int ifindex,
          struct nlattr **tb, char **recvbuf)
{
    int rc = 0;
745
    struct nlmsghdr *resp;
746 747 748 749 750 751 752
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = {
        .ifi_family = AF_UNSPEC,
        .ifi_index  = ifindex
    };
    unsigned int recvbuflen;
    uint32_t pid = 0;
753
    struct nl_msg *nl_msg;
754 755 756

    *recvbuf = NULL;

757 758 759 760 761
    nl_msg = nlmsg_alloc_simple(RTM_GETLINK, NLM_F_REQUEST);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }
762

763
    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
764 765 766
        goto buffer_too_small;

    if (ifindex < 0 && ifname) {
767
        if (nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
768 769 770 771 772
            goto buffer_too_small;
    }

    if (!nltarget_kernel) {
        pid = getLldpadPid();
773 774 775 776
        if (pid == 0) {
            rc = -1;
            goto err_exit;
        }
777 778
    }

779 780 781 782
    if (nlComm(nlmsg_hdr(nl_msg), recvbuf, &recvbuflen, pid) < 0) {
        rc = -1;
        goto err_exit;
    }
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

    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 dumping %s (%d) interface"),
                                 ifname, ifindex);
            rc = -1;
        }
        break;

    case GENL_ID_CTRL:
    case NLMSG_DONE:
        if (nlmsg_parse(resp, sizeof(struct ifinfomsg),
                        tb, IFLA_MAX, ifla_policy)) {
            goto malformed_resp;
        }
        break;

    default:
        goto malformed_resp;
    }

    if (rc != 0)
        VIR_FREE(*recvbuf);

818 819 820
err_exit:
    nlmsg_free(nl_msg);

821 822 823
    return rc;

malformed_resp:
824 825
    nlmsg_free(nl_msg);

826 827 828 829 830 831
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("malformed netlink response message"));
    VIR_FREE(*recvbuf);
    return -1;

buffer_too_small:
832 833
    nlmsg_free(nl_msg);

834
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
835
                 _("allocated netlink buffer is too small"));
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
    return -1;
}


/**
 * ifaceGetNthParent
 *
 * @ifindex : the index of the interface or -1 if ifname is given
 * @ifname : the name of the interface; ignored if ifindex is valid
 * @nthParent : the nth parent interface to get
 * @parent_ifindex : pointer to int
 * @parent_ifname : pointer to buffer of size IFNAMSIZ
 * @nth : the nth parent that is actually returned; if for example eth0.100
 *        was given and the 100th parent is to be returned, then eth0 will
 *        most likely be returned with nth set to 1 since the chain does
 *        not have more interfaces
 *
 * Get the nth parent interface of the given interface. 0 is the interface
 * itself.
 *
 * Return 0 on success, != 0 otherwise
 */
static int
ifaceGetNthParent(int ifindex, const char *ifname, unsigned int nthParent,
                  int *parent_ifindex, char *parent_ifname,
                  unsigned int *nth)
{
    int rc;
    struct nlattr *tb[IFLA_MAX + 1] = { NULL, };
    char *recvbuf = NULL;
    bool end = false;
    unsigned int i = 0;

    *nth = 0;

871 872 873
    if (ifindex <= 0 && ifaceGetIndex(true, ifname, &ifindex) != 0)
        return 1;

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
    while (!end && i <= nthParent) {
        rc = link_dump(true, ifname, ifindex, tb, &recvbuf);
        if (rc)
            break;

        if (tb[IFLA_IFNAME]) {
            if (!virStrcpy(parent_ifname, (char*)RTA_DATA(tb[IFLA_IFNAME]),
                           IFNAMSIZ)) {
                macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                             _("buffer for root interface name is too small"));
                VIR_FREE(recvbuf);
                return 1;
            }
            *parent_ifindex = ifindex;
        }

        if (tb[IFLA_LINK]) {
            ifindex = *(int *)RTA_DATA(tb[IFLA_LINK]);
            ifname = NULL;
        } else
            end = true;

        VIR_FREE(recvbuf);

        i++;
    }

    if (nth)
        *nth = i - 1;

    return rc;
}
906 907

/**
908 909 910 911 912 913 914 915 916 917 918 919 920 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 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
 * 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]);
986
        rc = 0;
987
    } else {
988 989 990 991 992 993 994 995
        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;
        }
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    }

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;
1019
    struct nlmsghdr *resp;
1020 1021 1022 1023 1024 1025 1026 1027
    struct nlmsgerr *err;
    struct ifinfomsg ifinfo = {
        .ifi_family = AF_UNSPEC,
        .ifi_index  = ifindex,
    };
    char *recvbuf = NULL;
    unsigned int recvbuflen = 0;
    uint32_t pid = 0;
1028 1029
    struct nl_msg *nl_msg;
    struct nlattr *vfports = NULL, *vfport;
1030

1031 1032 1033 1034 1035
    nl_msg = nlmsg_alloc_simple(RTM_SETLINK, NLM_F_REQUEST);
    if (!nl_msg) {
        virReportOOMError();
        return -1;
    }
1036

1037
    if (nlmsg_append(nl_msg,  &ifinfo, sizeof(ifinfo), NLMSG_ALIGNTO) < 0)
1038 1039
        goto buffer_too_small;

1040 1041 1042
    if (ifname &&
        nla_put(nl_msg, IFLA_IFNAME, strlen(ifname)+1, ifname) < 0)
        goto buffer_too_small;
1043 1044

    if (macaddr && vlanid >= 0) {
1045
        struct nlattr *vfinfolist, *vfinfo;
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        struct ifla_vf_mac ifla_vf_mac = {
            .vf = vf,
            .mac = { 0, },
        };
        struct ifla_vf_vlan ifla_vf_vlan = {
            .vf = vf,
            .vlan = vlanid,
            .qos = 0,
        };

        memcpy(ifla_vf_mac.mac, macaddr, 6);

1058
        if (!(vfinfolist = nla_nest_start(nl_msg, IFLA_VFINFO_LIST)))
1059 1060
            goto buffer_too_small;

1061
        if (!(vfinfo = nla_nest_start(nl_msg, IFLA_VF_INFO)))
1062 1063
            goto buffer_too_small;

1064 1065
        if (!nla_put(nl_msg, IFLA_VF_MAC, sizeof(ifla_vf_mac),
                     &ifla_vf_mac) < 0)
1066 1067
            goto buffer_too_small;

1068 1069
        if (!nla_put(nl_msg, IFLA_VF_VLAN, sizeof(ifla_vf_vlan),
                     &ifla_vf_vlan) < 0)
1070 1071
            goto buffer_too_small;

1072 1073
        nla_nest_end(nl_msg, vfinfo);
        nla_nest_end(nl_msg, vfinfolist);
1074 1075 1076
    }

    if (vf == PORT_SELF_VF && nltarget_kernel) {
1077 1078
        if (!(vfport = nla_nest_start(nl_msg, IFLA_PORT_SELF)))
            goto buffer_too_small;
1079
    } else {
1080
        if (!(vfports = nla_nest_start(nl_msg, IFLA_VF_PORTS)))
1081 1082 1083
            goto buffer_too_small;

        /* begin nesting vfports */
1084 1085
        if (!(vfport = nla_nest_start(nl_msg, IFLA_VF_PORT)))
            goto buffer_too_small;
1086 1087 1088
    }

    if (profileId) {
1089 1090
        if (nla_put(nl_msg, IFLA_PORT_PROFILE, strlen(profileId) + 1,
                    profileId) < 0)
1091 1092 1093 1094
            goto buffer_too_small;
    }

    if (portVsi) {
1095 1096
        if (nla_put(nl_msg, IFLA_PORT_VSI_TYPE, sizeof(*portVsi),
                    portVsi) < 0)
1097 1098 1099 1100
            goto buffer_too_small;
    }

    if (instanceId) {
1101 1102
        if (nla_put(nl_msg, IFLA_PORT_INSTANCE_UUID, VIR_UUID_BUFLEN,
                    instanceId) < 0)
1103 1104 1105 1106
            goto buffer_too_small;
    }

    if (hostUUID) {
1107 1108
        if (nla_put(nl_msg, IFLA_PORT_HOST_UUID, VIR_UUID_BUFLEN,
                    hostUUID) < 0)
1109 1110 1111 1112
            goto buffer_too_small;
    }

    if (vf != PORT_SELF_VF) {
1113
        if (nla_put(nl_msg, IFLA_PORT_VF, sizeof(vf), &vf) < 0)
1114 1115 1116
            goto buffer_too_small;
    }

1117
    if (nla_put(nl_msg, IFLA_PORT_REQUEST, sizeof(op), &op) < 0)
1118 1119 1120
        goto buffer_too_small;

    /* end nesting of vport */
1121
    nla_nest_end(nl_msg, vfport);
1122 1123 1124

    if (vfports) {
        /* end nesting of vfports */
1125
        nla_nest_end(nl_msg, vfports);
1126 1127 1128 1129
    }

    if (!nltarget_kernel) {
        pid = getLldpadPid();
1130 1131 1132 1133
        if (pid == 0) {
            rc = -1;
            goto err_exit;
        }
1134 1135
    }

1136 1137 1138 1139
    if (nlComm(nlmsg_hdr(nl_msg), &recvbuf, &recvbuflen, pid) < 0) {
        rc = -1;
        goto err_exit;
    }
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

    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;
    }

1167 1168 1169
err_exit:
    nlmsg_free(nl_msg);

1170 1171 1172 1173 1174
    VIR_FREE(recvbuf);

    return rc;

malformed_resp:
1175 1176
    nlmsg_free(nl_msg);

1177 1178 1179 1180 1181 1182
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
                 _("malformed netlink response message"));
    VIR_FREE(recvbuf);
    return -1;

buffer_too_small:
1183 1184
    nlmsg_free(nl_msg);

1185
    macvtapError(VIR_ERR_INTERNAL_ERROR, "%s",
1186
                 _("allocated netlink buffer is too small"));
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
    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;
    char *recvbuf = NULL;
    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) {
        rc = link_dump(nltarget_kernel, NULL, ifindex, tb, &recvbuf);
        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) {
            // keep trying...
        } 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) {
            if (ifaceGetVlanID(root_ifname, vlanid))
                *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) {
    case ASSOCIATE:
        op = PORT_REQUEST_ASSOCIATE;
        break;
    case DISASSOCIATE:
        op = PORT_REQUEST_DISASSOCIATE;
        break;
    default:
        macvtapError(VIR_ERR_INTERNAL_ERROR,
                     _("operation type %d not supported"), op);
        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
getPhysfn(const char *linkdev,
          int32_t *vf,
          char **physfndev)
{
    int rc = 0;
    bool virtfn = false;

    if (virtfn) {

        // XXX: if linkdev is SR-IOV VF, then set vf = VF index
        // XXX: and set linkdev = PF device
        // XXX: need to use get_physical_function_linux() or
        // XXX: something like that to get PF
        // XXX: device and figure out VF index

        rc = 1;

    } else {

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

        *vf = PORT_SELF_VF;
        *physfndev = (char *)linkdev;
    }

    return rc;
}
# endif /* IFLA_VF_PORT_MAX */

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

# ifndef IFLA_VF_PORT_MAX

    (void)ifname;
    (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 */

    char *physfndev;
    unsigned char hostuuid[VIR_UUID_BUFLEN];
    int32_t vf;
    bool nltarget_kernel = true;
    int ifindex;
    int vlanid = -1;
    const unsigned char *macaddr = NULL;

    rc = getPhysfn(ifname, &vf, &physfndev);
    if (rc)
        goto err_exit;

    if (ifaceGetIndex(true, physfndev, &ifindex) != 0) {
        rc = 1;
        goto err_exit;
    }

    switch (virtPortOp) {
    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,
                                   PORT_REQUEST_ASSOCIATE);
        if (rc == -ETIMEDOUT)
            /* Association timed out, disassociate */
            doPortProfileOpCommon(nltarget_kernel, NULL, ifindex,
                                  NULL,
                                  0,
                                  NULL,
                                  NULL,
                                  NULL,
                                  NULL,
                                  vf,
                                  PORT_REQUEST_DISASSOCIATE);
        if (!rc)
            ifaceUp(ifname);
        break;

    case DISASSOCIATE:
        rc = doPortProfileOpCommon(nltarget_kernel, NULL, ifindex,
                                   NULL,
                                   0,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   vf,
                                   PORT_REQUEST_DISASSOCIATE);
        ifaceDown(ifname);
        break;

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

err_exit:

# endif /* IFLA_VF_PORT_MAX */

    return rc;
}

/**
 * vpAssociatePortProfile
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
 *
 * @macvtap_ifname: The name of the macvtap device
 * @virtPort: pointer to the object holding port profile parameters
 * @vmuuid : the UUID of the virtual machine
 *
 * 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.
 */
1519 1520 1521 1522 1523 1524
int
vpAssociatePortProfileId(const char *macvtap_ifname,
                         const unsigned char *macvtap_macaddr,
                         const char *linkdev,
                         const virVirtualPortProfileParamsPtr virtPort,
                         const unsigned char *vmuuid)
1525 1526
{
    int rc = 0;
1527

1528 1529 1530 1531 1532 1533 1534 1535 1536
    VIR_DEBUG("Associating port profile '%p' on link device '%s'",
              virtPort, macvtap_ifname);

    switch (virtPort->virtPortType) {
    case VIR_VIRTUALPORT_NONE:
    case VIR_VIRTUALPORT_TYPE_LAST:
        break;

    case VIR_VIRTUALPORT_8021QBG:
1537 1538
        rc = doPortProfileOp8021Qbg(macvtap_ifname, macvtap_macaddr,
                                    virtPort, ASSOCIATE);
1539 1540 1541
        break;

    case VIR_VIRTUALPORT_8021QBH:
1542 1543 1544
        rc = doPortProfileOp8021Qbh(linkdev, virtPort,
                                    vmuuid,
                                    ASSOCIATE);
1545 1546 1547 1548 1549 1550 1551 1552
        break;
    }

    return rc;
}


/**
1553
 * vpDisassociatePortProfile
1554 1555
 *
 * @macvtap_ifname: The name of the macvtap device
1556 1557
 * @macvtap_macaddr : The MAC address of the macvtap
 * @linkdev: The link device in case of macvtap
1558 1559 1560 1561 1562
 * @virtPort: point to object holding port profile parameters
 *
 * Returns 0 in case of success, != 0 otherwise with error
 * having been reported.
 */
1563 1564 1565 1566 1567
int
vpDisassociatePortProfileId(const char *macvtap_ifname,
                            const unsigned char *macvtap_macaddr,
                            const char *linkdev,
                            const virVirtualPortProfileParamsPtr virtPort)
1568 1569
{
    int rc = 0;
1570

1571 1572 1573 1574 1575 1576 1577 1578 1579
    VIR_DEBUG("Disassociating port profile id '%p' on link device '%s' ",
              virtPort, macvtap_ifname);

    switch (virtPort->virtPortType) {
    case VIR_VIRTUALPORT_NONE:
    case VIR_VIRTUALPORT_TYPE_LAST:
        break;

    case VIR_VIRTUALPORT_8021QBG:
1580 1581
        rc = doPortProfileOp8021Qbg(macvtap_ifname, macvtap_macaddr,
                                    virtPort, DISASSOCIATE);
1582 1583 1584
        break;

    case VIR_VIRTUALPORT_8021QBH:
1585 1586 1587
        rc = doPortProfileOp8021Qbh(linkdev, virtPort,
                                    NULL,
                                    DISASSOCIATE);
1588 1589 1590 1591 1592
        break;
    }

    return rc;
}
1593

1594
#endif /* WITH_MACVTAP || WITH_VIRTUALPORT */