Commit Graph

3156 Commits

Author SHA1 Message Date
Erik Skultety
92e30a4dac mdev: Fix daemon crash on domain shutdown after reconnect
The problem resides in virHostdevUpdateActiveMediatedDevices which gets
called during qemuProcessReconnect. The issue here is that
virMediatedDeviceListAdd takes a pointer to the item to be added to the
list to which VIR_APPEND_ELEMENT is used, which also clears the pointer.
However, in this case only the local copy of the pointer got cleared,
leaving the original pointing to valid memory. To sum it up, during
cleanup phase, the original pointer is freed and the daemon crashes
basically any time it would access it.

Backtrace:
0x00007ffff3ccdeba in __strcmp_sse2_unaligned
0x00007ffff72a444a in virMediatedDeviceListFindIndex
0x00007ffff7241446 in virHostdevReAttachMediatedDevices
0x00007fffc60215d9 in qemuHostdevReAttachMediatedDevices
0x00007fffc60216dc in qemuHostdevReAttachDomainDevices
0x00007fffc6046e6f in qemuProcessStop
0x00007fffc6091596 in processMonitorEOFEvent
0x00007fffc6091793 in qemuProcessEventHandler
0x00007ffff7294bf5 in virThreadPoolWorker
0x00007ffff7294184 in virThreadHelper
0x00007ffff3fdc3c4 in start_thread () from /lib64/libpthread.so.0
0x00007ffff3d269cf in clone () from /lib64/libc.so.6

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1446455

Signed-off-by: Erik Skultety <eskultet@redhat.com>
Reviewed-by: Laine Stump <laine@laine.org>
2017-05-04 08:05:03 +02:00
Erik Skultety
2739a983f2 util: mdev: Use a local variable instead of a direct pointer access
Use a local variable to hold data, rather than accessing the pointer
after calling virMediatedDeviceListAdd (therefore VIR_APPEND_ELEMENT).
Although not causing an issue at the moment, this change is a necessary
prerequisite for tweaking virMediatedDeviceListAdd in a separate patch,
which will take a reference for the source pointer (instead of pointer
value) and will clear it along the way.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
Reviewed-by: Laine Stump <laine@laine.org>
Reviewed-by: Pavel Hrdina <phrdina@redhat.com>
2017-05-04 07:54:42 +02:00
Daniel P. Berrange
71890992da Fix padding of encrypted data
If we are encoding a block of data that is 16 bytes in length,
we cannot leave it as 16 bytes, we must pad it out to the next
block boundary, 32 bytes. Without this padding, the decoder will
incorrectly treat the last byte of plain text as the padding
length, as it can't distinguish padded from non-padded data.

The problem exhibited itself when using a 16 byte passphrase
for a LUKS volume

  $ virsh secret-set-value 55806c7d-8e93-456f-829b-607d8c198367 \
       $(echo -n 1234567812345678 | base64)
  Secret value set

  $ virsh start demo
  error: Failed to start domain demo
  error: internal error: process exited while connecting to monitor: >>>>>>>>>>Len 16
  2017-05-02T10:35:40.016390Z qemu-system-x86_64: -object \
    secret,id=virtio-disk1-luks-secret0,data=SEtNi5vDUeyseMKHwc1c1Q==,\
    keyid=masterKey0,iv=zm7apUB1A6dPcH53VW960Q==,format=base64: \
    Incorrect number of padding bytes (56) found on decrypted data

Notice how the padding '56' corresponds to the ordinal value of
the character '8'.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-05-02 17:27:13 +01:00
Laine Stump
30e672301d util: rename/move VIR_NET_GENERATED_PREFIX to be consistent
... with VIR_NET_GENERATED_MACV???_PREFIX, which is defined in
util/virnetdevmacvlan.h.

Since VIR_NET_GENERATED_PREFIX is used for plain tap devices, it is
renamed to VIR_NET_GENERATED_TAP_PREFIX and moved to virnetdev.h
2017-04-28 09:43:52 -04:00
Laine Stump
a05400ef55 util: make macvtap/macvlan generated name #defines available to other files
MACVTAP_NAME_PREFIX and MACVLAN_NAME_PREFIX could be useful to other
files if they were defined in virnetdevmacvlan.h instead of
virnetdevmacvlan.c, so do that (while slightly renaming them and also
adding yet another #define that chooses between macvlan/macvtap based
on flags).

This is a prerequisite to fix: https://bugzilla.redhat.com/1335798
2017-04-28 09:43:52 -04:00
Michal Privoznik
d111f52c35 iohelper: Remove unused mode
After 1eb6647979 nobody calls the iohelper with 6 arguments.
Everybody uses the other mode. Well, the only user of iohelper
after the previous commit is virFileWrapperFd really.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
2017-04-28 14:17:10 +02:00
Michal Privoznik
d1a60f4c3b virfdstream: Drop iohelper in favour of a thread
Currently we use iohelper for virFDStream implementation. This is
because UNIX I/O can lie sometimes: even though a FD for a
file/block device is set as unblocking, actual read()/write() can
block. To avoid this, a pipe is created and one end is kept for
read/write while the other is handed over to iohelper to
write/read the data for us. Thus it's iohelper which gets blocked
and not our event loop.

This approach has two problems:
1) we are spawning a new process.
2) any exchange of information between daemon and iohelper can be
done only through the pipe.

Therefore, iohelper is replaced with an implementation in thread
which is created just for the stream lifetime. The data are still
transferred through pipe (for now), but both problems described
above are solved.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
2017-04-28 14:17:10 +02:00
Michal Privoznik
585eb46920 virFDStreamData: Turn into virObjectLockable
While this is no functional change, it makes the code look a bit
nicer. Moreover, it prepares ground for future work.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
2017-04-28 14:17:10 +02:00
Michal Privoznik
58667ddd5b fdstream: s/struct virFDStreamData */virFDStreamDataPtr/
There is really no reason why we should have to have 'struct'
everywhere.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
2017-04-28 14:17:10 +02:00
Michal Privoznik
1a4a4ffa3e lib: Fix c99 style comments
We prefer c89 style of comments.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-04-27 14:13:19 +02:00
Wang King
81bbdafb96 util: Drop unused var @errbuf from virPCIGetDeviceAddressFromSysfsLink
Commit @a7035662 forgot to remove it when doing a refactor.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-04-27 12:21:17 +02:00
Cédric Bosdonnat
b63de148a4 IPv6 route check: list devices only once
If several RA routes are found for the same device, only list that
device once in the error message.
2017-04-26 18:59:24 +02:00
Daniel P. Berrange
02fb15fb60 util: switch over to use keycodemapdb GIT submodule
A long time ago we imported the keymaps.csv file from GTK-VNC so we
can do conversions between keycode sets. Meanwhile lots of bug fixes
have gone into this CSV file and libvirt hasn't kept in sync. The
keymaps.csv file and associated generator script has been pulled out
of GTK-VNC into a dedicated GIT repo for use as a submodule. This
allows GTK-VNC, SPICE-GTK, QEMU and libvirt to share the same master
database and tools and pushing updates merely requires a submodule
commit update as with gnulib.

The test suite is updated to cover some extra boundary conditions.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-04-25 21:14:18 +01:00
Roman Bogorodskiy
5e010605d1 util: relax virNetDevSetCoalesce() stub
Currently, virNetDevSetCoalesce() stub is always returning error. As
it's used by virNetDevTapCreateInBridgePort(), it essentially breaks
bridged networking if coalesce is not supported.

To make it work, relax the stub to trigger error only when its
coalesce argument is not NULL, otherwise report success.
2017-04-24 15:57:54 +04:00
Laine Stump
997134fb8b util: allow ignoring SIOCSIFHWADDR when errno is EPERM
Commit f4ef3a71 made a variation of virNetDevSetMAC that would return
without logging an error message if errno was set to
EADDRNOTAVAIL. This errno is set by some SRIOV VF drivers (in
particular igbvf) when they fail to set the device's MAC address due
to the PF driver refusing the request. This is useful if we want to
try a different method of setting the VF MAC address before giving up
(Commit 86556e16 actually does this, setting the desired MAC address
to the "admin MAC in the PF, then detaching and reattaching the VF
netdev driver to force a reinit of the MAC address).

During testing of Bug 1442040 t was discovered that the ixgbe driver
returns EPERM in this situation, so this patch changes the exception
case for silent+non-terminal failure to account for this difference.

Completes resolution to: https://bugzilla.redhat.com/1415609 (RHEL 7.4)
                         https://bugzilla.redhat.com/1442040 (RHEL 7.3.z)
2017-04-21 10:37:13 -04:00
Daniel P. Berrange
e6625ed410 util: fix virNetDevSetCoalesce fallback on Win32/FreeBSD
The current fallback stub for virNetDevSetCoalesce is inside an
earlier conditional block. This deals with the feature being
missing on older Linux platforms. We need a second fallback stub
though, outside the top level conditional, to ensure builds work
on Win32/FreeBSD platforms too.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-04-21 14:57:31 +01:00
Martin Kletzander
fcef44728d Set coalesce settings for domain interfaces
This patch makes use of the virNetDevSetCoalesce() function to make
appropriate settings effective for devices that support them.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1414627

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-04-21 13:35:04 +02:00
Martin Kletzander
652ef9bc8c util: Add virNetDevSetCoalesce function
That function is able to configure coalesce settings for an interface,
similarly to 'ethtool -C'.  This function also updates back the
structure so that it contains actual data on the device (if the device
doesn't support some settings kernel might just return 0 and not set
whatever is not supported), so this way we'll have up-to-date
information in the live domain XML.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-04-21 13:29:39 +02:00
Pavel Hrdina
42000bf7e5 util: check ifa_addr pointer before accessing its elements
Reported by Rafał Wojciechowski <it@rafalwojciechowski.pl>.

Thread 1 (Thread 0x7f194b99d700 (LWP 5631)):
0  virNetDevGetifaddrsAddress (addr=0x7f194b99c7c0, ifname=0x7f193400e2b0 "ovirtmgmt") at util/virnetdevip.c:738
1  virNetDevIPAddrGet (ifname=0x7f193400e2b0 "ovirtmgmt", addr=addr@entry=0x7f194b99c7c0) at util/virnetdevip.c:795
2  0x00007f19467800d6 in networkGetNetworkAddress (netname=<optimized out>, netaddr=netaddr@entry=0x7f1924013f18) at network/bridge_driver.c:4780
3  0x00007f193e43a33c in qemuProcessGraphicsSetupNetworkAddress (listenAddr=0x7f19340f7650 "127.0.0.1", glisten=0x7f1924013f10) at qemu/qemu_process.c:4062
4  qemuProcessGraphicsSetupListen (vm=<optimized out>, graphics=0x7f1924014f10, cfg=0x7f1934119f00) at qemu/qemu_process.c:4133
5  qemuProcessSetupGraphics (flags=17, vm=0x7f19240155d0, driver=0x7f193411f1d0) at qemu/qemu_process.c:4196
6  qemuProcessPrepareDomain (conn=conn@entry=0x7f192c00ab50, driver=driver@entry=0x7f193411f1d0, vm=vm@entry=0x7f19240155d0, flags=flags@entry=17) at qemu/qemu_process.c:4969
7  0x00007f193e4417c0 in qemuProcessStart (conn=conn@entry=0x7f192c00ab50, driver=driver@entry=0x7f193411f1d0, vm=0x7f19240155d0,asyncJob=asyncJob@entry=QEMU_ASYNC_JOB_START, migrateFrom=migrateFrom@entry=0x0, migrateFd=migrateFd@entry=-1, migratePath=migratePath@entry=0x0,snapshot=snapshot@entry=0x0, vmop=vmop@entry=VIR_NETDEV_VPORT_PROFILE_OP_CREATE, flags=17, flags@entry=1) at qemu/qemu_process.c:5553

Man page for getifaddrs also states that the "ifa_addr" may contain
a null pointer which happens if there is an existing network interface
on the host without IP address.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2017-04-21 11:05:18 +02:00
Daniel P. Berrange
728cacc8ab annotate all mocked functions with noinline
CLang's optimizer is more aggressive at inlining functions than
gcc and so will often inline functions that our tests want to
mock-override. This causes the test to fail in bizarre ways.

We don't want to disable inlining completely, but we must at
least prevent inlining of mocked functions. Fortunately there
is a 'noinline' attribute that lets us control this per function.

A syntax check rule is added that parses tests/*mock.c to extract
the list of functions that are mocked (restricted to names starting
with 'vir' prefix). It then checks that src/*.h header file to
ensure it has a 'ATTRIBUTE_NOINLINE' annotation. This should prevent
use from bit-rotting in future.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-04-19 10:51:51 +01:00
Shivaprasad G Bhat
8e09663f7f pci: recognize/report GEN4 (PCIe 4.0) card 16GT/s Link speed
Without this added enum value, nodedev-dumpxml of a GEN4 (PCIe 4.0)
card will fail (due to the unrecognized link speed), and since
nodedev-detach and nodedev-reattach internally do a dumpxml+parse,
they will also fail. With this patch, all those operations succeed.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
2017-04-13 13:23:56 -04:00
Wim ten Have
ae5d758209 virConfSaveValue: protect against a NULL pointer reference
Fix xlconfigtest runs build for --enable-test-oom on
        Xen XL-2-XML Parse  channel-pty

Program received signal SIGSEGV, Segmentation fault.

    #0  0x00007ffff3c2b373 in __strchr_sse2 () from /lib64/libc.so.6
==> #1  0x00007ffff7875701 in virConfSaveValue (buf=buf@entry=0x7fffffffd8a0, val=val@entry=0x674750) at util/virconf.c:290
    #2  0x00007ffff7875668 in virConfSaveValue (buf=buf@entry=0x7fffffffd8a0, val=<optimized out>) at util/virconf.c:306
    #3  0x00007ffff78757ef in virConfSaveEntry (buf=buf@entry=0x7fffffffd8a0, cur=cur@entry=0x674780) at util/virconf.c:338
    #4  0x00007ffff78783eb in virConfWriteMem (memory=0x665570 "", len=len@entry=0x7fffffffd910, conf=conf@entry=0x65b940)
        at util/virconf.c:1543
    #5  0x000000000040eccb in testCompareParseXML (replaceVars=<optimized out>, xml=<optimized out>,
        xlcfg=0x662c00 "/home/wtenhave/WORK/libvirt/OOMtesting/libvirt-devel/tests/xlconfigdata/test-channel-pty.cfg")
        at xlconfigtest.c:108
    #6  testCompareHelper (data=<optimized out>) at xlconfigtest.c:205
    #7  0x0000000000410b3a in virTestRun (title=title@entry=0x432cc0 "Xen XL-2-XML Parse  channel-pty",
        body=body@entry=0x40e9b0 <testCompareHelper>, data=data@entry=0x7fffffffd9f0) at testutils.c:247
    #8  0x000000000040f322 in mymain () at xlconfigtest.c:278
    #9  0x0000000000411410 in virTestMain (argc=1, argv=0x7fffffffdba8, func=0x40f660 <mymain>) at testutils.c:992
    #10 0x00007ffff3bc0401 in __libc_start_main () from /lib64/libc.so.6
    #11 0x000000000040e86a in _start ()

    (gdb) frame 1
    #1  0x00007ffff7875701 in virConfSaveValue (buf=buf@entry=0x7fffffffd8a0, val=val@entry=0x674750) at util/virconf.c:290
    290                 if (strchr(val->str, '\n') != NULL) {
    (gdb) print *val
    $1 = {type = VIR_CONF_STRING, next = 0x0, l = 0, str = 0x0, list = 0x0}

Signed-off-by: Wim ten Have <wim.ten.have@oracle.com>
2017-04-13 10:54:04 -06:00
Wang King
123770cd4e util: Fix resource leak
The virRotatingFileWriterAppend method leaks the file->entry
on the virRotatingFileWriterEntryNew failing path.
2017-04-13 08:14:54 -04:00
Ján Tomko
b80b0c4517 util: add missing equal sign in initialization
Fix the build with clang:
util/virperf.c:86:27: error: use of GNU 'missing =' extension
    in designator [-Werror,-Wgnu-designator]
    [VIR_PERF_EVENT_MBML] {
                          ^
                          =
2017-04-13 14:02:46 +02:00
Daniel P. Berrange
bdcf6e4810 perf: get rid of pointless virPerfGetEvent() method
The virPerfGetEvent method pointlessly checks for a NULL
parameter and the range of an enum value. The whole point
of using an enum is that we can avoid such checks. Just
replace calls to virPerfGetEvent, with perf->events[type]
array access.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-04-12 16:33:05 +01:00
Daniel P. Berrange
5fca70ef57 perf: get rid of pointless virPerfGetEventAttr() method
The virPerfGetEventAttr method contains a totally pointless
loop. Remove it, verify the array size statically, and then
just use an array index to access the perf event.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-04-12 16:33:05 +01:00
Wang King
c5ca209f58 util: systemd: Don't strlen a possibly NULL string
Coverity complains about virBufferCurrentContent might be return null
when calling strlen, so check virBufferError first before calling
strlen.
2017-04-12 10:55:42 +02:00
Pavel Hrdina
ffc810b7c7 src: fix multiple resource leaks in loops
All of the variables are filled inside a loop and therefore
needs to be also freed in every cycle.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2017-04-11 13:23:00 +02:00
Martin Kletzander
8f0b731d22 util: Add virStringTrimOptionalNewline
And use it in virFileRead*

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-04-07 08:49:34 +02:00
Martin Kletzander
b11e893224 util: Fix virDirRead() description
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-04-07 08:49:34 +02:00
Michal Privoznik
9c037c6cae virISCSIGetSession: Don't leak memory
This function runs an iscsi command and parses its output.
However, due to the nature of things, virISCSIExtractSession()
callback can be called multiple times. In each run it would
allocate new memory and overwrite the variable where we keep
pointer to it and thus leaking old allocations.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-04-05 15:18:30 +02:00
Michal Privoznik
349badbffd virStorageSourceClear: Don't leave dangling pointers behind
Imagine that this function is called twice over the same disk
source. While in the first run all allocated memory is freed, not
all pointers are set to NULL (e.g. def->srcpool). So when called
again, these poitners are freed again resulting in double free.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-04-05 15:18:30 +02:00
Ján Tomko
04be4111d9 util: ignore -Wcast-align in virNetlinkDumpCommand
Similar to commit b202c39 ignore the warning that breaks the build
with clang:
util/virnetlink.c:365:52: error: cast from 'char *' to 'struct nlmsghdr *'
 increases required alignment from 1 to 4 [-Werror,-Wcast-align]
        for (msg = resp; NLMSG_OK(msg, len); msg = NLMSG_NEXT(msg, len)) {
                                                   ^~~~~~~~~~~~~~~~~~~~
/usr/include/linux/netlink.h:87:7: note: expanded from macro 'NLMSG_NEXT'
         (struct nlmsghdr*)(((char*)(nlh)) + NLMSG_ALIGN((nlh)->nlmsg_len)))
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-04-04 12:53:23 +02:00
John Ferlan
b7d44f450c storage: Fix capacity value for LUKS encrypted volumes
https://bugzilla.redhat.com/show_bug.cgi?id=1371892

The 'capacity' value (e.g. guest logical size) for a LUKS volume is
smaller than the 'physical' value of the file in the file system, so
we need to account for that.

When peeking at the encryption information about the volume add a fetch
of the payload_offset which is described as the offset to the start of
the volume data (in 512 byte sectors) in QEMU's QCryptoBlockLUKSHeader.

Then adjust the ->capacity appropriately when we determine that the
volume target encryption has a payload_offset value.
2017-04-03 16:15:29 -04:00
Cédric Bosdonnat
b202c39adc virNetDevIPCheckIPv6ForwardingCallback fixes
Add check for more than one RTA_OIF, even though this is rather
unlikely.

Get rid of the buggy switch / break as this code won't need to
handle more attributes.

Use VIR_WARNINGS_NO_CAST_ALIGN to fix impossible to fix
util/virnetdevip.c:560:17: error: cast increases required alignment of target type [-Werror=cast-align]
2017-04-03 14:23:15 -04:00
Erik Skultety
6461510386 admin: Throw a system error when 'open' fails on user-provided output
There was an unhandled 'open' call which resulted in:

"error: Library function returned error but did not set virError"

Even if this happens during the daemon's start when we still don't have
any set of outputs defined yet, we can safely report an error, since we
automatically fallback to stderr which is fine even for both
running as a daemonized process, since this happens before the daemon
forks into the background, and running as a systemd service, since
systemd re-directs std outputs to journald by default.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1436060

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-03-31 12:07:07 +02:00
Andrea Bolognani
868d043a09 process: Translate "unlimited" correctly
The value we use internally to represent the lack of a memory
locking limit, VIR_DOMAIN_MEMORY_PARAM_UNLIMITED, doesn't
match the value setrlimit() and prlimit() use for the same
purpose, RLIM_INFINITY, so we have to handle the translation
ourselves.

Partially-resolves: https://bugzilla.redhat.com/1431793
2017-03-28 10:54:49 +02:00
Martin Kletzander
0fc454cec0 Use stub for virNetDevGetName on mingw
If if_indextoname is not defined, the whole function using it should
not be defined either.  Add stub to fix build on mingw.

Caused by 5dd607059d

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 22:26:21 +02:00
Roman Bogorodskiy
8ffffae97f virmdev: fix build on non-Linux
- Make virMediatedDeviceNew() stub args match its prototype
 - Fix typo: virRerportError -> virReportError
 - Move MDEV_SYSFS_DEVICES definition out of the #ifdef __linux__ block
   so we don't have to stub virMediatedDeviceGetSysfsPath()
2017-03-27 21:59:39 +04:00
Roman Bogorodskiy
5efdc1a6e2 netdev: fix build on non-Linux
Fix typo: virNetDevVLanPtr -> virNetDevVlanPtr.
2017-03-27 21:59:20 +04:00
Jiri Denemark
9bca66530b util: Fix build on FreeBSD
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2017-03-27 19:43:31 +02:00
John Ferlan
2902771fa0 util: Remove NONNULL from virHostdevReAttachMediatedDevices
Causes build failure when enabling static analysis
2017-03-27 12:41:24 -04:00
Martin Kletzander
71732f0f54 virhostcpu: Make only defined symbols available
That way you get the error from the compiler before the linker.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 17:34:59 +02:00
Martin Kletzander
9c5ac84d76 virhostcpu: Expose virHostCPUGetOnline on non-Linux
Previously, this function must've been called only on Linux in order
to fail gracefully.  That lead to #ifdef mess in callers, so the
function was redesigned so it failed gracefully on non-existing
files.  However that commit forgot to define the function outside the
__linux__ ifdef, it broke non-Linux builds.

Caused by c67e04e25f.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 17:34:59 +02:00
Laine Stump
43da691582 util: rename virHostdevNetConfigRestore() to virHostdevRestoreNetConfig() 2017-03-27 10:21:35 -04:00
Laine Stump
6ec36b0699 util: log all setting of MAC addresses and vlan tags
Having this information available will make it easier to determine the
culprit when MAC or vlan tag appear to not be set, eg.:

  https://bugzilla.redhat.com/1364073

(This patch doesn't fix that bug, just makes it easier to diagnose)
2017-03-27 10:21:30 -04:00
Laine Stump
86556e167a util: try *really* hard to set the MAC address of an SRIOV VF
If an SRIOV VF has previously been used for VFIO device assignment,
the "admin MAC" that is stored in the PF driver's table of VF info
will have been set to the MAC address that the virtual machine wanted
the device to have. Setting the admin MAC for a VF also sets a flag in
the PF that is loosely called the "administratively set" flag. Once
that flag is set, it is no longer possible for the net driver of the
VF (either on the host or in a virtual machine) to directly set the
VF's MAC again; this flag isn't reset until the *PF* driver is
restarted, and that requires taking *all* VFs offline, so it's not
really feasible to do.

If the same SRIOV VF is later used for macvtap passthrough mode, the
VF's MAC address must be set, but normally we don't unbind the VF from
its host net driver (since we actually need the host net driver in
this case). Since setting the VF MAC directly will fail, in the past
"we" ("I") had tried to fix the problem by simply setting the admin MAC
(via the PF) instead. This *appeared* to work (and might have at one
time, due to promiscuous mode being turned on somewhere or something),
but it currently creates a non-working interface because only the
value for admin MAC is set to the desired value, *not* the actual MAC
that the VF is using.

Earlier patches in this series reverted that behavior, so that we once
again set the MAC of the VF itself for macvtap passthrough operation,
not the admin MAC. But that brings back the original bug - if the
interface has been used for VFIO device assignment, you can no longer
use it for macvtap passthrough.

This patch solves that problem by noticing when virNetDevSetMAC()
fails for a VF, and in that case it sets the desired MAC to the admin
MAC via the PF, then "bounces" the VF driver (by unbinding and the
immediately rebinding it to the VF). This causes the VF's MAC to be
reinitialized from the admin MAC, and everybody is happy (until the
*next* time someone wants to set the VF's MAC address, since the
"administratively set" bit is still turned on).
2017-03-27 10:21:23 -04:00
Laine Stump
d5f4abefc2 util: if setting admin MAC to 00:00:00:00:00:00 fails, try 02:00:00:00:00:00
Some PF drivers allow setting the admin MAC (that is the MAC address
that the VF will be initialized to the next time the VF's driver is
loaded) to 00:00:00:00:00:00, and some don't. Multiple drivers
initialize the admin MACs to all 0, but don't allow setting it to that
very same value. It has been an uphill battle convincing the driver
people that it's reasonable to expect The argument that's used is
that an all 0 device MAC address on a device is invalid; however, from
an outsider's point of view, when the admin MAC is set to 0 at the
time the VF driver is loaded, the VF's MAC is *not* set to 0, but to a
random non-0 value. But that's beside the point - even if I could
convince one or two SRIOV driver maintainers to permit setting the
admin MAC to 0, there are still several other drivers.

So rather than fighting that losing battle, this patch checks for a
failure to set the admin MAC due to an all 0 value, and retries it
with 02:00:00:00:00:00. That won't result in a random value being set
in the VF MAC at next VF driver init, but that's okay, because we
always want to set a specific value anyway. Rather, the "almost 0"
setting makes it easy to visually detect from the output of "ip link
show" which VFs are currently in use and which are free.
2017-03-27 10:21:18 -04:00
Laine Stump
bc4168f3e1 util: remove unused functions from virnetdev.c
The global functions virNetDevReplaceMacAddress(),
virNetDevReplaceNetConfig(), virNetDevRestoreMacAddress(), and
virNetDevRestoreNetConfig() are no longer used, as their functionality
has been replaced by virNetDev(Save|Read|Set)NetConfig().

The static functions virNetDevReplaceVfConfig() and
virNetDevRestoreVfConfig() were only used by the above-named global
functions that were removed.
2017-03-27 10:19:42 -04:00
Laine Stump
d6ef331f11 util: after hostdev assignment, restore VF MAC address via setting admin MAC
It takes longer to explain this than to fix it...

In the past we weren't able to save the VF's own MAC address *at all*
when using it for hostdev assignment, because we had already unbound
the VF from the host net driver prior to saving its config. With the
previous patch, that problem has been solved, so we now have the VF's
MAC address saved and can move on to the *next* problem, which is twofold:

1) during teardown we restore the config before we've re-bound, so the
   VF doesn't have a net driver, and thus we can't set its MAC address
   directly.

2) even if we delay restoring the config until the VF is bound to a
   net driver, the request to set its MAC address would fail, since
   (during device setup) we had set the "admin MAC" for the VF via an
   RTM_SETLINK to the PF - once you've set the admin MAC for a VF, the
   VF driver (either on host or on guest) is not allowed to change the
   VF's MAC address "forever" (well, until you reload the PF driver,
   but that requires destroying and recreating every single VF, which
   isn't something you can require).

The solution is to keep the restoration of config at the same place,
but to set the *admin MAC* to the address you want the VF to have -
when the VF net driver is later initialized (as a part of re-binding
to the VF net driver) its MAC will be initialized to the current value
of the admin MAC.
2017-03-27 10:19:34 -04:00
Laine Stump
cceada574e util: save hostdev network device config before unbinding from host driver
In order to properly restore the original state of an SRIOV VF when
we're finished with it, we need to save the MAC address of the VF
itself (not just the admin MAC address for the VF that is stored in
the PF). But that can only be done when the VF is still bound to the
host's netdev driver, and we have always done the saving of device
config after the VF is already bound to vfio-pci. This patch prepares
us for adding a save of the VF's MAC by calling the function that
saves netconfig earlier in the device preparation, before we've
unbound it from the host netdev driver.
2017-03-27 10:19:24 -04:00
Laine Stump
b684734bef util: replace virHostdevNetConfigReplace with ...(Save|Set)NetConfig()
These two operations will need to be separated so that saving of the
original config is done before detaching the host net driver, and
setting the new config is done after attaching vfio-pci. This patch
splits the single function into two, but for now calls them together
(to make bisecting easier if there is a regression).
2017-03-27 10:19:18 -04:00
Laine Stump
9c004d55d0 util: use new virNetDev*NetConfig() functions for hostdev setup/teardown
virHostdevNetConfigReplace() and virHostdevNetConfigRestore() are
modified to use the new virNetDev*NetConfig() functions.

Note that due to the VF's original MAC addresses being saved after it
has already been un-bound from the host net driver, the actual current
VF MAC address won't be saved (because it no longer exists) - only the
"admin MAC" will be saved. This reflects existing behavior that will
be fixed in an upcoming patch.
2017-03-27 10:19:12 -04:00
Laine Stump
b91a336384 util: use new virNetDev*NetConfig() functions for macvtap setup/teardown
This patch modifies the macvtap passthrough setup to use
virNetDevSaveNetConfig()+virNetDevSetConfig() instead of
virNetDevReplaceNetConfig() or virNetDevReplaceMacAddress(), and the
teardown to use virNetDevReadNetConfig()+virNetDevSetConfig() instead
of virNetDevRestoreNetConfig() or virNetDevRestoreMacAddress().

Since the older functions only saved/restored the admin MAC and vlan
tag (which is incorrect) and the new functions save/restore the VF's
own MAC address and vlan tag (correct), this actually fixes a bug
(which was introduced by commit cb3fe38c7, which was itself supposed
to be a fix for https://bugzilla.redhat.com/1113474 ).

The downside to this patch is that it causes an *apparent* regression
in that bug (because there will once again be an error reported if the
interface had previously been used for VFIO device assignment), but in
reality, the code hasn't been working for *any* case before this
current patch (at least not with any recent kernel). Anyway, that
"regression" will be fixed with an upcoming patch that fixes it the
*right* way.
2017-03-27 10:19:04 -04:00
Laine Stump
26694daf09 util: new functions virNetDev(Save|Read|Set)NetConfig()
These three functions are destined to replace
virNetDev(Replace|Restore)NetConfig() and
virNetDev(Replace|Restore)MacAddress(), which both do the save and set
together as a single step. We need to separate the save, read, and set
steps because there will be situations where we need to do something
else in between (in particular, we will need to rebind a VF's driver
after save but before set).

This patch creates the new functions, but doesn't call them - that
will come in a subsequent patch. Note that the new functions to
read/write the file that stores the original network config now uses
JSON rather than plaintext (it still recognizes the old format as well
though, so it won't get confused during an upgrade).
2017-03-27 10:18:58 -04:00
Erik Skultety
a4a39d90ab hostdev: Maintain a driver list of active mediated devices
Keep track of the assigned mediated devices the same way we do it for
the rest of hostdevs. Methods like 'Prepare', 'Update', and 'ReAttach'
are introduced by this patch.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-03-27 15:39:35 +02:00
Erik Skultety
e1ec4f88ff util: Introduce new module virmdev
Beside creation, disposal, getter, and setter methods the module exports
methods to work with lists of mediated devices.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-03-27 15:39:35 +02:00
Eric Blake
044198476a util: fix build on RHEL 6
We keep forgetting that older setups don't like 'index':

  CC     util/libvirt_util_la-virsysinfo.lo
cc1: warnings being treated as errors
util/virstoragefile.c: In function 'virStorageSourceFindByNodeName':
util/virstoragefile.c:3804: error: declaration of 'index' shadows a global declaration [-Wshadow]
/usr/include/string.h:489: error: shadowed declaration is here [-Wshadow]

Signed-off-by: Eric Blake <eblake@redhat.com>
2017-03-27 08:12:18 -05:00
Martin Kletzander
d2d1dec1f5 util: Fix naming in util/virnodesuspend
That file has only two exported files and each one of them has
different naming.  virNode is what all the other files use, so let's
use it.  It wasn't used before because the clash with public API
naming, so let's fix that by shortening the name (there is no other
private variant of it anyway).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:13:29 +02:00
Martin Kletzander
bdcb199532 Move src/fdstream to src/util/virfdstream
There is no reason for it not to be in the utils, all global symbols
under that file already have prefix vir* and there is no reason for it
to be part of DRIVER_SOURCES because that is just a leftover from
older days (pre-driver modules era, I believe).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:13:29 +02:00
Martin Kletzander
c67e04e25f util: Adapt virhostcpu to the new virsysfs
While on that, drop support for kernels from RHEL-5 era (missing
cpu/present file).  Also add some useful functions and export them.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:13:29 +02:00
Martin Kletzander
a7b902c082 util: Add virsysfs for handling sysfs files
By using this we are able to easily switch the sysfs path being
used (fake it).  This will not only help tests in the future but can
be also used from files where the code is duplicated currently.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:13:29 +02:00
Martin Kletzander
9fdd077de7 virfile: Add helpers for reading simple values
These helpers are doing just a read and covert the value, but they
properly size the read limit, handle additional whitespace characters,
and unify error reporting.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:13:29 +02:00
Martin Kletzander
eec3b255d2 Fix build with GCC's static analysis
STREQ_NULLABLE returns true if both parameters are NULL.  And that's
not what we want here.  We just want to skop comparing source nodes
that don't have that info set.  The function wouldn't make much sense
with nodeName == NULL, so we don't need to check that.  Moreover, the
function's declaration uses ATTRIBUDE_NONNULL for nodeName, which not
only means that function expects the parameter not to be NULL, but
actually tells the compiler that it can optimize out the NULL checks.
That way it could end up calling strcmp on NULL (either nodeformat or
nodebacking).  GCC figures this out if libvirt is compiled with
lv_cv_static_analysis=yes, unfortunately not everyone uses that.

Caused by cbc6d53513.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2017-03-27 13:12:23 +02:00
Peter Krempa
86e51d68f9 util: json: Make function to free JSON values in virHash universal
Move the helper that frees JSON entries put into hash tables into the
JSON module so that it does not have to be reimplemented.
2017-03-27 10:35:19 +02:00
Peter Krempa
cbc6d53513 util: storage: Add variables for node names into virStorageSource
'nodeformat' should be used for strings which describe the storage
format object, and 'nodebacking' for the actual storage object itself.
2017-03-27 09:29:57 +02:00
Peter Krempa
ad36f3853b util: storage: Split out useful bits of virStorageFileParseChainIndex
The function has very specific semantics. Split out the part that parses
the backing store specification string into a separate helper so that it
can be reused later while keeping the wrapper with existing semantics.

Note that virStorageFileParseChainIndex is pretty well covered by the
test suite.
2017-03-27 09:29:57 +02:00
Peter Krempa
91e7862c15 util: buffer: Add API to set indentation level to a given value
It will be useful to set indentation level to 0 after formatting a
nested structure rather than having to track the depth.
2017-03-27 09:29:57 +02:00
Roman Bogorodskiy
27a59a9230 virpci: fix build on non-Linux
virPCIGetDeviceAddressFromSysfsLink() should return
virPCIDeviceAddressPtr, so return NULL in the stub instead of "-1".
2017-03-25 20:48:24 +04:00
Roman Bogorodskiy
a7496ad29a util: fix build on non-Linux
Fix typo in virNetDevPFGetVF() stub:

  ATTRUBUTE_UNUSED -> ATTRIBUTE_UNUSED.

While here, use common indent style for arguments in
virNetDevGetVirtualFunctionIndex() stub.
2017-03-25 08:24:21 +04:00
Laine Stump
554253ad04 util: new function virNetDevPFGetVF()
Given an SRIOV PF netdev name (e.g. "enp2s0f0") and VF#, this new
function returns the netdev name of the referenced VF device
(e.g. "enp2s11f6"), or NULL if the device isn't bound to a net driver.
2017-03-24 00:39:31 -04:00
Laine Stump
f4ef3a71f8 util: new internal function to permit silent failure of virNetDevSetMAC()
We will want to allow silent failure of virNetDevSetMAC() in the case
that the SIOSIFHWADDR ioctl fails with errno == EADDRNOTAVAIL. (Yes,
that is very specific, but we really *do* want a logged failure in all
other circumstances, and don't want to duplicate code in the caller
for the other possibilities).

This patch renames the 3 different virNetDevSetMAC() functions to
virNetDevSetMACInternal(), adding a 3rd arg called "quiet" and making
them static (because this extra control will only be needed within
virnetdev.c). A new global virNetDevSetMAC() is defined that calls
whichever of the three *Internal() functions gets compiled with quiet
= false. Callers in virnetdev.c that want to notice a failure with
errno == EADDRNOTAVAIL and retry with a different strategy rather than
immediately failing, can call virNetDevSetMACInternal(..., true).
2017-03-24 00:39:08 -04:00
Laine Stump
251d179bf2 util: new function virPCIDeviceRebind()
This function unbinds a device from its driver, then immediately
rebinds it to its driver again. The code for this new function is just
the 2nd half of virPCIDeviceBindWithDriverOverride(), so that
function's 2nd half is replaced with a call to virPCIDeviceRebind().
2017-03-24 00:38:21 -04:00
Laine Stump
9a238c16b3 util: make virPCIGetDeviceAddressFromSysfsLink() public
This function will be useful in virnetdev.c, so promote it from static.
2017-03-24 00:37:36 -04:00
Laine Stump
d6ee56d723 util: change virPCIGetNetName() to not return error if device has no net name
...and cleanup the callers to report it when it *is* an error.

In many cases It's useful for virPCIGetNetName() to not log an error
and simply return a NULL pointer when the given device isn't bound to
a net driver (e.g. we're looking at a VF that is permanently bound to
vfio-pci). The existing code would silently return an error in this
case, which could eventually lead to the dreaded "An error occurred
but the cause is unknown" log message.

This patch changes virPCIGetNetName() to still return success if the
device simply isn't bound to a net driver, and adjusts all the callers
that require a non-null netname to check for that condition and log an
error when it happens.
2017-03-24 00:37:19 -04:00
Laine Stump
30b07a425d util: make virMacAddrParse more versatile
Previously the MAC address text was required to be terminated with a
NULL. After this, it can be terminated with a space or any control
character.
2017-03-24 00:37:01 -04:00
Laine Stump
606a013395 util: eliminate useless local variable
vf in virNetDevMacVLanDeleteWithVPortProfile() is initialized to -1
and never set. It's not set for a good reason - because it doesn't
make sense during macvtap device setup to refer to a VF device as
"PF:VF#". This patch replaces the two uses of "vf" with "-1", and
removes the local variable, so that it's more clear we are always
calling the utility functions with vf set to -1.
2017-03-24 00:36:43 -04:00
Laine Stump
19c5db749c util: use cleanup label consistently in virHostdevNetConfigReplace()
This will make an upcoming functional change more straightforward.
2017-03-24 00:36:22 -04:00
Laine Stump
0a583c26f7 util: remove unused args from virNetDevSetVfConfig()
This function is only called in two places, and the ifindex,
nltarget_kernel, and getPidFunc args are never used (and never will
be).

ifindex - we always know the name of the device, and never know the
ifindex - if we really did need the ifindex we would have to get it
from the name using virNetDevGetIndex(). In practice, we just send -1
to virNetDevSetVfConfig(), which doesn't bother to learn the real
ifindex (you only need a name *or* an ifindex for the netlink command
to succeed, not both).

nltarget_kernel - messages to set the config of an SRIOV VF will
always go to netlink in the kernel, not to another user process, so
this arg is always true (there are other uses of netlink messages
where the message might need to go to another user process, but never
in the case of RTM_SETLINK for SRIOV).

getPidFunc - this arg is only used if nltarget_kernel is false, and it
never is.

None of this has any functional effect, it just makes it easier to
follow what's happening when virNetDevSetVfConfig() is called.
2017-03-24 00:35:43 -04:00
Laine Stump
176229dd05 util: permit querying a VF MAC address or VLAN tag by itself
virNetDevParseVfConfig() assumed that both the MAC address and VLAN
tag pointers were valid, so even if you only wanted one or the other,
you would need a variable to hold the returned value for both. This
patch checks each for a NULL pointer before filling it in.
2017-03-24 00:34:08 -04:00
Roman Bogorodskiy
8095828480 util: fix build on non-Linux
Decorate unused arguments of the virNetDevGetMaster() stub
with ATTRIBUTE_UNUSED to fix build on systems where this
stub is used.
2017-03-23 07:45:29 +04:00
John Ferlan
73f5256b4c util: Remove NONNULL(1) for virNetDevMacVLanDeleteWithVPortProfile
Since the source code checks 'ifname' for NULL before using, the prototype
doesn't need the NONNULL
2017-03-22 13:50:00 -04:00
John Ferlan
5482db8176 util: Remove NONNULL's for virNetDevVPortProfile[Associate|Disassociate]
The source code will check for NULL arguments for 'macvtap_macaddr' and
'vmuuid', so no need for the NONNULL in the prototypes. Following the stack
for both arguments to virNetDevVPortProfileOpSetLink also shows called
functions would handle a NULL value.

Additionally, modified the prototype to use the same 'macvtap_macaddr'
name as the source code for consistency.
2017-03-22 13:50:00 -04:00
John Ferlan
fbd804ff3d util: Remove NONNULL(1) for virNetDevOpenvswitchGetVhostuserIfname
Since the code checks and handles a NULL 'path', no need for the NONNULL
2017-03-22 13:50:00 -04:00
John Ferlan
cb91d5cc58 util: Remove NONNULL(2) for virNetDevBandwidthPlug
Since the code checks and handles a NULL 'net_bandwidth' parameter,
so no need for NONNNULL.
2017-03-22 13:50:00 -04:00
John Ferlan
dc2d9431a0 util: Remove NONNULL(1,3,4) from virTypedParamsFilter
The API checks each parameter for NULL anyway and would error, so need
to add NONNULL on prototype.
2017-03-22 13:50:00 -04:00
John Ferlan
3ae0e7853e util: Remove NONNULL(1) for virNetDevOpenvswitchSetMigrateData
The code checks and handles a NULL 'migrate', so no need for NONNULL
2017-03-22 13:50:00 -04:00
John Ferlan
cd0ed1456d util: Remove NONNULL(1) for virHostdevReAttachDomainDevices
Since the function handles a NULL 'mgr' condition, no need for the NONNULL
2017-03-22 13:50:00 -04:00
John Ferlan
40f2a476d1 util: Remove NONNULL(1) for virHostdevPrepareDomainDevices
Since the code checks 'mgr == NULL' anyway, no need for the prototype
to have the NONNULL arg check.  Also add an error message to indicate what
the failure is so that there isn't a failed for some reason error.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-22 13:50:00 -04:00
John Ferlan
47dcce2f08 util: Remove NONNULL(2,3) for virHostdevReAttachSCSIVHostDevices
The comparison code used STREQ_NULLABLE anyway for both 'drv_name' and
'dom_name', so no need. Add a NULLSTR on the 'dom_name' too.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-22 13:50:00 -04:00
John Ferlan
ceaf327475 util: Remove NONNULL(2,3) for virHostdevReAttachUSBDevices
The comparison code used STREQ_NULLABLE anyway for both 'drv_name' and
'dom_name', so no need. Add a NULLSTR on the 'dom_name' too.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-22 13:49:59 -04:00
John Ferlan
17a448da1d util: Remove NONNULL(2,3) for virHostdevReAttachPCIDevices
The called function uses a STRNEQ_NULLABLE anyway for both 'drv_name' and
'dom_name', so no need.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-22 13:49:59 -04:00
John Ferlan
fecc6ed090 util: Remove NONNULL(1) for virBitmapParseUnlimited
The code checks and handles a NULL 'str', so just remove the NONNULL.

Update the error message to add the NULLSTR() around 'str' also.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-22 13:49:59 -04:00
John Ferlan
9f66e09bc5 util: Change return argument for virBitmapParseUnlimited
Rather than returning an int and a *bitmap pointer, just return and
check a NULL bitmap pointer
2017-03-22 13:49:59 -04:00
John Ferlan
91d28d993f util: Remove NONNULL(1) for virNetDevGetName
The 'ifindex' argument is not a pointer, so no need for NONNULL in prototype
2017-03-22 13:49:59 -04:00
Laine Stump
a454134951 util: new function virNetDevTapAttachBridge()
This patch splits out the part of virNetDevTapCreateInBridgePort()
that would need to be re-done if an existing tap device had to be
re-attached to a bridge, and puts it into a separate function. This
can be used both when an existing domain interface config is updated
to change its connection, and also to re-attach to the "same" bridge
when a network has been stopped and restarted. So far it is used for
nothing.
2017-03-22 12:16:51 -04:00
Laine Stump
e75f5bfbe8 util: new function virNetDevGetMaster()
This function provides the bridge/bond device that the given network
device is attached to. The return value is 0 or -1, and the master
device is a char** argument to the function - this is needed in order
to allow for a "success" return from a device that has no master.
2017-03-22 12:12:52 -04:00
Laine Stump
549fe5a882 util: allow retrieving ethtool features when unprivileged
The only reason that the ethtool features weren't being retrieved in
an unprivileged libvirtd was because they required ioctl(), and the
ioctl was using an AF_PACKET socket, which requires root. Now that we
are using AF_UNIX for ioctl(), this restriction can be removed.
2017-03-22 12:10:09 -04:00
Laine Stump
1c9a8746ef util: use AF_UNIX family (not AF_PACKET) for ioctl sockets
The exact family of the socket created for the fd used by ioctl(7)
doesn't matter, it just needs to be a socket and not a file. But for
some reason when macvtap support was added, it used
AF_PACKET/SOCK_DGRAM sockets for its ioctls; we later used the same
AF_PACKET/SOCK_DGRAM socket for new ioctls we added, and eventually
modified the other pre-existing ioctl sockets (for creating/deleting
bridges) to also use AF_PACKET/SOCK_DGRAM (that code originally used
AF_UNIX/SOCK_STREAM).

The problem with using AF_PACKET (intended for sending/receiving "raw"
packets, i.e. packets that can be some protocol other than TCP or UDP)
is that it requires root privileges. This meant that none of the
ioctls in virnetdev.c or virnetdevip.c would work when running
libvirtd unprivileged.

This packet solves that problem by changing the family to AF_UNIX when
creating the socket used for any ioctl().
2017-03-22 12:07:13 -04:00
Cédric Bosdonnat
00d28a78b5 network: check accept_ra before enabling ipv6 forwarding
When enabling IPv6 on all interfaces, we may get the host Router
Advertisement routes discarded. To avoid this, the user needs to set
accept_ra to 2 for the interfaces with such routes.

See https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt
on this topic.

To avoid user mistakenly losing routes on their hosts, check
accept_ra values before enabling IPv6 forwarding. If a RA route is
detected, but neither the corresponding device nor global accept_ra
is set to 2, the network will fail to start.
2017-03-22 09:01:33 +01:00
Cédric Bosdonnat
5dd607059d util: add virNetDevGetName() function
Add a function getting the name of a network interface out of its index.
2017-03-22 09:01:33 +01:00
Cédric Bosdonnat
754515b7db util: add virNetlinkDumpCommand()
virNetlinkCommand() processes only one response message, while some
netlink commands, like route dumping, need to process several.
Add virNetlinkDumpCommand() as a virNetlinkCommand() sister.
2017-03-22 09:01:32 +01:00
Cédric Bosdonnat
d68cb4f554 util: extract the request sending code from virNetlinkCommand()
Allow to reuse as much as possible from virNetlinkCommand(). This
comment prepares for the introduction of virNetlinkDumpCommand()
only differing by how it handles the responses.
2017-03-22 09:01:32 +01:00
Michal Privoznik
67dcb797ed virTimeBackOffWait: Avoid long periods of sleep
While connecting to qemu monitor, the first thing we do is wait
for it to show up. However, we are doing it with some timeout to
avoid indefinite waits (e.g. when qemu doesn't create the monitor
socket at all). After beaa447a29 we are using exponential back
off timeout meaning, after the first connection attempt we wait
1ms, then 2ms, then 4 and so on.  This allows us to bring down
wait time for small domains where qemu initializes quickly.
However, on the other end of this scale are some domains with
huge amounts of guest memory. Now imagine that we've gotten up to
wait time of 15 seconds. The next one is going to be 30 seconds,
and the one after that whole minute. Well, okay - with current
code we are not going to wait longer than 30 seconds in total,
but this is going to change in the next commit.

The exponential back off is usable only for first few iterations.
Then it needs to be caped (one second was chosen as the limit)
and switch to constant wait time.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-03-16 09:21:39 +01:00
John Ferlan
97e0d3c3c9 util: Rename virFileWaitForDevices
The function is actually in virutil.c, but prototyped in virfile.h.
This patch fixes that by renaming the function to virWaitForDevices,
adding the prototype in virutil.h and libvirt_private.syms, and then
changing the callers to use the new name.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-15 21:17:47 -04:00
Nitesh Konkar
0265bbeee3 perf: add emulation_faults software perf event support
This patch adds support and documentation
for the emulation_faults perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:05 -05:00
Nitesh Konkar
6780791f18 perf: add alignment_faults software perf event support
This patch adds support and documentation
for the alignment_faults perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:05 -05:00
Nitesh Konkar
43a54cedf6 perf: add page_faults_maj software perf event support
This patch adds support and documentation
for the page_faults_maj perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:05 -05:00
Nitesh Konkar
d216e9ad77 perf: add page_faults_min software perf event support
This patch adds support and documentation
for the page_faults_min perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
Nitesh Konkar
8110c6a567 perf: add cpu_migrations software perf event support
This patch adds support and documentation
for the cpu_migrations perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
Nitesh Konkar
99cc3dc6a2 perf: add context_switches software perf event support
This patch adds support and documentation
for the context_switches perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
Nitesh Konkar
6ef2c7e00f perf: add page_faults software perf event support
This patch adds support and documentation
for the page_faults perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
Nitesh Konkar
20dc690865 perf: add task_clock software perf event support
This patch adds support and documentation for
the task_clock perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
Nitesh Konkar
f372a862ac perf: add cpu_clock software perf event support
This patch adds support and documentation for
the cpu_clock perf event.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-03-07 13:51:04 -05:00
John Ferlan
15b881474b util: Avoid possible NULL dereference in virSysinfoParsePPCProcessor
Found by Coverity. Because there's an "if ((cur = strstr(base, "revision"))
 != NULL) {" followed by a "base = cur" coverity notes that 'base' could
then be NULL causing the return to the top of the "while ((tmp_base =
strstr(base, "processor")) != NULL) {" to have strstr deref a NULL 'base'
pointer because the setting of base at the bottom of the loop is unconditional.

Alter the code to set "base = cur" after processing each key. That will
"ensure" that base doesn't get set to NULL if both "cpu" and "revision"
do no follow a "processor".

While a /proc/cpuinfo file that has a "processor" key but with neither
a "cpu" nor a "revision" doesn't seem feasible, the code is written as if
it could happen, so we have to account for it.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-07 13:25:03 -05:00
John Ferlan
7744d99415 util: Resource some resource leaks in virsysinfo code
Calls to virFileReadAll after a VIR_ALLOC that return NULL all show
a memory leak since 'ret' isn't virSysinfoDefFree'd and normal path
"return ret" doesn't free outbuf.

Reported by Coverity

Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-03-07 13:25:03 -05:00
Peter Krempa
c58d95b7a0 tests: sysinfo: Export virSysinfoSetup via the private header
virSysinfoSetup should be used only in tests so it can be moved to the
new header file rather than using an extern declaration.
2017-03-07 10:44:26 +01:00
Peter Krempa
b38c6b6ad3 util: sysinfo: Reduce amount of conditionally compiled code
Whole implementations along with helper totalling screens of code were
conditionally compiled. That made the code totally unreadable and
untestable. Rename functions to have the architecture in the name so
that all can be compiled at the same time and introduce header to allow
testing them all.
2017-03-07 10:44:26 +01:00
Laine Stump
3898526931 make all struct typedefs comply with proposed coding conventions
Proposed formal coding conventions encourage defining typedefs for
vir[Blah] and vir[Blah]Ptr separately from the associated struct named
_vir[Blah]:

    typedef struct _virBlah virBlah;
    typedef virBlah *virBlahPtr;
    struct _virBlah {
    ...
    };

At some point in the past, I had submitted several patches using a
more compact style that I prefer, and they were accepted:

    typedef struct _virBlah {
        ...
    } virBlah, *virBlahPtr;

Since these are by far a minority among all struct definitions, this
patch changes all those definitions to reflect the style prefered by
the proposal so that there is 100% consistency.
2017-03-06 13:00:45 -05:00
Ján Tomko
f10bd740e1 Cache the presence of machine1 service
After the system has been booted, it should not change.

Cache the return value of virSystemdHasMachined.
Allow starting and terminating machines with just one
DBus call, instead of three, reducing the chance of
the call timing out.

Also introduce a small function for resetting the cache
to be used in tests.
2017-03-06 15:44:33 +01:00
Ján Tomko
18c145a0d3 Unify checking for machine1 systemd service
Both virSystemdTerminateMachine and virSystemdCreateMachine
propagate the error to tell between a non-systemd system
and a hard error.

In virSystemdGetMachineNameByPID both are treated the same,
but an error is ignored by the callers.

Split out the checks into a separate function.
2017-03-06 15:34:33 +01:00
Erik Skultety
38a8489c01 virfile: Fix virFileExists commentary
Arguably though, function returning only on success is a very
interesting, although quite impractical concept. Also, the errno isn't
and shouldn't be preserved in this case, since the errno can be directly
fed to the virReportSystemError.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-02-24 14:46:50 +01:00
Pavel Hrdina
22b02f4492 util: virqemu: introduce virQEMUBuildBufferEscape
This will eventually replace virQEMUBuildBufferEscapeComma, however
it's not possible right now.  Some parts of the code that uses the
old function needs to be refactored.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2017-02-24 12:58:48 +01:00
Pavel Hrdina
726403461b util: virbuffer: introduce virBufferEscapeN
Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2017-02-24 12:58:23 +01:00
Daniel P. Berrange
09db97d3cb Use explicit boolean comparison in OOM check
GCC 7 gets upset by

   if (!tmp && (size * count))

warning

  util/viralloc.c: In function 'virReallocN':
  util/viralloc.c:246:23: error: '*' in boolean context, suggest '&&' instead [-Werror=int-in-bool-context]
     if (!tmp && (size * count)) {
                 ~~~~~~^~~~~~~~

Keep it happy by adding != 0 to the right hand expression
so it realizes we really are wanting to treat the result
of the arithmetic expression as a boolean

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2017-02-23 10:11:16 +00:00
Tomáš Golembiovský
e4c6d4ae55 util: storage: add JSON backing volume parser 'raw' block driver
The 'raw' block driver in Qemu is not directly interesting from
libvirt's perspective, but it can be layered above some other block
drivers and this may be interesting for the user.

The patch adds support for the 'raw' block driver. The driver is treated
simply as a pass-through and child driver in JSON is queried to get the
necessary information.

Signed-off-by: Tomáš Golembiovský <tgolembi@redhat.com>
2017-02-22 10:39:57 +01:00
Tomáš Golembiovský
cb4adb43d6 util: storage: split function for JSON backing volume parsing in two
Split virStorageSourceParseBackingJSON into two functions so that the
core can be reused by other functions. The new function called
virStorageSourceParseBackingJSONInternal accepts virJSONValuePtr.

Signed-off-by: Tomáš Golembiovský <tgolembi@redhat.com>
2017-02-22 10:39:39 +01:00
Peter Krempa
b4c7310633 Disallow inclusion of files from src/conf into src/utils
The utils code should stay separated from other code (except for very
well justified cases). Unfortunately commit 272769becc
made it trivial to break the separation (and not get slapped by the
syntax-check rule) by adding -I src/conf to the CFLAGS for utils.

Remove this shortcut and except the two offenders from the syntax check
so that the codebase can be kept separated.
2017-02-20 15:12:07 +01:00
Pavel Hrdina
165c76acd0 util: virvhba: fix typo that breaks build on non-linux systems
Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2017-02-19 15:47:27 +01:00
John Ferlan
03346def06 util: Move scsi_host specific functions from virutil
Create a virscsihost.c and place the functions there. That removes the
last #ifdef __linux__ from virutil.c.

Take the opporunity to also change the function names and in one case
the parameters slightly
2017-02-19 06:45:09 -05:00
John Ferlan
16416816c1 util: Create a new virvhba module and move/rename API's
Rather than have them mixed in with the virutil apis, create a separate
virvhba.c module and move the vHBA related calls into there. Soon there
will be more added.

Also modify the names of the functions and some arguments to be more
indicative of what is really happening. Adjust the callers respectively.

While I was changing fchosttest, rather than the non-descriptive names
test1...test6, rename them to match what the test is doing.
2017-02-19 06:45:09 -05:00
Michal Privoznik
1d9ab0f04a qemu: Allow empty script path to <interface/>
Before 9c17d665fd (v1.3.2 - I know, right?) it was possible to
have the following interface configuration:

  <interface type='ethernet'/>
    <script path=''/>
  </interface>

This resulted in -netdev tap,script=,.. Fortunately, qemu helped
us to get away with this as it just ignored the empty script
path. However, after the commit mentioned above it's libvirtd
who is executing the script. Unfortunately without special
case-ing empty script path.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-02-16 17:39:34 +01:00
Nitesh Konkar
5729746543 Ensure disk names follow the disk name regex
Currently disk names do not follow the
(regex) /^[fhv]d[a-z]+[0-9]*$/ completely
and hence one can assign disk names like
vd2 etc. This patch ensures that the
disk names follow the regex mentioned.
This patch also adds a testcase.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-02-16 09:59:13 +01:00
Ján Tomko
4a41cf18b1 util: fix off-by-one when expanding a bitmap
To make sure bit 'b' fits into the bitmap, we need to allocate b+1
bits, since we number from 0.

Adjust the bitmap test to set a bit at a multiple of 16.
That way the test fails without this fix, because the VIR_REALLOC
call clears the newly added memory even if the original pointer
has not changed.
2017-02-14 13:30:48 +01:00
Nitesh Konkar
ef41eda68a util: Fix indentation for virnetdevmacvlan
Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-02-10 14:13:50 -05:00
Erik Skultety
875894245a util: Introduce virFileComparePaths
So rather than comparing 2 paths (strings) as they are, which can very
easily lead to unnecessary errors (e.g. in storage driver) that the paths
are not the same when in fact they'd be e.g. just symlinks to the same
location, we should put our best effort into resolving any symlinks and
canonicalizing the path and only then compare the 2 paths for equality.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2017-02-10 17:01:12 +01:00
Nitesh Konkar
f278a148e2 Mention the min duration for nodesuspend explicitly
Although currently this is documented in virsh man page
and virsh help, the expicit mention in the error message
is helful for tools using the API directly.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-02-10 09:13:30 -05:00
Marc Hartmayer
c26fe44be5 util: reset the counters to zero
After freeing the data structures we have to reset the counters to
zero. This fixes a segmentation fault when virNetDevIPInfoClear is
called twice (e.g. this is possible in virDomainNetDefParseXML() if
virDomainNetIPInfoParseXML(...) fails with ret < 0 (this leads to the
first call of 'virNetDevIPInfoClear(&def->guestIP)') and the resulting
call of virDomainNetDefFree(def) in the error path of
virDomainNetDefParseXML() (this leads to the second call of
virNetDevIPInfoClear(&def->guestIP), and finally to the segmentation
fault).

Signed-off-by: Marc Hartmayer <mhartmay@linux.vnet.ibm.com>
Reviewed-by: Boris Fiuczynski <fiuczy@linux.vnet.ibm.com>
Reviewed-by: Bjoern Walk <bwalk@linux.vnet.ibm.com>
2017-02-09 14:20:42 -05:00
Boris Fiuczynski
f4d06ca8fd network: allow to specify timeout for openvswitch calls
This patchs allows to set the timeout value used for all
openvswitch calls. The default timeout value remains as
before at 5 seconds.

Signed-off-by: Boris Fiuczynski <fiuczy@linux.vnet.ibm.com>
Reviewed-by: Bjoern Walk <bwalk@linux.vnet.ibm.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-02-09 14:34:08 +01:00
Boris Fiuczynski
66583c0cf7 libvirtd: add openvitch timeout value
Provide the ability to specify a default timeout value for
successful completion of openvswitch calls in the libvirtd
configuration file.

Signed-off-by: Boris Fiuczynski <fiuczy@linux.vnet.ibm.com>
Reviewed-by: Bjoern Walk <bwalk@linux.vnet.ibm.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-02-09 14:34:08 +01:00
Laine Stump
dd8ac030fb util: add MTU arg to virNetDevTapCreateInBridgePort()
virNetDevTapCreateInBridgePort() has always set the new tap device to
the current MTU of the bridge it's being attached to. There is one
case where we will want to set the new tap device to a different
(usually larger) MTU - if that's done with the very first device added
to the bridge, the bridge's MTU will be set to the device's MTU. This
patch allows for that possibility by adding "int mtu" to the arg list
for virNetDevTapCreateInBridgePort(), but all callers are sending -1,
so it doesn't yet have any effect.

Since the requested MTU isn't necessarily what is used in the end (for
example, if there is no MTU requested, the tap device will be set to
the current MTU of the bridge), and the hypervisor may want to know
the actual MTU used, we also return the actual MTU to the caller (if
actualMTU is non-NULL).
2017-02-07 13:45:08 -05:00
Michal Privoznik
6094169b83 util: Introduce virFileReadLink
We will need to traverse the symlinks one step at the time.
Therefore we need to see where a symlink is pointing to.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-02-07 10:40:53 +01:00
Michal Privoznik
3172d26730 virProcessRunInMountNamespace: Report errors from child
The comment to the function states that the errors from the child
process are reported. Well, the error buffer is filled with
possible error messages. But then it is thrown away. Among with
important error message from the child process.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2017-02-07 10:40:53 +01:00
John Ferlan
48ad600916 util: Fix domain object leaks on closecallbacks
Originally/discovered proposed by "Wang King <king.wang@huawei.com>"

When the virCloseCallbacksSet is first called, it increments the refcnt
on the domain object to ensure it doesn't get deleted before the callback
is called. The refcnt would be decremented in virCloseCallbacksUnset once
the entry is removed from the closeCallbacks has table.

When (mostly) normal shutdown occurs, the qemuProcessStop will end up
calling qemuProcessAutoDestroyRemove and will remove the callback from
the list and hash table normally and decrement the refcnt.

However, when qemuConnectClose calls virCloseCallbacksRun, it will scan
the (locked) closeCallbacks list for matching domain and callback function.
If an entry is found, it will be removed from the closeCallbacks list and
placed into a lookaside list to be processed when the closeCallbacks lock
is dropped. The callback function (e.g. qemuProcessAutoDestroy) is called
and will run qemuProcessStop. That code will fail to find the callback
in the list when qemuProcessAutoDestroyRemove is called and thus not decrement
the domain refcnt. Instead since the entry isn't found the code will just
return (mostly) harmlessly.

This patch will resolve the issue by taking another ref during the
search UUID process during virCloseCallackRun, decrementing the refcnt
taken by virCloseCallbacksSet, calling the callback routine and returning
overwriting the vm (since it could return NULL). Finally, it will call the
virDomainObjEndAPI to lower the refcnt and remove the lock taken during
the search UUID processing. This may cause the vm to be destroyed.
2017-02-03 19:38:39 -05:00
Nitesh Konkar
26ac16f3ce perf: Prevent enabling of already enabled perf event
Currently, on every --enable perf_event command,
a new event->fd is created and counting of perf
event counter starts from zero and previous
event->fd is lost. This patch prevents this
behaviour.

Signed-off-by: Nitesh Konkar <nitkon12@linux.vnet.ibm.com>
2017-01-26 15:13:58 -05:00
Chen Hanxiao
f97a8a3284 THREADS.txt: fix typos
s/wakup/wakeup

Signed-off-by: Chen Hanxiao <chenhanxiao@gmail.com>
2017-01-25 09:18:49 +01:00
Shivaprasad G Bhat
bd12889616 util: Forbid resetting non-endpoint devices
It is destructive to attempt reset on a pci- or cardbus-bridge, the
host can crash.  The bridges won't contain any guest data and neither
they can be passed through using vfio/stub.  So, no point in allowing a
reset on them.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
2017-01-23 17:23:12 +01:00
Shivaprasad G Bhat
bec9b9b01a util: Forbid assigning a pci-bridge to a guest
Non-endpoint devices like pci-bridges cannot be assigned to guests.
Prevent such attempts.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
2017-01-23 17:23:03 +01:00
John Ferlan
5f580d82f3 util: Fix typo in previous commit
Should be Unlock not Lock... Bad fingers.
2017-01-21 12:46:09 -05:00
Wang King
a563451e2b util: unlock closeCallbacks if get callbacks for connect fail
Avoid return with the closeCallbacks locked when get callbacks list for connect fail.

Signed-off-by: Wang King <king.wang@huawei.com>
Signed-off-by: John Ferlan <jferlan@redhat.com>
2017-01-21 12:39:52 -05:00