xen_hypervisor.c 99.5 KB
Newer Older
1
/*
2
 * xen_hypervisor.c: direct access to Xen hypervisor level
3
 *
4
 * Copyright (C) 2005-2014 Red Hat, Inc.
5
 *
O
Osier Yang 已提交
6 7 8 9 10 11 12 13 14 15 16
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22
 *
 * Daniel Veillard <veillard@redhat.com>
 */

23
#include <config.h>
24

25 26
#include <stdio.h>
#include <string.h>
27
/* required for uint8_t, uint32_t, etc ... */
28 29 30 31 32 33 34
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
35
#include <limits.h>
36 37
#include <regex.h>
#include <errno.h>
38

J
John Levon 已提交
39
#ifdef __sun
40
# include <sys/systeminfo.h>
J
John Levon 已提交
41

42
# include <priv.h>
J
John Levon 已提交
43

44 45 46
# ifndef PRIV_XVM_CONTROL
#  define PRIV_XVM_CONTROL ((const char *)"xvm_control")
# endif
J
John Levon 已提交
47 48 49

#endif /* __sun */

50
/* required for dom0_getdomaininfo_t */
51
#include <xen/dom0_ops.h>
52
#include <xen/version.h>
53
#ifdef HAVE_XEN_LINUX_PRIVCMD_H
54
# include <xen/linux/privcmd.h>
55
#else
56 57 58
# ifdef HAVE_XEN_SYS_PRIVCMD_H
#  include <xen/sys/privcmd.h>
# endif
59
#endif
60

61 62 63
/* required for shutdown flags */
#include <xen/sched.h>

64
#include "virerror.h"
65
#include "virlog.h"
66
#include "datatypes.h"
67
#include "driver.h"
68 69
#include "xen_driver.h"
#include "xen_hypervisor.h"
70
#include "xs_internal.h"
71
#include "virstatslinux.h"
72
#include "block_stats.h"
73
#include "xend_internal.h"
74
#include "virbuffer.h"
75
#include "capabilities.h"
76
#include "viralloc.h"
77
#include "virthread.h"
E
Eric Blake 已提交
78
#include "virfile.h"
79
#include "virnodesuspend.h"
80
#include "virtypedparam.h"
E
Eric Blake 已提交
81
#include "virendian.h"
82
#include "virstring.h"
83

84 85
#define VIR_FROM_THIS VIR_FROM_XEN

86 87
VIR_LOG_INIT("xen.xen_hypervisor");

88
/*
89
 * so far there is 2 versions of the structures usable for doing
90 91 92 93
 * hypervisor calls.
 */
/* the old one */
typedef struct v0_hypercall_struct {
94 95
    unsigned long op;
    unsigned long arg[5];
96
} v0_hypercall_t;
97 98

#ifdef __linux__
99
# define XEN_V0_IOCTL_HYPERCALL_CMD \
100 101 102 103 104 105 106
        _IOC(_IOC_NONE, 'P', 0, sizeof(v0_hypercall_t))
/* the new one */
typedef struct v1_hypercall_struct
{
    uint64_t op;
    uint64_t arg[5];
} v1_hypercall_t;
107
# define XEN_V1_IOCTL_HYPERCALL_CMD                  \
108
    _IOC(_IOC_NONE, 'P', 0, sizeof(v1_hypercall_t))
109
typedef v1_hypercall_t hypercall_t;
110
#elif defined(__sun)
111 112
typedef privcmd_hypercall_t hypercall_t;
#else
113
# error "unsupported platform"
114
#endif
115 116

#ifndef __HYPERVISOR_sysctl
117
# define __HYPERVISOR_sysctl 35
118 119
#endif
#ifndef __HYPERVISOR_domctl
120
# define __HYPERVISOR_domctl 36
121
#endif
122

123
#ifdef WITH_RHEL5_API
124
# define SYS_IFACE_MIN_VERS_NUMA 3
125
#else
126
# define SYS_IFACE_MIN_VERS_NUMA 4
127 128
#endif

129
static int xen_ioctl_hypercall_cmd = 0;
P
Philipp Hahn 已提交
130 131 132 133 134 135 136
static struct xenHypervisorVersions hv_versions = {
    .hv = 0,
    .hypervisor = 2,
    .sys_interface = -1,
    .dom_interface = -1,
};

137
static int kb_per_pages = 0;
138

139 140 141 142 143 144 145 146
/* Regular expressions used by xenHypervisorGetCapabilities, and
 * compiled once by xenHypervisorInit.  Note that these are POSIX.2
 * extended regular expressions (regex(7)).
 */
static const char *flags_hvm_re = "^flags[[:blank:]]+:.* (vmx|svm)[[:space:]]";
static regex_t flags_hvm_rec;
static const char *flags_pae_re = "^flags[[:blank:]]+:.* pae[[:space:]]";
static regex_t flags_pae_rec;
147
static const char *xen_cap_re = "(xen|hvm)-[[:digit:]]+\\.[[:digit:]]+-(x86_32|x86_64|ia64|powerpc64)(p|be)?";
148 149
static regex_t xen_cap_rec;

150 151 152 153
/*
 * The content of the structures for a getdomaininfolist system hypercall
 */
#ifndef DOMFLAGS_DYING
154 155 156 157 158 159 160 161 162 163
# define DOMFLAGS_DYING     (1<<0) /* Domain is scheduled to die.             */
# define DOMFLAGS_HVM       (1<<1) /* Domain is HVM                           */
# define DOMFLAGS_SHUTDOWN  (1<<2) /* The guest OS has shut down.             */
# define DOMFLAGS_PAUSED    (1<<3) /* Currently paused by control software.   */
# define DOMFLAGS_BLOCKED   (1<<4) /* Currently blocked pending an event.     */
# define DOMFLAGS_RUNNING   (1<<5) /* Domain is currently running.            */
# define DOMFLAGS_CPUMASK      255 /* CPU to which this domain is bound.      */
# define DOMFLAGS_CPUSHIFT       8
# define DOMFLAGS_SHUTDOWNMASK 255 /* DOMFLAGS_SHUTDOWN guest-supplied code.  */
# define DOMFLAGS_SHUTDOWNSHIFT 16
164 165
#endif

166 167 168 169 170
/*
 * These flags explain why a system is in the state of "shutdown".  Normally,
 * They are defined in xen/sched.h
 */
#ifndef SHUTDOWN_poweroff
171 172 173 174
# define SHUTDOWN_poweroff   0  /* Domain exited normally. Clean up and kill. */
# define SHUTDOWN_reboot     1  /* Clean up, kill, and then restart.          */
# define SHUTDOWN_suspend    2  /* Clean up, save suspend info, kill.         */
# define SHUTDOWN_crash      3  /* Tell controller we've crashed.             */
175 176
#endif

177 178 179 180 181 182
#define XEN_V0_OP_GETDOMAININFOLIST	38
#define XEN_V1_OP_GETDOMAININFOLIST	38
#define XEN_V2_OP_GETDOMAININFOLIST	6

struct xen_v0_getdomaininfo {
    domid_t  domain;	/* the domain number */
R
Richard W.M. Jones 已提交
183
    uint32_t flags;	/* flags, see before */
184 185
    uint64_t tot_pages;	/* total number of pages used */
    uint64_t max_pages;	/* maximum number of pages allowed */
186
    unsigned long shared_info_frame; /* MFN of shared_info struct */
187 188 189 190 191 192 193 194
    uint64_t cpu_time;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
};
typedef struct xen_v0_getdomaininfo xen_v0_getdomaininfo;

195 196
struct xen_v2_getdomaininfo {
    domid_t  domain;	/* the domain number */
R
Richard W.M. Jones 已提交
197
    uint32_t flags;	/* flags, see before */
198 199 200 201 202 203 204 205 206 207 208
    uint64_t tot_pages;	/* total number of pages used */
    uint64_t max_pages;	/* maximum number of pages allowed */
    uint64_t shared_info_frame; /* MFN of shared_info struct */
    uint64_t cpu_time;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
};
typedef struct xen_v2_getdomaininfo xen_v2_getdomaininfo;

209 210 211 212 213 214 215

/* As of Hypervisor Call v2,  DomCtl v5 we are now 8-byte aligned
   even on 32-bit archs when dealing with uint64_t */
#define ALIGN_64 __attribute__((aligned(8)))

struct xen_v2d5_getdomaininfo {
    domid_t  domain;	/* the domain number */
R
Richard W.M. Jones 已提交
216
    uint32_t flags;	/* flags, see before */
217 218 219 220 221 222 223 224 225 226 227
    uint64_t tot_pages ALIGN_64;	/* total number of pages used */
    uint64_t max_pages ALIGN_64;	/* maximum number of pages allowed */
    uint64_t shared_info_frame ALIGN_64; /* MFN of shared_info struct */
    uint64_t cpu_time ALIGN_64;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
};
typedef struct xen_v2d5_getdomaininfo xen_v2d5_getdomaininfo;

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
struct xen_v2d6_getdomaininfo {
    domid_t  domain;	/* the domain number */
    uint32_t flags;	/* flags, see before */
    uint64_t tot_pages ALIGN_64;	/* total number of pages used */
    uint64_t max_pages ALIGN_64;	/* maximum number of pages allowed */
    uint64_t shr_pages ALIGN_64;    /* number of shared pages */
    uint64_t shared_info_frame ALIGN_64; /* MFN of shared_info struct */
    uint64_t cpu_time ALIGN_64;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
};
typedef struct xen_v2d6_getdomaininfo xen_v2d6_getdomaininfo;

J
Jim Fehlig 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
struct xen_v2d7_getdomaininfo {
    domid_t  domain;	/* the domain number */
    uint32_t flags;	/* flags, see before */
    uint64_t tot_pages ALIGN_64;	/* total number of pages used */
    uint64_t max_pages ALIGN_64;	/* maximum number of pages allowed */
    uint64_t shr_pages ALIGN_64;    /* number of shared pages */
    uint64_t shared_info_frame ALIGN_64; /* MFN of shared_info struct */
    uint64_t cpu_time ALIGN_64;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
    uint32_t cpupool;
};
typedef struct xen_v2d7_getdomaininfo xen_v2d7_getdomaininfo;

J
Jim Fehlig 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
struct xen_v2d8_getdomaininfo {
    domid_t  domain;	/* the domain number */
    uint32_t flags;	/* flags, see before */
    uint64_t tot_pages ALIGN_64;	/* total number of pages used */
    uint64_t max_pages ALIGN_64;	/* maximum number of pages allowed */
    uint64_t shr_pages ALIGN_64;    /* number of shared pages */
    uint64_t paged_pages ALIGN_64;    /* number of paged pages */
    uint64_t shared_info_frame ALIGN_64; /* MFN of shared_info struct */
    uint64_t cpu_time ALIGN_64;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
    uint32_t cpupool;
};
typedef struct xen_v2d8_getdomaininfo xen_v2d8_getdomaininfo;

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
struct xen_v2d9_getdomaininfo {
    domid_t  domain;	/* the domain number */
    uint32_t flags;	/* flags, see before */
    uint64_t tot_pages ALIGN_64;	/* total number of pages used */
    uint64_t max_pages ALIGN_64;	/* maximum number of pages allowed */
    uint64_t outstanding_pages ALIGN_64;
    uint64_t shr_pages ALIGN_64;    /* number of shared pages */
    uint64_t paged_pages ALIGN_64;    /* number of paged pages */
    uint64_t shared_info_frame ALIGN_64; /* MFN of shared_info struct */
    uint64_t cpu_time ALIGN_64;  /* CPU time used */
    uint32_t nr_online_vcpus;  /* Number of VCPUs currently online. */
    uint32_t max_vcpu_id; /* Maximum VCPUID in use by this domain. */
    uint32_t ssidref;
    xen_domain_handle_t handle;
    uint32_t cpupool;
};
typedef struct xen_v2d9_getdomaininfo xen_v2d9_getdomaininfo;

294 295 296
union xen_getdomaininfo {
    struct xen_v0_getdomaininfo v0;
    struct xen_v2_getdomaininfo v2;
297
    struct xen_v2d5_getdomaininfo v2d5;
298
    struct xen_v2d6_getdomaininfo v2d6;
J
Jim Fehlig 已提交
299
    struct xen_v2d7_getdomaininfo v2d7;
J
Jim Fehlig 已提交
300
    struct xen_v2d8_getdomaininfo v2d8;
301
    struct xen_v2d9_getdomaininfo v2d9;
302 303 304 305 306 307
};
typedef union xen_getdomaininfo xen_getdomaininfo;

union xen_getdomaininfolist {
    struct xen_v0_getdomaininfo *v0;
    struct xen_v2_getdomaininfo *v2;
308
    struct xen_v2d5_getdomaininfo *v2d5;
309
    struct xen_v2d6_getdomaininfo *v2d6;
J
Jim Fehlig 已提交
310
    struct xen_v2d7_getdomaininfo *v2d7;
J
Jim Fehlig 已提交
311
    struct xen_v2d8_getdomaininfo *v2d8;
312
    struct xen_v2d8_getdomaininfo *v2d9;
313 314 315
};
typedef union xen_getdomaininfolist xen_getdomaininfolist;

316 317 318 319 320 321 322 323 324 325 326 327

struct xen_v2_getschedulerid {
    uint32_t sched_id; /* Get Scheduler ID from Xen */
};
typedef struct xen_v2_getschedulerid xen_v2_getschedulerid;


union xen_getschedulerid {
    struct xen_v2_getschedulerid *v2;
};
typedef union xen_getschedulerid xen_getschedulerid;

328 329 330 331 332 333 334 335 336
struct xen_v2s4_availheap {
    uint32_t min_bitwidth;  /* Smallest address width (zero if don't care). */
    uint32_t max_bitwidth;  /* Largest address width (zero if don't care). */
    int32_t  node;          /* NUMA node (-1 for sum across all nodes). */
    uint64_t avail_bytes;   /* Bytes available in the specified region. */
};

typedef struct xen_v2s4_availheap  xen_v2s4_availheap;

337 338 339 340 341 342 343 344 345
struct xen_v2s5_availheap {
    uint32_t min_bitwidth;  /* Smallest address width (zero if don't care). */
    uint32_t max_bitwidth;  /* Largest address width (zero if don't care). */
    int32_t  node;          /* NUMA node (-1 for sum across all nodes). */
    uint64_t avail_bytes ALIGN_64;   /* Bytes available in the specified region. */
};

typedef struct xen_v2s5_availheap  xen_v2s5_availheap;

346

347
#define XEN_GETDOMAININFOLIST_ALLOC(domlist, size)                      \
P
Philipp Hahn 已提交
348
    (hv_versions.hypervisor < 2 ?                                       \
349
     (VIR_ALLOC_N(domlist.v0, (size)) == 0) :                           \
350 351 352
     (hv_versions.dom_interface >= 9 ?                                  \
      (VIR_ALLOC_N(domlist.v2d9, (size)) == 0) :                        \
     (hv_versions.dom_interface == 8 ?                                  \
J
Jim Fehlig 已提交
353 354
      (VIR_ALLOC_N(domlist.v2d8, (size)) == 0) :                        \
     (hv_versions.dom_interface == 7 ?                                  \
J
Jim Fehlig 已提交
355
      (VIR_ALLOC_N(domlist.v2d7, (size)) == 0) :                        \
P
Philipp Hahn 已提交
356
     (hv_versions.dom_interface == 6 ?                                  \
357
      (VIR_ALLOC_N(domlist.v2d6, (size)) == 0) :                        \
P
Philipp Hahn 已提交
358
     (hv_versions.dom_interface == 5 ?                                  \
359
      (VIR_ALLOC_N(domlist.v2d5, (size)) == 0) :                        \
360
      (VIR_ALLOC_N(domlist.v2, (size)) == 0)))))))
361

362
#define XEN_GETDOMAININFOLIST_FREE(domlist)            \
P
Philipp Hahn 已提交
363
    (hv_versions.hypervisor < 2 ?                      \
364
     VIR_FREE(domlist.v0) :                            \
365 366 367
     (hv_versions.dom_interface >= 9 ?                 \
      VIR_FREE(domlist.v2d9) :                         \
     (hv_versions.dom_interface == 8 ?                 \
J
Jim Fehlig 已提交
368 369
      VIR_FREE(domlist.v2d8) :                         \
     (hv_versions.dom_interface == 7 ?                 \
J
Jim Fehlig 已提交
370
      VIR_FREE(domlist.v2d7) :                         \
P
Philipp Hahn 已提交
371
     (hv_versions.dom_interface == 6 ?                 \
372
      VIR_FREE(domlist.v2d6) :                         \
P
Philipp Hahn 已提交
373
     (hv_versions.dom_interface == 5 ?                 \
374
      VIR_FREE(domlist.v2d5) :                         \
375
      VIR_FREE(domlist.v2)))))))
376

377
#define XEN_GETDOMAININFOLIST_CLEAR(domlist, size)            \
P
Philipp Hahn 已提交
378
    (hv_versions.hypervisor < 2 ?                             \
379
     memset(domlist.v0, 0, sizeof(*domlist.v0) * size) :      \
380 381 382
     (hv_versions.dom_interface >= 9 ?                        \
      memset(domlist.v2d9, 0, sizeof(*domlist.v2d9) * size) : \
     (hv_versions.dom_interface == 8 ?                        \
J
Jim Fehlig 已提交
383 384
      memset(domlist.v2d8, 0, sizeof(*domlist.v2d8) * size) : \
     (hv_versions.dom_interface == 7 ?                        \
J
Jim Fehlig 已提交
385
      memset(domlist.v2d7, 0, sizeof(*domlist.v2d7) * size) : \
P
Philipp Hahn 已提交
386
     (hv_versions.dom_interface == 6 ?                        \
387
      memset(domlist.v2d6, 0, sizeof(*domlist.v2d6) * size) : \
P
Philipp Hahn 已提交
388
     (hv_versions.dom_interface == 5 ?                        \
389
      memset(domlist.v2d5, 0, sizeof(*domlist.v2d5) * size) : \
390
      memset(domlist.v2, 0, sizeof(*domlist.v2) * size)))))))
391 392

#define XEN_GETDOMAININFOLIST_DOMAIN(domlist, n)    \
P
Philipp Hahn 已提交
393
    (hv_versions.hypervisor < 2 ?                   \
394
     domlist.v0[n].domain :                         \
395 396 397
     (hv_versions.dom_interface >= 9 ?              \
      domlist.v2d9[n].domain :                      \
     (hv_versions.dom_interface == 8 ?              \
J
Jim Fehlig 已提交
398 399
      domlist.v2d8[n].domain :                      \
     (hv_versions.dom_interface == 7 ?              \
J
Jim Fehlig 已提交
400
      domlist.v2d7[n].domain :                      \
P
Philipp Hahn 已提交
401
     (hv_versions.dom_interface == 6 ?              \
402
      domlist.v2d6[n].domain :                      \
P
Philipp Hahn 已提交
403
     (hv_versions.dom_interface == 5 ?              \
404
      domlist.v2d5[n].domain :                      \
405
      domlist.v2[n].domain))))))
406

407
#define XEN_GETDOMAININFOLIST_UUID(domlist, n)      \
P
Philipp Hahn 已提交
408
    (hv_versions.hypervisor < 2 ?                   \
409
     domlist.v0[n].handle :                         \
410 411 412
     (hv_versions.dom_interface >= 9 ?              \
      domlist.v2d9[n].handle :                      \
     (hv_versions.dom_interface == 8 ?              \
J
Jim Fehlig 已提交
413 414
      domlist.v2d8[n].handle :                      \
     (hv_versions.dom_interface == 7 ?              \
J
Jim Fehlig 已提交
415
      domlist.v2d7[n].handle :                      \
P
Philipp Hahn 已提交
416
     (hv_versions.dom_interface == 6 ?              \
417
      domlist.v2d6[n].handle :                      \
P
Philipp Hahn 已提交
418
     (hv_versions.dom_interface == 5 ?              \
419
      domlist.v2d5[n].handle :                      \
420
      domlist.v2[n].handle))))))
421

422
#define XEN_GETDOMAININFOLIST_DATA(domlist)        \
P
Philipp Hahn 已提交
423
    (hv_versions.hypervisor < 2 ?                  \
424
     (void*)(domlist->v0) :                        \
425 426 427
     (hv_versions.dom_interface >= 9 ?             \
      (void*)(domlist->v2d9) :                     \
     (hv_versions.dom_interface == 8 ?             \
J
Jim Fehlig 已提交
428 429
      (void*)(domlist->v2d8) :                     \
     (hv_versions.dom_interface == 7 ?             \
J
Jim Fehlig 已提交
430
      (void*)(domlist->v2d7) :                     \
P
Philipp Hahn 已提交
431
     (hv_versions.dom_interface == 6 ?             \
432
      (void*)(domlist->v2d6) :                     \
P
Philipp Hahn 已提交
433
     (hv_versions.dom_interface == 5 ?             \
434
      (void*)(domlist->v2d5) :                     \
435
      (void*)(domlist->v2)))))))
436 437

#define XEN_GETDOMAININFO_SIZE                     \
P
Philipp Hahn 已提交
438
    (hv_versions.hypervisor < 2 ?                  \
439
     sizeof(xen_v0_getdomaininfo) :                \
440 441 442
     (hv_versions.dom_interface >= 9 ?             \
      sizeof(xen_v2d9_getdomaininfo) :             \
     (hv_versions.dom_interface == 8 ?             \
J
Jim Fehlig 已提交
443 444
      sizeof(xen_v2d8_getdomaininfo) :             \
     (hv_versions.dom_interface == 7 ?             \
J
Jim Fehlig 已提交
445
      sizeof(xen_v2d7_getdomaininfo) :             \
P
Philipp Hahn 已提交
446
     (hv_versions.dom_interface == 6 ?             \
447
      sizeof(xen_v2d6_getdomaininfo) :             \
P
Philipp Hahn 已提交
448
     (hv_versions.dom_interface == 5 ?             \
449
      sizeof(xen_v2d5_getdomaininfo) :             \
450
      sizeof(xen_v2_getdomaininfo)))))))
451 452

#define XEN_GETDOMAININFO_CLEAR(dominfo)                           \
P
Philipp Hahn 已提交
453
    (hv_versions.hypervisor < 2 ?                                  \
454
     memset(&(dominfo.v0), 0, sizeof(xen_v0_getdomaininfo)) :      \
455 456 457
     (hv_versions.dom_interface >= 9 ?                             \
      memset(&(dominfo.v2d9), 0, sizeof(xen_v2d9_getdomaininfo)) : \
     (hv_versions.dom_interface == 8 ?                             \
J
Jim Fehlig 已提交
458 459
      memset(&(dominfo.v2d8), 0, sizeof(xen_v2d8_getdomaininfo)) : \
     (hv_versions.dom_interface == 7 ?                             \
J
Jim Fehlig 已提交
460
      memset(&(dominfo.v2d7), 0, sizeof(xen_v2d7_getdomaininfo)) : \
P
Philipp Hahn 已提交
461
     (hv_versions.dom_interface == 6 ?                             \
462
      memset(&(dominfo.v2d6), 0, sizeof(xen_v2d6_getdomaininfo)) : \
P
Philipp Hahn 已提交
463
     (hv_versions.dom_interface == 5 ?                             \
464
      memset(&(dominfo.v2d5), 0, sizeof(xen_v2d5_getdomaininfo)) : \
465
      memset(&(dominfo.v2), 0, sizeof(xen_v2_getdomaininfo))))))))
466 467

#define XEN_GETDOMAININFO_DOMAIN(dominfo)       \
P
Philipp Hahn 已提交
468
    (hv_versions.hypervisor < 2 ?               \
469
     dominfo.v0.domain :                        \
470 471 472
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.domain :                     \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
473 474
      dominfo.v2d8.domain :                     \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
475
      dominfo.v2d7.domain :                     \
P
Philipp Hahn 已提交
476
     (hv_versions.dom_interface == 6 ?          \
477
      dominfo.v2d6.domain :                     \
P
Philipp Hahn 已提交
478
     (hv_versions.dom_interface == 5 ?          \
479
      dominfo.v2d5.domain :                     \
480
      dominfo.v2.domain))))))
481 482

#define XEN_GETDOMAININFO_CPUTIME(dominfo)      \
P
Philipp Hahn 已提交
483
    (hv_versions.hypervisor < 2 ?               \
484
     dominfo.v0.cpu_time :                      \
485 486 487
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.cpu_time :                   \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
488 489
      dominfo.v2d8.cpu_time :                   \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
490
      dominfo.v2d7.cpu_time :                   \
P
Philipp Hahn 已提交
491
     (hv_versions.dom_interface == 6 ?          \
492
      dominfo.v2d6.cpu_time :                   \
P
Philipp Hahn 已提交
493
     (hv_versions.dom_interface == 5 ?          \
494
      dominfo.v2d5.cpu_time :                   \
495
      dominfo.v2.cpu_time))))))
496

497 498

#define XEN_GETDOMAININFO_CPUCOUNT(dominfo)     \
P
Philipp Hahn 已提交
499
    (hv_versions.hypervisor < 2 ?               \
500
     dominfo.v0.nr_online_vcpus :               \
501 502 503
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.nr_online_vcpus :            \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
504 505
      dominfo.v2d8.nr_online_vcpus :            \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
506
      dominfo.v2d7.nr_online_vcpus :            \
P
Philipp Hahn 已提交
507
     (hv_versions.dom_interface == 6 ?          \
508
      dominfo.v2d6.nr_online_vcpus :            \
P
Philipp Hahn 已提交
509
     (hv_versions.dom_interface == 5 ?          \
510
      dominfo.v2d5.nr_online_vcpus :            \
511
      dominfo.v2.nr_online_vcpus))))))
512

J
Jim Fehlig 已提交
513
#define XEN_GETDOMAININFO_MAXCPUID(dominfo)     \
P
Philipp Hahn 已提交
514
    (hv_versions.hypervisor < 2 ?               \
515
     dominfo.v0.max_vcpu_id :                   \
516 517 518
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.max_vcpu_id :                \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
519 520
      dominfo.v2d8.max_vcpu_id :                \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
521
      dominfo.v2d7.max_vcpu_id :                \
P
Philipp Hahn 已提交
522
     (hv_versions.dom_interface == 6 ?          \
523
      dominfo.v2d6.max_vcpu_id :                \
P
Philipp Hahn 已提交
524
     (hv_versions.dom_interface == 5 ?          \
525
      dominfo.v2d5.max_vcpu_id :                \
526
      dominfo.v2.max_vcpu_id))))))
527

528
#define XEN_GETDOMAININFO_FLAGS(dominfo)        \
P
Philipp Hahn 已提交
529
    (hv_versions.hypervisor < 2 ?               \
530
     dominfo.v0.flags :                         \
531 532 533
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.flags :                      \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
534 535
      dominfo.v2d8.flags :                      \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
536
      dominfo.v2d7.flags :                      \
P
Philipp Hahn 已提交
537
     (hv_versions.dom_interface == 6 ?          \
538
      dominfo.v2d6.flags :                      \
P
Philipp Hahn 已提交
539
     (hv_versions.dom_interface == 5 ?          \
540
      dominfo.v2d5.flags :                      \
541
      dominfo.v2.flags))))))
542 543

#define XEN_GETDOMAININFO_TOT_PAGES(dominfo)    \
P
Philipp Hahn 已提交
544
    (hv_versions.hypervisor < 2 ?               \
545
     dominfo.v0.tot_pages :                     \
546 547 548
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.tot_pages :                  \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
549 550
      dominfo.v2d8.tot_pages :                  \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
551
      dominfo.v2d7.tot_pages :                  \
P
Philipp Hahn 已提交
552
     (hv_versions.dom_interface == 6 ?          \
553
      dominfo.v2d6.tot_pages :                  \
P
Philipp Hahn 已提交
554
     (hv_versions.dom_interface == 5 ?          \
555
      dominfo.v2d5.tot_pages :                  \
556
      dominfo.v2.tot_pages))))))
557 558

#define XEN_GETDOMAININFO_MAX_PAGES(dominfo)    \
P
Philipp Hahn 已提交
559
    (hv_versions.hypervisor < 2 ?               \
560
     dominfo.v0.max_pages :                     \
561 562 563
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.max_pages :                  \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
564 565
      dominfo.v2d8.max_pages :                  \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
566
      dominfo.v2d7.max_pages :                  \
P
Philipp Hahn 已提交
567
     (hv_versions.dom_interface == 6 ?          \
568
      dominfo.v2d6.max_pages :                  \
P
Philipp Hahn 已提交
569
     (hv_versions.dom_interface == 5 ?          \
570
      dominfo.v2d5.max_pages :                  \
571
      dominfo.v2.max_pages))))))
572

573
#define XEN_GETDOMAININFO_UUID(dominfo)         \
P
Philipp Hahn 已提交
574
    (hv_versions.hypervisor < 2 ?               \
575
     dominfo.v0.handle :                        \
576 577 578
     (hv_versions.dom_interface >= 9 ?          \
      dominfo.v2d9.handle :                     \
     (hv_versions.dom_interface == 8 ?          \
J
Jim Fehlig 已提交
579 580
      dominfo.v2d8.handle :                     \
     (hv_versions.dom_interface == 7 ?          \
J
Jim Fehlig 已提交
581
      dominfo.v2d7.handle :                     \
P
Philipp Hahn 已提交
582
     (hv_versions.dom_interface == 6 ?          \
583
      dominfo.v2d6.handle :                     \
P
Philipp Hahn 已提交
584
     (hv_versions.dom_interface == 5 ?          \
585
      dominfo.v2d5.handle :                     \
586
      dominfo.v2.handle))))))
587

588

589 590 591 592
static int
lock_pages(void *addr, size_t len)
{
#ifdef __linux__
593 594 595 596 597 598 599
    if (mlock(addr, len) < 0) {
        virReportSystemError(errno,
                             _("Unable to lock %zu bytes of memory"),
                             len);
        return -1;
    }
    return 0;
600
#elif defined(__sun)
601
    return 0;
602 603 604 605 606 607 608
#endif
}

static int
unlock_pages(void *addr, size_t len)
{
#ifdef __linux__
609 610 611 612 613 614 615
    if (munlock(addr, len) < 0) {
        virReportSystemError(errno,
                             _("Unable to unlock %zu bytes of memory"),
                             len);
        return -1;
    }
    return 0;
616
#elif defined(__sun)
617
    return 0;
618 619 620
#endif
}

621 622

struct xen_v0_getdomaininfolistop {
623 624 625 626 627
    domid_t   first_domain;
    uint32_t  max_domains;
    struct xen_v0_getdomaininfo *buffer;
    uint32_t  num_domains;
};
628 629 630 631 632 633 634 635 636 637 638
typedef struct xen_v0_getdomaininfolistop xen_v0_getdomaininfolistop;


struct xen_v2_getdomaininfolistop {
    domid_t   first_domain;
    uint32_t  max_domains;
    struct xen_v2_getdomaininfo *buffer;
    uint32_t  num_domains;
};
typedef struct xen_v2_getdomaininfolistop xen_v2_getdomaininfolistop;

639 640 641 642
/* As of HV version 2, sysctl version 3 the *buffer pointer is 64-bit aligned */
struct xen_v2s3_getdomaininfolistop {
    domid_t   first_domain;
    uint32_t  max_domains;
643 644
#ifdef __BIG_ENDIAN__
    struct {
645
        int __pad[(sizeof(long long) - sizeof(struct xen_v2d5_getdomaininfo *)) / sizeof(int)];
646 647 648
        struct xen_v2d5_getdomaininfo *v;
    } buffer;
#else
649 650 651 652
    union {
        struct xen_v2d5_getdomaininfo *v;
        uint64_t pad ALIGN_64;
    } buffer;
653
#endif
654 655 656 657
    uint32_t  num_domains;
};
typedef struct xen_v2s3_getdomaininfolistop xen_v2s3_getdomaininfolistop;

658

659 660 661 662 663 664 665

struct xen_v0_domainop {
    domid_t   domain;
};
typedef struct xen_v0_domainop xen_v0_domainop;

/*
666
 * The information for a pausedomain system hypercall
667 668 669 670 671 672
 */
#define XEN_V0_OP_PAUSEDOMAIN	10
#define XEN_V1_OP_PAUSEDOMAIN	10
#define XEN_V2_OP_PAUSEDOMAIN	3

/*
673
 * The information for an unpausedomain system hypercall
674 675 676 677 678 679
 */
#define XEN_V0_OP_UNPAUSEDOMAIN	11
#define XEN_V1_OP_UNPAUSEDOMAIN	11
#define XEN_V2_OP_UNPAUSEDOMAIN	4

/*
E
Eric Blake 已提交
680
 * The information for a setmaxmem system hypercall
681 682 683
 */
#define XEN_V0_OP_SETMAXMEM	28
#define XEN_V1_OP_SETMAXMEM	28
684
#define XEN_V2_OP_SETMAXMEM	11
685 686 687 688 689 690 691 692 693 694 695 696 697

struct xen_v0_setmaxmem {
    domid_t	domain;
    uint64_t	maxmem;
};
typedef struct xen_v0_setmaxmem xen_v0_setmaxmem;
typedef struct xen_v0_setmaxmem xen_v1_setmaxmem;

struct xen_v2_setmaxmem {
    uint64_t	maxmem;
};
typedef struct xen_v2_setmaxmem xen_v2_setmaxmem;

698 699 700 701 702
struct xen_v2d5_setmaxmem {
    uint64_t	maxmem ALIGN_64;
};
typedef struct xen_v2d5_setmaxmem xen_v2d5_setmaxmem;

703
/*
E
Eric Blake 已提交
704
 * The information for a setvcpumap system hypercall
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
 * Note that between 1 and 2 the limitation to 64 physical CPU was lifted
 * hence the difference in structures
 */
#define XEN_V0_OP_SETVCPUMAP	20
#define XEN_V1_OP_SETVCPUMAP	20
#define XEN_V2_OP_SETVCPUMAP	9

struct xen_v0_setvcpumap {
    domid_t	domain;
    uint32_t	vcpu;
    cpumap_t    cpumap;
};
typedef struct xen_v0_setvcpumap xen_v0_setvcpumap;
typedef struct xen_v0_setvcpumap xen_v1_setvcpumap;

struct xen_v2_cpumap {
    uint8_t    *bitmap;
    uint32_t    nr_cpus;
};
struct xen_v2_setvcpumap {
    uint32_t	vcpu;
    struct xen_v2_cpumap cpumap;
};
typedef struct xen_v2_setvcpumap xen_v2_setvcpumap;

730 731
/* HV version 2, Dom version 5 requires 64-bit alignment */
struct xen_v2d5_cpumap {
732 733
#ifdef __BIG_ENDIAN__
    struct {
734
        int __pad[(sizeof(long long) - sizeof(uint8_t *)) / sizeof(int)];
735 736 737
        uint8_t *v;
    } bitmap;
#else
738 739 740 741
    union {
        uint8_t    *v;
        uint64_t   pad ALIGN_64;
    } bitmap;
742
#endif
743 744 745 746 747 748 749 750
    uint32_t    nr_cpus;
};
struct xen_v2d5_setvcpumap {
    uint32_t	vcpu;
    struct xen_v2d5_cpumap cpumap;
};
typedef struct xen_v2d5_setvcpumap xen_v2d5_setvcpumap;

751
/*
E
Eric Blake 已提交
752
 * The information for a vcpuinfo system hypercall
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
 */
#define XEN_V0_OP_GETVCPUINFO   43
#define XEN_V1_OP_GETVCPUINFO	43
#define XEN_V2_OP_GETVCPUINFO   14

struct xen_v0_vcpuinfo {
    domid_t	domain;		/* owner's domain */
    uint32_t	vcpu;		/* the vcpu number */
    uint8_t	online;		/* seen as on line */
    uint8_t	blocked;	/* blocked on event */
    uint8_t	running;	/* scheduled on CPU */
    uint64_t    cpu_time;	/* nanosecond of CPU used */
    uint32_t	cpu;		/* current mapping */
    cpumap_t	cpumap;		/* deprecated in V2 */
};
typedef struct xen_v0_vcpuinfo xen_v0_vcpuinfo;
typedef struct xen_v0_vcpuinfo xen_v1_vcpuinfo;

struct xen_v2_vcpuinfo {
    uint32_t	vcpu;		/* the vcpu number */
    uint8_t	online;		/* seen as on line */
    uint8_t	blocked;	/* blocked on event */
    uint8_t	running;	/* scheduled on CPU */
    uint64_t    cpu_time;	/* nanosecond of CPU used */
    uint32_t	cpu;		/* current mapping */
};
typedef struct xen_v2_vcpuinfo xen_v2_vcpuinfo;

781 782 783 784 785 786 787 788 789 790
struct xen_v2d5_vcpuinfo {
    uint32_t	vcpu;		/* the vcpu number */
    uint8_t	online;		/* seen as on line */
    uint8_t	blocked;	/* blocked on event */
    uint8_t	running;	/* scheduled on CPU */
    uint64_t    cpu_time ALIGN_64; /* nanosecond of CPU used */
    uint32_t	cpu;		/* current mapping */
};
typedef struct xen_v2d5_vcpuinfo xen_v2d5_vcpuinfo;

791 792 793 794 795
/*
 * from V2 the pinning of a vcpu is read with a separate call
 */
#define XEN_V2_OP_GETVCPUMAP	25
typedef struct xen_v2_setvcpumap xen_v2_getvcpumap;
796
typedef struct xen_v2d5_setvcpumap xen_v2d5_getvcpumap;
797

798 799 800 801 802
/*
 * from V2 we get the scheduler information
 */
#define XEN_V2_OP_GETSCHEDULERID	4

803 804 805
/*
 * from V2 we get the available heap information
 */
E
Eric Blake 已提交
806
#define XEN_V2_OP_GETAVAILHEAP		9
807

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
/*
 * from V2 we get the scheduler parameter
 */
#define XEN_V2_OP_SCHEDULER		16
/* Scheduler types. */
#define XEN_SCHEDULER_SEDF       4
#define XEN_SCHEDULER_CREDIT     5
/* get/set scheduler parameters */
#define XEN_DOMCTL_SCHEDOP_putinfo 0
#define XEN_DOMCTL_SCHEDOP_getinfo 1

struct xen_v2_setschedinfo {
    uint32_t sched_id;
    uint32_t cmd;
    union {
        struct xen_domctl_sched_sedf {
            uint64_t period ALIGN_64;
            uint64_t slice  ALIGN_64;
            uint64_t latency ALIGN_64;
            uint32_t extratime;
            uint32_t weight;
        } sedf;
        struct xen_domctl_sched_credit {
            uint16_t weight;
            uint16_t cap;
        } credit;
    } u;
};
typedef struct xen_v2_setschedinfo xen_v2_setschedinfo;
typedef struct xen_v2_setschedinfo xen_v2_getschedinfo;


840 841 842 843 844 845 846 847 848
/*
 * The hypercall operation structures also have changed on
 * changeset 86d26e6ec89b
 */
/* the old structure */
struct xen_op_v0 {
    uint32_t cmd;
    uint32_t interface_version;
    union {
849 850 851 852 853 854
        xen_v0_getdomaininfolistop getdomaininfolist;
        xen_v0_domainop          domain;
        xen_v0_setmaxmem         setmaxmem;
        xen_v0_setvcpumap        setvcpumap;
        xen_v0_vcpuinfo          getvcpuinfo;
        uint8_t padding[128];
855 856 857 858 859 860 861 862 863 864
    } u;
};
typedef struct xen_op_v0 xen_op_v0;
typedef struct xen_op_v0 xen_op_v1;

/* the new structure for systems operations */
struct xen_op_v2_sys {
    uint32_t cmd;
    uint32_t interface_version;
    union {
865 866
        xen_v2_getdomaininfolistop   getdomaininfolist;
        xen_v2s3_getdomaininfolistop getdomaininfolists3;
867
        xen_v2_getschedulerid        getschedulerid;
868
        xen_v2s4_availheap           availheap;
869
        xen_v2s5_availheap           availheap5;
870
        uint8_t padding[128];
871 872 873 874 875 876 877 878 879 880
    } u;
};
typedef struct xen_op_v2_sys xen_op_v2_sys;

/* the new structure for domains operation */
struct xen_op_v2_dom {
    uint32_t cmd;
    uint32_t interface_version;
    domid_t  domain;
    union {
881
        xen_v2_setmaxmem         setmaxmem;
882
        xen_v2d5_setmaxmem       setmaxmemd5;
883
        xen_v2_setvcpumap        setvcpumap;
884
        xen_v2d5_setvcpumap      setvcpumapd5;
885
        xen_v2_vcpuinfo          getvcpuinfo;
886
        xen_v2d5_vcpuinfo        getvcpuinfod5;
887
        xen_v2_getvcpumap        getvcpumap;
888
        xen_v2d5_getvcpumap      getvcpumapd5;
889 890
        xen_v2_setschedinfo      setschedinfo;
        xen_v2_getschedinfo      getschedinfo;
891
        uint8_t padding[128];
892 893 894
    } u;
};
typedef struct xen_op_v2_dom xen_op_v2_dom;
895 896


897
#ifdef __linux__
898 899
# define XEN_HYPERVISOR_SOCKET	"/proc/xen/privcmd"
# define HYPERVISOR_CAPABILITIES	"/sys/hypervisor/properties/capabilities"
900
#elif defined(__sun)
901
# define XEN_HYPERVISOR_SOCKET	"/dev/xen/privcmd"
902
#else
903
# error "unsupported platform"
904
#endif
905

906 907 908
/**
 * xenHypervisorDoV0Op:
 * @handle: the handle to the Xen hypervisor
R
Richard W.M. Jones 已提交
909
 * @op: pointer to the hypervisor operation structure
910
 *
E
Eric Blake 已提交
911 912
 * Do a hypervisor operation though the old interface,
 * this leads to a hypervisor call through ioctl.
913 914 915 916 917 918 919 920 921 922
 *
 * Returns 0 in case of success and -1 in case of error.
 */
static int
xenHypervisorDoV0Op(int handle, xen_op_v0 * op)
{
    int ret;
    v0_hypercall_t hc;

    memset(&hc, 0, sizeof(hc));
P
Philipp Hahn 已提交
923
    op->interface_version = hv_versions.hv << 8;
924 925 926
    hc.op = __HYPERVISOR_dom0_op;
    hc.arg[0] = (unsigned long) op;

927
    if (lock_pages(op, sizeof(dom0_op_t)) < 0)
928
        return -1;
929 930 931

    ret = ioctl(handle, xen_ioctl_hypercall_cmd, (unsigned long) &hc);
    if (ret < 0) {
932 933 934
        virReportSystemError(errno,
                             _("Unable to issue hypervisor ioctl %d"),
                             xen_ioctl_hypercall_cmd);
935 936
    }

937
    if (unlock_pages(op, sizeof(dom0_op_t)) < 0)
938 939 940
        ret = -1;

    if (ret < 0)
941
        return -1;
942

943
    return 0;
944 945 946 947
}
/**
 * xenHypervisorDoV1Op:
 * @handle: the handle to the Xen hypervisor
R
Richard W.M. Jones 已提交
948
 * @op: pointer to the hypervisor operation structure
949
 *
E
Eric Blake 已提交
950
 * Do a hypervisor v1 operation, this leads to a hypervisor call through
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
 * ioctl.
 *
 * Returns 0 in case of success and -1 in case of error.
 */
static int
xenHypervisorDoV1Op(int handle, xen_op_v1* op)
{
    int ret;
    hypercall_t hc;

    memset(&hc, 0, sizeof(hc));
    op->interface_version = DOM0_INTERFACE_VERSION;
    hc.op = __HYPERVISOR_dom0_op;
    hc.arg[0] = (unsigned long) op;

966
    if (lock_pages(op, sizeof(dom0_op_t)) < 0)
967
        return -1;
968 969 970

    ret = ioctl(handle, xen_ioctl_hypercall_cmd, (unsigned long) &hc);
    if (ret < 0) {
971 972 973
        virReportSystemError(errno,
                             _("Unable to issue hypervisor ioctl %d"),
                             xen_ioctl_hypercall_cmd);
974 975
    }

976
    if (unlock_pages(op, sizeof(dom0_op_t)) < 0)
977 978 979
        ret = -1;

    if (ret < 0)
980
        return -1;
981

982
    return 0;
983 984 985 986 987 988 989
}

/**
 * xenHypervisorDoV2Sys:
 * @handle: the handle to the Xen hypervisor
 * @op: pointer to the hypervisor operation structure
 *
E
Eric Blake 已提交
990
 * Do a hypervisor v2 system operation, this leads to a hypervisor
991 992 993 994 995 996 997 998 999 1000 1001
 * call through ioctl.
 *
 * Returns 0 in case of success and -1 in case of error.
 */
static int
xenHypervisorDoV2Sys(int handle, xen_op_v2_sys* op)
{
    int ret;
    hypercall_t hc;

    memset(&hc, 0, sizeof(hc));
P
Philipp Hahn 已提交
1002
    op->interface_version = hv_versions.sys_interface;
1003 1004 1005
    hc.op = __HYPERVISOR_sysctl;
    hc.arg[0] = (unsigned long) op;

1006
    if (lock_pages(op, sizeof(dom0_op_t)) < 0)
1007
        return -1;
1008 1009 1010

    ret = ioctl(handle, xen_ioctl_hypercall_cmd, (unsigned long) &hc);
    if (ret < 0) {
1011 1012 1013
        virReportSystemError(errno,
                             _("Unable to issue hypervisor ioctl %d"),
                             xen_ioctl_hypercall_cmd);
1014 1015
    }

1016
    if (unlock_pages(op, sizeof(dom0_op_t)) < 0)
1017 1018 1019
        ret = -1;

    if (ret < 0)
1020
        return -1;
1021

1022
    return 0;
1023 1024 1025 1026 1027 1028 1029
}

/**
 * xenHypervisorDoV2Dom:
 * @handle: the handle to the Xen hypervisor
 * @op: pointer to the hypervisor domain operation structure
 *
E
Eric Blake 已提交
1030
 * Do a hypervisor v2 domain operation, this leads to a hypervisor
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
 * call through ioctl.
 *
 * Returns 0 in case of success and -1 in case of error.
 */
static int
xenHypervisorDoV2Dom(int handle, xen_op_v2_dom* op)
{
    int ret;
    hypercall_t hc;

    memset(&hc, 0, sizeof(hc));
P
Philipp Hahn 已提交
1042
    op->interface_version = hv_versions.dom_interface;
1043 1044 1045
    hc.op = __HYPERVISOR_domctl;
    hc.arg[0] = (unsigned long) op;

1046
    if (lock_pages(op, sizeof(dom0_op_t)) < 0)
1047
        return -1;
1048 1049 1050

    ret = ioctl(handle, xen_ioctl_hypercall_cmd, (unsigned long) &hc);
    if (ret < 0) {
1051 1052 1053
        virReportSystemError(errno,
                             _("Unable to issue hypervisor ioctl %d"),
                             xen_ioctl_hypercall_cmd);
1054 1055
    }

1056
    if (unlock_pages(op, sizeof(dom0_op_t)) < 0)
1057 1058 1059
        ret = -1;

    if (ret < 0)
1060
        return -1;
1061

1062
    return 0;
1063 1064 1065 1066 1067 1068 1069 1070 1071
}

/**
 * virXen_getdomaininfolist:
 * @handle: the hypervisor handle
 * @first_domain: first domain in the range
 * @maxids: maximum number of domains to list
 * @dominfos: output structures
 *
1072
 * Do a low level hypercall to list existing domains information
1073 1074 1075 1076
 *
 * Returns the number of domains or -1 in case of failure
 */
static int
1077 1078 1079
virXen_getdomaininfolist(int handle,
                         int first_domain,
                         int maxids,
1080
                         xen_getdomaininfolist *dominfos)
1081 1082 1083
{
    int ret = -1;

1084
    if (lock_pages(XEN_GETDOMAININFOLIST_DATA(dominfos),
1085
                   XEN_GETDOMAININFO_SIZE * maxids) < 0)
1086
        return -1;
1087

P
Philipp Hahn 已提交
1088
    if (hv_versions.hypervisor > 1) {
1089 1090 1091
        xen_op_v2_sys op;

        memset(&op, 0, sizeof(op));
1092
        op.cmd = XEN_V2_OP_GETDOMAININFOLIST;
1093

P
Philipp Hahn 已提交
1094
        if (hv_versions.sys_interface < 3) {
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
            op.u.getdomaininfolist.first_domain = (domid_t) first_domain;
            op.u.getdomaininfolist.max_domains = maxids;
            op.u.getdomaininfolist.buffer = dominfos->v2;
            op.u.getdomaininfolist.num_domains = maxids;
        } else {
            op.u.getdomaininfolists3.first_domain = (domid_t) first_domain;
            op.u.getdomaininfolists3.max_domains = maxids;
            op.u.getdomaininfolists3.buffer.v = dominfos->v2d5;
            op.u.getdomaininfolists3.num_domains = maxids;
        }
1105
        ret = xenHypervisorDoV2Sys(handle, &op);
1106 1107

        if (ret == 0) {
P
Philipp Hahn 已提交
1108
            if (hv_versions.sys_interface < 3)
1109 1110 1111 1112
                ret = op.u.getdomaininfolist.num_domains;
            else
                ret = op.u.getdomaininfolists3.num_domains;
        }
P
Philipp Hahn 已提交
1113
    } else if (hv_versions.hypervisor == 1) {
1114 1115 1116
        xen_op_v1 op;

        memset(&op, 0, sizeof(op));
1117 1118 1119 1120 1121 1122 1123 1124
        op.cmd = XEN_V1_OP_GETDOMAININFOLIST;
        op.u.getdomaininfolist.first_domain = (domid_t) first_domain;
        op.u.getdomaininfolist.max_domains = maxids;
        op.u.getdomaininfolist.buffer = dominfos->v0;
        op.u.getdomaininfolist.num_domains = maxids;
        ret = xenHypervisorDoV1Op(handle, &op);
        if (ret == 0)
            ret = op.u.getdomaininfolist.num_domains;
P
Philipp Hahn 已提交
1125
    } else if (hv_versions.hypervisor == 0) {
1126 1127 1128
        xen_op_v0 op;

        memset(&op, 0, sizeof(op));
1129 1130 1131 1132 1133 1134 1135 1136
        op.cmd = XEN_V0_OP_GETDOMAININFOLIST;
        op.u.getdomaininfolist.first_domain = (domid_t) first_domain;
        op.u.getdomaininfolist.max_domains = maxids;
        op.u.getdomaininfolist.buffer = dominfos->v0;
        op.u.getdomaininfolist.num_domains = maxids;
        ret = xenHypervisorDoV0Op(handle, &op);
        if (ret == 0)
            ret = op.u.getdomaininfolist.num_domains;
1137
    }
1138
    if (unlock_pages(XEN_GETDOMAININFOLIST_DATA(dominfos),
1139
                     XEN_GETDOMAININFO_SIZE * maxids) < 0)
1140
        ret = -1;
1141

1142
    return ret;
1143 1144
}

1145
static int
1146 1147
virXen_getdomaininfo(int handle, int first_domain, xen_getdomaininfo *dominfo)
{
1148 1149
    xen_getdomaininfolist dominfos;

P
Philipp Hahn 已提交
1150
    if (hv_versions.hypervisor < 2) {
1151 1152 1153 1154 1155 1156 1157 1158 1159
        dominfos.v0 = &(dominfo->v0);
    } else {
        dominfos.v2 = &(dominfo->v2);
    }

    return virXen_getdomaininfolist(handle, first_domain, 1, &dominfos);
}


1160 1161
/**
 * xenHypervisorGetSchedulerType:
1162
 * @conn: the hypervisor connection
1163 1164 1165 1166 1167 1168 1169
 * @nparams:give a number of scheduler parameters.
 *
 * Do a low level hypercall to get scheduler type
 *
 * Returns scheduler name or NULL in case of failure
 */
char *
1170 1171
xenHypervisorGetSchedulerType(virConnectPtr conn,
                              int *nparams)
1172 1173
{
    char *schedulertype = NULL;
1174
    xenUnifiedPrivatePtr priv = conn->privateData;
1175 1176

    /*
P
Philipp Hahn 已提交
1177
     * Support only hv_versions.dom_interface >=5
1178
     * (Xen3.1.0 or later)
1179
     * TODO: check on Xen 3.0.3
1180
     */
P
Philipp Hahn 已提交
1181
    if (hv_versions.dom_interface < 5) {
1182 1183
        virReportError(VIR_ERR_NO_XEN, "%s",
                       _("unsupported in dom interface < 5"));
1184 1185 1186
        return NULL;
    }

P
Philipp Hahn 已提交
1187
    if (hv_versions.hypervisor > 1) {
1188 1189 1190 1191 1192 1193 1194
        xen_op_v2_sys op;
        int ret;

        memset(&op, 0, sizeof(op));
        op.cmd = XEN_V2_OP_GETSCHEDULERID;
        ret = xenHypervisorDoV2Sys(priv->handle, &op);
        if (ret < 0)
1195
            return NULL;
1196 1197

        switch (op.u.getschedulerid.sched_id){
1198
            case XEN_SCHEDULER_SEDF:
1199
                ignore_value(VIR_STRDUP(schedulertype, "sedf"));
1200
                if (nparams)
1201
                    *nparams = XEN_SCHED_SEDF_NPARAM;
1202 1203
                break;
            case XEN_SCHEDULER_CREDIT:
1204
                ignore_value(VIR_STRDUP(schedulertype, "credit"));
1205
                if (nparams)
1206
                    *nparams = XEN_SCHED_CRED_NPARAM;
1207 1208 1209
                break;
            default:
                break;
1210 1211 1212 1213 1214 1215 1216 1217
        }
    }

    return schedulertype;
}

/**
 * xenHypervisorGetSchedulerParameters:
1218 1219
 * @conn: the hypervisor connection
 * @def: domain configuration
1220 1221
 * @params: pointer to scheduler parameters.
 *     This memory area should be allocated before calling.
1222 1223
 * @nparams: this parameter must be at least as large as
 *     the given number of scheduler parameters.
1224 1225 1226 1227 1228 1229 1230
 *     from xenHypervisorGetSchedulerType().
 *
 * Do a low level hypercall to get scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
int
1231 1232
xenHypervisorGetSchedulerParameters(virConnectPtr conn,
                                    virDomainDefPtr def,
1233 1234
                                    virTypedParameterPtr params,
                                    int *nparams)
1235
{
1236
    xenUnifiedPrivatePtr priv = conn->privateData;
1237 1238

    /*
P
Philipp Hahn 已提交
1239
     * Support only hv_versions.dom_interface >=5
1240 1241 1242
     * (Xen3.1.0 or later)
     * TODO: check on Xen 3.0.3
     */
P
Philipp Hahn 已提交
1243
    if (hv_versions.dom_interface < 5) {
1244 1245
        virReportError(VIR_ERR_NO_XEN, "%s",
                       _("unsupported in dom interface < 5"));
1246 1247 1248
        return -1;
    }

P
Philipp Hahn 已提交
1249
    if (hv_versions.hypervisor > 1) {
1250 1251 1252 1253 1254 1255 1256 1257
        xen_op_v2_sys op_sys;
        xen_op_v2_dom op_dom;
        int ret;

        memset(&op_sys, 0, sizeof(op_sys));
        op_sys.cmd = XEN_V2_OP_GETSCHEDULERID;
        ret = xenHypervisorDoV2Sys(priv->handle, &op_sys);
        if (ret < 0)
1258
            return -1;
1259 1260

        switch (op_sys.u.getschedulerid.sched_id){
1261
            case XEN_SCHEDULER_SEDF:
1262
                if (*nparams < XEN_SCHED_SEDF_NPARAM) {
1263 1264
                    virReportError(VIR_ERR_INVALID_ARG,
                                   "%s", _("Invalid parameter count"));
1265 1266 1267
                    return -1;
                }

1268 1269
                /* TODO: Implement for Xen/SEDF */
                TODO
1270
                return -1;
1271 1272 1273
            case XEN_SCHEDULER_CREDIT:
                memset(&op_dom, 0, sizeof(op_dom));
                op_dom.cmd = XEN_V2_OP_SCHEDULER;
1274
                op_dom.domain = (domid_t) def->id;
1275 1276 1277 1278
                op_dom.u.getschedinfo.sched_id = XEN_SCHEDULER_CREDIT;
                op_dom.u.getschedinfo.cmd = XEN_DOMCTL_SCHEDOP_getinfo;
                ret = xenHypervisorDoV2Dom(priv->handle, &op_dom);
                if (ret < 0)
1279
                    return -1;
1280

1281 1282 1283 1284
                if (virTypedParameterAssign(&params[0],
                                            VIR_DOMAIN_SCHEDULER_WEIGHT,
                                            VIR_TYPED_PARAM_UINT,
                                            op_dom.u.getschedinfo.u.credit.weight) < 0)
C
Chris Lalancette 已提交
1285
                    return -1;
1286 1287 1288 1289 1290 1291

                if (*nparams > 1 &&
                    virTypedParameterAssign(&params[1],
                                            VIR_DOMAIN_SCHEDULER_CAP,
                                            VIR_TYPED_PARAM_UINT,
                                            op_dom.u.getschedinfo.u.credit.cap) < 0)
1292
                        return -1;
1293

1294 1295
                if (*nparams > XEN_SCHED_CRED_NPARAM)
                    *nparams = XEN_SCHED_CRED_NPARAM;
1296 1297
                break;
            default:
1298 1299 1300
                virReportError(VIR_ERR_INVALID_ARG,
                               _("Unknown scheduler %d"),
                               op_sys.u.getschedulerid.sched_id);
1301
                return -1;
1302 1303 1304 1305 1306 1307 1308 1309
        }
    }

    return 0;
}

/**
 * xenHypervisorSetSchedulerParameters:
1310 1311
 * @conn: the hypervisor connection
 * @def: domain configuration
1312 1313 1314 1315 1316 1317 1318
 * @nparams:give a number of scheduler setting parameters .
 *
 * Do a low level hypercall to set scheduler parameters
 *
 * Returns 0 or -1 in case of failure
 */
int
1319 1320
xenHypervisorSetSchedulerParameters(virConnectPtr conn,
                                    virDomainDefPtr def,
1321 1322
                                    virTypedParameterPtr params,
                                    int nparams)
1323
{
1324
    size_t i;
1325
    unsigned int val;
1326
    xenUnifiedPrivatePtr priv = conn->privateData;
1327
    char buf[256];
1328

1329 1330 1331
    if (nparams == 0) {
        /* nothing to do, exit early */
        return 0;
1332 1333
    }

1334 1335 1336 1337 1338 1339
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
1340 1341
        return -1;

1342
    /*
P
Philipp Hahn 已提交
1343
     * Support only hv_versions.dom_interface >=5
1344 1345 1346
     * (Xen3.1.0 or later)
     * TODO: check on Xen 3.0.3
     */
P
Philipp Hahn 已提交
1347
    if (hv_versions.dom_interface < 5) {
1348 1349
        virReportError(VIR_ERR_NO_XEN, "%s",
                       _("unsupported in dom interface < 5"));
1350 1351 1352
        return -1;
    }

P
Philipp Hahn 已提交
1353
    if (hv_versions.hypervisor > 1) {
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        xen_op_v2_sys op_sys;
        xen_op_v2_dom op_dom;
        int ret;

        memset(&op_sys, 0, sizeof(op_sys));
        op_sys.cmd = XEN_V2_OP_GETSCHEDULERID;
        ret = xenHypervisorDoV2Sys(priv->handle, &op_sys);
        if (ret == -1) return -1;

        switch (op_sys.u.getschedulerid.sched_id){
        case XEN_SCHEDULER_SEDF:
            /* TODO: Implement for Xen/SEDF */
            TODO
1367
            return -1;
1368 1369 1370
        case XEN_SCHEDULER_CREDIT: {
            memset(&op_dom, 0, sizeof(op_dom));
            op_dom.cmd = XEN_V2_OP_SCHEDULER;
1371
            op_dom.domain = (domid_t) def->id;
1372 1373 1374 1375
            op_dom.u.getschedinfo.sched_id = XEN_SCHEDULER_CREDIT;
            op_dom.u.getschedinfo.cmd = XEN_DOMCTL_SCHEDOP_putinfo;

            /*
1376 1377
             * credit scheduler parameters
             * following values do not change the parameters
1378 1379 1380 1381 1382
             */
            op_dom.u.getschedinfo.u.credit.weight = 0;
            op_dom.u.getschedinfo.u.credit.cap    = (uint16_t)~0U;

            for (i = 0; i < nparams; i++) {
1383
                memset(&buf, 0, sizeof(buf));
1384
                if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_WEIGHT)) {
1385 1386
                    val = params[i].value.ui;
                    if ((val < 1) || (val > USHRT_MAX)) {
1387 1388 1389
                        virReportError(VIR_ERR_INVALID_ARG,
                                       _("Credit scheduler weight parameter (%d) "
                                         "is out of range (1-65535)"), val);
1390
                        return -1;
1391
                    }
1392
                    op_dom.u.getschedinfo.u.credit.weight = val;
1393
                } else if (STREQ(params[i].field, VIR_DOMAIN_SCHEDULER_CAP)) {
1394
                    val = params[i].value.ui;
1395
                    if (val >= USHRT_MAX) {
1396 1397 1398
                        virReportError(VIR_ERR_INVALID_ARG,
                                       _("Credit scheduler cap parameter (%d) is "
                                         "out of range (0-65534)"), val);
1399
                        return -1;
1400
                    }
1401
                    op_dom.u.getschedinfo.u.credit.cap = val;
1402
                }
1403 1404 1405 1406
            }

            ret = xenHypervisorDoV2Dom(priv->handle, &op_dom);
            if (ret < 0)
1407
                return -1;
1408
            break;
1409
        }
1410
        default:
1411 1412 1413
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Unknown scheduler %d"),
                           op_sys.u.getschedulerid.sched_id);
1414 1415 1416
            return -1;
        }
    }
1417

1418 1419 1420
    return 0;
}

1421 1422

int
1423 1424
xenHypervisorDomainBlockStats(virConnectPtr conn,
                              virDomainDefPtr def,
1425 1426
                              const char *path,
                              struct _virDomainBlockStats *stats)
1427
{
1428
#ifdef __linux__
1429
    xenUnifiedPrivatePtr priv = conn->privateData;
D
Daniel P. Berrange 已提交
1430
    int ret;
1431

D
Daniel P. Berrange 已提交
1432 1433
    xenUnifiedLock(priv);
    /* Need to lock because it hits the xenstore handle :-( */
1434
    ret = xenLinuxDomainBlockStats(priv, def, path, stats);
D
Daniel P. Berrange 已提交
1435 1436
    xenUnifiedUnlock(priv);
    return ret;
1437
#else
1438 1439
    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("block statistics not supported on this platform"));
1440
    return -1;
1441
#endif
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
}

/* Paths have the form vif<domid>.<n> (this interface checks that
 * <domid> is the real domain ID and returns an error if not).
 *
 * In future we may allow you to query bridge stats (virbrX or
 * xenbrX), but that will probably be through a separate
 * virNetwork interface, as yet not decided.
 */
int
1452
xenHypervisorDomainInterfaceStats(virDomainDefPtr def,
1453 1454
                                  const char *path,
                                  struct _virDomainInterfaceStats *stats)
1455
{
1456
#ifdef __linux__
1457 1458
    int rqdomid, device;

1459 1460 1461
    /* Verify that the vif requested is one belonging to the current
     * domain.
     */
1462
    if (sscanf(path, "vif%d.%d", &rqdomid, &device) != 2) {
1463 1464
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path, should be vif<domid>.<n>."));
1465 1466
        return -1;
    }
1467
    if (rqdomid != def->id) {
1468 1469
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid path, vif<domid> should match this domain ID"));
1470 1471 1472
        return -1;
    }

1473
    return linuxDomainInterfaceStats(path, stats);
1474
#else
1475 1476
    virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                   _("/proc/net/dev: Interface not found"));
1477
    return -1;
1478
#endif
1479 1480
}

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492

/**
 * virXen_setmaxmem:
 * @handle: the hypervisor handle
 * @id: the domain id
 * @memory: the amount of memory in kilobytes
 *
 * Do a low level hypercall to change the max memory amount
 *
 * Returns 0 or -1 in case of failure
 */
static int
1493
virXen_setmaxmem(int handle, int id, unsigned long memory)
1494 1495 1496
{
    int ret = -1;

P
Philipp Hahn 已提交
1497
    if (hv_versions.hypervisor > 1) {
1498 1499 1500
        xen_op_v2_dom op;

        memset(&op, 0, sizeof(op));
1501 1502
        op.cmd = XEN_V2_OP_SETMAXMEM;
        op.domain = (domid_t) id;
P
Philipp Hahn 已提交
1503
        if (hv_versions.dom_interface < 5)
1504 1505 1506
            op.u.setmaxmem.maxmem = memory;
        else
            op.u.setmaxmemd5.maxmem = memory;
1507
        ret = xenHypervisorDoV2Dom(handle, &op);
P
Philipp Hahn 已提交
1508
    } else if (hv_versions.hypervisor == 1) {
1509 1510 1511
        xen_op_v1 op;

        memset(&op, 0, sizeof(op));
1512 1513 1514 1515
        op.cmd = XEN_V1_OP_SETMAXMEM;
        op.u.setmaxmem.domain = (domid_t) id;
        op.u.setmaxmem.maxmem = memory;
        ret = xenHypervisorDoV1Op(handle, &op);
P
Philipp Hahn 已提交
1516
    } else if (hv_versions.hypervisor == 0) {
1517
        xen_op_v0 op;
1518 1519

        memset(&op, 0, sizeof(op));
1520 1521 1522 1523
        op.cmd = XEN_V0_OP_SETMAXMEM;
        op.u.setmaxmem.domain = (domid_t) id;
        op.u.setmaxmem.maxmem = memory;
        ret = xenHypervisorDoV0Op(handle, &op);
1524
    }
1525
    return ret;
1526 1527 1528 1529 1530 1531 1532 1533 1534
}


/**
 * virXen_setvcpumap:
 * @handle: the hypervisor handle
 * @id: the domain id
 * @vcpu: the vcpu to map
 * @cpumap: the bitmap for this vcpu
1535
 * @maplen: the size of the bitmap in bytes
1536 1537 1538 1539 1540 1541
 *
 * Do a low level hypercall to change the pinning for vcpu
 *
 * Returns 0 or -1 in case of failure
 */
static int
1542 1543 1544 1545 1546
virXen_setvcpumap(int handle,
                  int id,
                  unsigned int vcpu,
                  unsigned char * cpumap,
                  int maplen)
1547 1548
{
    int ret = -1;
1549 1550 1551
    unsigned char *new = NULL;
    unsigned char *bitmap = NULL;
    uint32_t nr_cpus;
1552

P
Philipp Hahn 已提交
1553
    if (hv_versions.hypervisor > 1) {
1554 1555
        xen_op_v2_dom op;

1556
        if (lock_pages(cpumap, maplen) < 0)
1557
            return -1;
1558

1559
        memset(&op, 0, sizeof(op));
1560 1561
        op.cmd = XEN_V2_OP_SETVCPUMAP;
        op.domain = (domid_t) id;
1562 1563 1564 1565

        /* The allocated memory to cpumap must be 'sizeof(uint64_t)' byte *
         * for Xen, and also nr_cpus must be 'sizeof(uint64_t) * 8'       */
        if (maplen < 8) {
1566
            if (VIR_ALLOC_N(new, sizeof(uint64_t)) < 0)
1567
                return -1;
1568 1569 1570 1571 1572 1573 1574 1575
            memcpy(new, cpumap, maplen);
            bitmap = new;
            nr_cpus = sizeof(uint64_t) * 8;
        } else {
            bitmap = cpumap;
            nr_cpus = maplen * 8;
        }

P
Philipp Hahn 已提交
1576
        if (hv_versions.dom_interface < 5) {
1577
            op.u.setvcpumap.vcpu = vcpu;
1578 1579
            op.u.setvcpumap.cpumap.bitmap = bitmap;
            op.u.setvcpumap.cpumap.nr_cpus = nr_cpus;
1580 1581
        } else {
            op.u.setvcpumapd5.vcpu = vcpu;
1582 1583
            op.u.setvcpumapd5.cpumap.bitmap.v = bitmap;
            op.u.setvcpumapd5.cpumap.nr_cpus = nr_cpus;
1584
        }
1585
        ret = xenHypervisorDoV2Dom(handle, &op);
1586
        VIR_FREE(new);
1587

1588
        if (unlock_pages(cpumap, maplen) < 0)
1589
            ret = -1;
1590
    } else {
1591
        cpumap_t xen_cpumap; /* limited to 64 CPUs in old hypervisors */
E
Eric Blake 已提交
1592
        char buf[8] = "";
1593

E
Eric Blake 已提交
1594
        if (maplen > sizeof(cpumap_t) || sizeof(cpumap_t) != sizeof(uint64_t))
1595
            return -1;
E
Eric Blake 已提交
1596 1597 1598
        /* Supply trailing 0s if user's input array was short */
        memcpy(buf, cpumap, maplen);
        xen_cpumap = virReadBufInt64LE(buf);
1599

P
Philipp Hahn 已提交
1600
        if (hv_versions.hypervisor == 1) {
1601 1602 1603 1604 1605 1606 1607 1608
            xen_op_v1 op;

            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V1_OP_SETVCPUMAP;
            op.u.setvcpumap.domain = (domid_t) id;
            op.u.setvcpumap.vcpu = vcpu;
            op.u.setvcpumap.cpumap = xen_cpumap;
            ret = xenHypervisorDoV1Op(handle, &op);
P
Philipp Hahn 已提交
1609
        } else if (hv_versions.hypervisor == 0) {
1610 1611 1612 1613 1614 1615 1616 1617 1618
            xen_op_v0 op;

            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V0_OP_SETVCPUMAP;
            op.u.setvcpumap.domain = (domid_t) id;
            op.u.setvcpumap.vcpu = vcpu;
            op.u.setvcpumap.cpumap = xen_cpumap;
            ret = xenHypervisorDoV0Op(handle, &op);
        }
1619
    }
1620
    return ret;
1621
}
1622

1623

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
/**
 * virXen_getvcpusinfo:
 * @handle: the hypervisor handle
 * @id: the domain id
 * @vcpu: the vcpu to map
 * @cpumap: the bitmap for this vcpu
 * @maplen: the size of the bitmap in bytes
 *
 * Do a low level hypercall to change the pinning for vcpu
 *
 * Returns 0 or -1 in case of failure
 */
static int
1637 1638 1639 1640 1641 1642
virXen_getvcpusinfo(int handle,
                    int id,
                    unsigned int vcpu,
                    virVcpuInfoPtr ipt,
                    unsigned char *cpumap,
                    int maplen)
1643 1644 1645
{
    int ret = -1;

P
Philipp Hahn 已提交
1646
    if (hv_versions.hypervisor > 1) {
1647 1648 1649
        xen_op_v2_dom op;

        memset(&op, 0, sizeof(op));
1650 1651
        op.cmd = XEN_V2_OP_GETVCPUINFO;
        op.domain = (domid_t) id;
P
Philipp Hahn 已提交
1652
        if (hv_versions.dom_interface < 5)
1653 1654 1655
            op.u.getvcpuinfo.vcpu = (uint16_t) vcpu;
        else
            op.u.getvcpuinfod5.vcpu = (uint16_t) vcpu;
1656
        ret = xenHypervisorDoV2Dom(handle, &op);
1657

1658
        if (ret < 0)
1659
            return -1;
1660
        ipt->number = vcpu;
P
Philipp Hahn 已提交
1661
        if (hv_versions.dom_interface < 5) {
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
            if (op.u.getvcpuinfo.online) {
                if (op.u.getvcpuinfo.running)
                    ipt->state = VIR_VCPU_RUNNING;
                if (op.u.getvcpuinfo.blocked)
                    ipt->state = VIR_VCPU_BLOCKED;
            } else
                ipt->state = VIR_VCPU_OFFLINE;

            ipt->cpuTime = op.u.getvcpuinfo.cpu_time;
            ipt->cpu = op.u.getvcpuinfo.online ? (int)op.u.getvcpuinfo.cpu : -1;
        } else {
            if (op.u.getvcpuinfod5.online) {
                if (op.u.getvcpuinfod5.running)
                    ipt->state = VIR_VCPU_RUNNING;
                if (op.u.getvcpuinfod5.blocked)
                    ipt->state = VIR_VCPU_BLOCKED;
            } else
                ipt->state = VIR_VCPU_OFFLINE;

            ipt->cpuTime = op.u.getvcpuinfod5.cpu_time;
            ipt->cpu = op.u.getvcpuinfod5.online ? (int)op.u.getvcpuinfod5.cpu : -1;
1683 1684
        }
        if ((cpumap != NULL) && (maplen > 0)) {
1685
            if (lock_pages(cpumap, maplen) < 0)
1686
                return -1;
1687

1688
            memset(cpumap, 0, maplen);
1689 1690 1691
            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V2_OP_GETVCPUMAP;
            op.domain = (domid_t) id;
P
Philipp Hahn 已提交
1692
            if (hv_versions.dom_interface < 5) {
1693 1694 1695 1696 1697 1698 1699 1700
                op.u.getvcpumap.vcpu = vcpu;
                op.u.getvcpumap.cpumap.bitmap = cpumap;
                op.u.getvcpumap.cpumap.nr_cpus = maplen * 8;
            } else {
                op.u.getvcpumapd5.vcpu = vcpu;
                op.u.getvcpumapd5.cpumap.bitmap.v = cpumap;
                op.u.getvcpumapd5.cpumap.nr_cpus = maplen * 8;
            }
1701
            ret = xenHypervisorDoV2Dom(handle, &op);
1702
            if (unlock_pages(cpumap, maplen) < 0)
1703 1704
                ret = -1;
        }
1705
    } else {
1706 1707 1708 1709 1710
        int mapl = maplen;
        int cpu;

        if (maplen > (int)sizeof(cpumap_t))
            mapl = (int)sizeof(cpumap_t);
1711

P
Philipp Hahn 已提交
1712
        if (hv_versions.hypervisor == 1) {
1713 1714 1715 1716 1717 1718 1719 1720
            xen_op_v1 op;

            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V1_OP_GETVCPUINFO;
            op.u.getvcpuinfo.domain = (domid_t) id;
            op.u.getvcpuinfo.vcpu = vcpu;
            ret = xenHypervisorDoV1Op(handle, &op);
            if (ret < 0)
1721
                return -1;
1722
            ipt->number = vcpu;
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
            if (op.u.getvcpuinfo.online) {
                if (op.u.getvcpuinfo.running) ipt->state = VIR_VCPU_RUNNING;
                if (op.u.getvcpuinfo.blocked) ipt->state = VIR_VCPU_BLOCKED;
            }
            else ipt->state = VIR_VCPU_OFFLINE;
            ipt->cpuTime = op.u.getvcpuinfo.cpu_time;
            ipt->cpu = op.u.getvcpuinfo.online ? (int)op.u.getvcpuinfo.cpu : -1;
            if ((cpumap != NULL) && (maplen > 0)) {
                for (cpu = 0; cpu < (mapl * 8); cpu++) {
                    if (op.u.getvcpuinfo.cpumap & ((uint64_t)1<<cpu))
                        VIR_USE_CPU(cpumap, cpu);
                }
            }
P
Philipp Hahn 已提交
1736
        } else if (hv_versions.hypervisor == 0) {
1737 1738 1739 1740 1741 1742 1743 1744
            xen_op_v1 op;

            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V0_OP_GETVCPUINFO;
            op.u.getvcpuinfo.domain = (domid_t) id;
            op.u.getvcpuinfo.vcpu = vcpu;
            ret = xenHypervisorDoV0Op(handle, &op);
            if (ret < 0)
1745
                return -1;
1746
            ipt->number = vcpu;
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
            if (op.u.getvcpuinfo.online) {
                if (op.u.getvcpuinfo.running) ipt->state = VIR_VCPU_RUNNING;
                if (op.u.getvcpuinfo.blocked) ipt->state = VIR_VCPU_BLOCKED;
            }
            else ipt->state = VIR_VCPU_OFFLINE;
            ipt->cpuTime = op.u.getvcpuinfo.cpu_time;
            ipt->cpu = op.u.getvcpuinfo.online ? (int)op.u.getvcpuinfo.cpu : -1;
            if ((cpumap != NULL) && (maplen > 0)) {
                for (cpu = 0; cpu < (mapl * 8); cpu++) {
                    if (op.u.getvcpuinfo.cpumap & ((uint64_t)1<<cpu))
                        VIR_USE_CPU(cpumap, cpu);
                }
            }
        }
1761
    }
1762
    return ret;
1763
}
1764

1765 1766
/**
 * xenHypervisorInit:
P
Philipp Hahn 已提交
1767 1768
 * @override_versions: pointer to optional struct xenHypervisorVersions with
 *     version information used instead of automatic version detection.
1769 1770 1771
 *
 * Initialize the hypervisor layer. Try to detect the kind of interface
 * used i.e. pre or post changeset 10277
P
Philipp Hahn 已提交
1772 1773
 *
 * Returns 0 or -1 in case of failure
1774
 */
1775
int
P
Philipp Hahn 已提交
1776
xenHypervisorInit(struct xenHypervisorVersions *override_versions)
1777
{
1778
    int fd, ret, cmd, errcode;
1779
    hypercall_t hc;
1780
    v0_hypercall_t v0_hc;
1781
    xen_getdomaininfo info;
D
Daniel Veillard 已提交
1782
    virVcpuInfoPtr ipt = NULL;
1783

1784 1785 1786 1787
    /* Compile regular expressions used by xenHypervisorGetCapabilities.
     * Note that errors here are really internal errors since these
     * regexps should never fail to compile.
     */
1788
    errcode = regcomp(&flags_hvm_rec, flags_hvm_re, REG_EXTENDED);
1789 1790
    if (errcode != 0) {
        char error[100];
1791
        regerror(errcode, &flags_hvm_rec, error, sizeof(error));
1792
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", error);
1793 1794
        return -1;
    }
1795
    errcode = regcomp(&flags_pae_rec, flags_pae_re, REG_EXTENDED);
1796 1797
    if (errcode != 0) {
        char error[100];
1798 1799
        regerror(errcode, &flags_pae_rec, error, sizeof(error));
        regfree(&flags_hvm_rec);
1800
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", error);
1801 1802
        return -1;
    }
1803
    errcode = regcomp(&xen_cap_rec, xen_cap_re, REG_EXTENDED);
1804 1805
    if (errcode != 0) {
        char error[100];
1806 1807 1808
        regerror(errcode, &xen_cap_rec, error, sizeof(error));
        regfree(&flags_pae_rec);
        regfree(&flags_hvm_rec);
1809
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", error);
1810 1811 1812
        return -1;
    }

P
Philipp Hahn 已提交
1813 1814 1815 1816 1817
    if (override_versions) {
      hv_versions = *override_versions;
      return 0;
    }

1818
    /* Xen hypervisor version detection begins. */
1819 1820
    ret = open(XEN_HYPERVISOR_SOCKET, O_RDWR);
    if (ret < 0) {
P
Philipp Hahn 已提交
1821
        hv_versions.hypervisor = -1;
1822
        return -1;
1823 1824 1825
    }
    fd = ret;

1826 1827 1828 1829
    /*
     * The size of the hypervisor call block changed July 2006
     * this detect if we are using the new or old hypercall_t structure
     */
1830 1831 1832 1833 1834 1835 1836 1837
    hc.op = __HYPERVISOR_xen_version;
    hc.arg[0] = (unsigned long) XENVER_version;
    hc.arg[1] = 0;

    cmd = IOCTL_PRIVCMD_HYPERCALL;
    ret = ioctl(fd, cmd, (unsigned long) &hc);

    if ((ret != -1) && (ret != 0)) {
1838
        VIR_DEBUG("Using new hypervisor call: %X", ret);
P
Philipp Hahn 已提交
1839
        hv_versions.hv = ret;
1840 1841
        xen_ioctl_hypercall_cmd = cmd;
        goto detect_v2;
1842
    }
1843

1844
#ifndef __sun
1845 1846 1847 1848 1849 1850 1851 1852
    /*
     * check if the old hypercall are actually working
     */
    v0_hc.op = __HYPERVISOR_xen_version;
    v0_hc.arg[0] = (unsigned long) XENVER_version;
    v0_hc.arg[1] = 0;
    cmd = _IOC(_IOC_NONE, 'P', 0, sizeof(v0_hypercall_t));
    ret = ioctl(fd, cmd, (unsigned long) &v0_hc);
1853
    if ((ret != -1) && (ret != 0)) {
1854
        VIR_DEBUG("Using old hypervisor call: %X", ret);
P
Philipp Hahn 已提交
1855
        hv_versions.hv = ret;
1856
        xen_ioctl_hypercall_cmd = cmd;
P
Philipp Hahn 已提交
1857
        hv_versions.hypervisor = 0;
1858
        goto done;
1859
    }
1860
#endif
1861

1862
    /*
R
Richard W.M. Jones 已提交
1863
     * we failed to make any hypercall
1864 1865
     */

P
Philipp Hahn 已提交
1866
    hv_versions.hypervisor = -1;
1867 1868 1869
    virReportSystemError(errno,
                         _("Unable to issue hypervisor ioctl %lu"),
                         (unsigned long)IOCTL_PRIVCMD_HYPERCALL);
1870
    VIR_FORCE_CLOSE(fd);
1871
    return -1;
1872

1873
 detect_v2:
1874 1875 1876 1877 1878
    /*
     * The hypercalls were refactored into 3 different section in August 2006
     * Try to detect if we are running a version post 3.0.2 with the new ones
     * or the old ones
     */
P
Philipp Hahn 已提交
1879
    hv_versions.hypervisor = 2;
1880

1881
    if (VIR_ALLOC(ipt) < 0)
1882
        return -1;
1883
    /* Currently consider RHEL5.0 Fedora7, xen-3.1, and xen-unstable */
P
Philipp Hahn 已提交
1884
    hv_versions.sys_interface = 2; /* XEN_SYSCTL_INTERFACE_VERSION */
1885
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
1886
        /* RHEL 5.0 */
P
Philipp Hahn 已提交
1887
        hv_versions.dom_interface = 3; /* XEN_DOMCTL_INTERFACE_VERSION */
1888
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
1889
            VIR_DEBUG("Using hypervisor call v2, sys ver2 dom ver3");
1890 1891 1892
            goto done;
        }
        /* Fedora 7 */
P
Philipp Hahn 已提交
1893
        hv_versions.dom_interface = 4; /* XEN_DOMCTL_INTERFACE_VERSION */
1894
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
1895
            VIR_DEBUG("Using hypervisor call v2, sys ver2 dom ver4");
1896 1897 1898 1899
            goto done;
        }
    }

P
Philipp Hahn 已提交
1900
    hv_versions.sys_interface = 3; /* XEN_SYSCTL_INTERFACE_VERSION */
1901
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
1902
        /* xen-3.1 */
P
Philipp Hahn 已提交
1903
        hv_versions.dom_interface = 5; /* XEN_DOMCTL_INTERFACE_VERSION */
1904
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
1905
            VIR_DEBUG("Using hypervisor call v2, sys ver3 dom ver5");
1906 1907
            goto done;
        }
1908
    }
1909

P
Philipp Hahn 已提交
1910
    hv_versions.sys_interface = 4; /* XEN_SYSCTL_INTERFACE_VERSION */
1911
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
1912
        /* Fedora 8 */
P
Philipp Hahn 已提交
1913
        hv_versions.dom_interface = 5; /* XEN_DOMCTL_INTERFACE_VERSION */
1914
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
1915
            VIR_DEBUG("Using hypervisor call v2, sys ver4 dom ver5");
1916 1917 1918 1919
            goto done;
        }
    }

P
Philipp Hahn 已提交
1920
    hv_versions.sys_interface = 6; /* XEN_SYSCTL_INTERFACE_VERSION */
1921 1922
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
        /* Xen 3.2, Fedora 9 */
P
Philipp Hahn 已提交
1923
        hv_versions.dom_interface = 5; /* XEN_DOMCTL_INTERFACE_VERSION */
1924
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
1925
            VIR_DEBUG("Using hypervisor call v2, sys ver6 dom ver5");
1926 1927
            goto done;
        }
J
Jim Fehlig 已提交
1928 1929 1930
    }

    /* Xen 4.0 */
P
Philipp Hahn 已提交
1931
    hv_versions.sys_interface = 7; /* XEN_SYSCTL_INTERFACE_VERSION */
J
Jim Fehlig 已提交
1932
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
P
Philipp Hahn 已提交
1933
        hv_versions.dom_interface = 6; /* XEN_DOMCTL_INTERFACE_VERSION */
1934
        VIR_DEBUG("Using hypervisor call v2, sys ver7 dom ver6");
J
Jim Fehlig 已提交
1935
        goto done;
1936 1937
    }

J
Jim Fehlig 已提交
1938 1939 1940
    /* Xen 4.1
     * sysctl version 8 -> xen-unstable c/s 21118:28e5409e3fb3
     * domctl version 7 -> xen-unstable c/s 21212:de94884a669c
J
Jim Fehlig 已提交
1941
     * domctl version 8 -> xen-unstable c/s 23874:651aed73b39c
J
Jim Fehlig 已提交
1942
     */
P
Philipp Hahn 已提交
1943
    hv_versions.sys_interface = 8; /* XEN_SYSCTL_INTERFACE_VERSION */
J
Jim Fehlig 已提交
1944
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
P
Philipp Hahn 已提交
1945
        hv_versions.dom_interface = 7; /* XEN_DOMCTL_INTERFACE_VERSION */
J
Jim Fehlig 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
            VIR_DEBUG("Using hypervisor call v2, sys ver8 dom ver7");
            goto done;
        }
        hv_versions.dom_interface = 8; /* XEN_DOMCTL_INTERFACE_VERSION */
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
            VIR_DEBUG("Using hypervisor call v2, sys ver8 dom ver8");
            goto done;
        }
J
Jim Fehlig 已提交
1955 1956
    }

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
    /* Xen 4.2
     * sysctl version 9 -> xen-unstable c/s 24102:dc8e55c90604
     * domctl version 8 -> unchanged from Xen 4.1
     */
    hv_versions.sys_interface = 9; /* XEN_SYSCTL_INTERFACE_VERSION */
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
        hv_versions.dom_interface = 8; /* XEN_DOMCTL_INTERFACE_VERSION */
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0){
            VIR_DEBUG("Using hypervisor call v2, sys ver9 dom ver8");
            goto done;
        }
    }
1969

1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    /* Xen 4.3
     * sysctl version 10 -> xen-unstable commit bec8f17e
     * domctl version 9 -> xen-unstable commit 65c9792d
     */
    hv_versions.sys_interface = 10; /* XEN_SYSCTL_INTERFACE_VERSION */
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
        hv_versions.dom_interface = 9; /* XEN_DOMCTL_INTERFACE_VERSION */
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0) {
            VIR_DEBUG("Using hypervisor call v2, sys ver10 dom ver9");
            goto done;
        }
    }

J
Jim Fehlig 已提交
1983 1984 1985 1986 1987 1988 1989
    hv_versions.hypervisor = 1;
    hv_versions.sys_interface = -1;
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
        VIR_DEBUG("Using hypervisor call v1");
        goto done;
    }

1990
    /*
R
Richard W.M. Jones 已提交
1991
     * we failed to make the getdomaininfolist hypercall
1992
     */
P
Philipp Hahn 已提交
1993
    hv_versions.hypervisor = -1;
1994 1995 1996 1997
    virReportSystemError(errno,
                         _("Unable to issue hypervisor ioctl %lu"),
                         (unsigned long)IOCTL_PRIVCMD_HYPERCALL);
    VIR_DEBUG("Failed to find any Xen hypervisor method");
1998
    VIR_FORCE_CLOSE(fd);
1999
    VIR_FREE(ipt);
2000
    return -1;
2001

2002
 done:
2003
    VIR_FORCE_CLOSE(fd);
2004
    VIR_FREE(ipt);
2005
    return 0;
2006 2007
}

2008

2009 2010
static int xenHypervisorOnceInit(void)
{
2011 2012 2013 2014 2015
    return xenHypervisorInit(NULL);
}

VIR_ONCE_GLOBAL_INIT(xenHypervisor)

2016 2017
/**
 * xenHypervisorOpen:
2018 2019 2020
 * @conn: pointer to the connection block
 * @name: URL for the target, NULL for local
 * @flags: combination of virDrvOpenFlag(s)
2021 2022 2023
 *
 * Connects to the Xen hypervisor.
 *
2024
 * Returns 0 or -1 in case of error.
2025
 */
2026
int
2027
xenHypervisorOpen(virConnectPtr conn,
2028
                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
2029
                  unsigned int flags)
2030
{
2031
    int ret;
2032
    xenUnifiedPrivatePtr priv = conn->privateData;
2033

2034
    virCheckFlags(VIR_CONNECT_RO, -1);
E
Eric Blake 已提交
2035

2036
    if (xenHypervisorInitialize() < 0)
2037
        return -1;
2038

2039
    priv->handle = -1;
2040

2041
    ret = open(XEN_HYPERVISOR_SOCKET, O_RDWR);
2042
    if (ret < 0) {
2043
        virReportError(VIR_ERR_NO_XEN, "%s", XEN_HYPERVISOR_SOCKET);
2044
        return -1;
2045
    }
2046 2047

    priv->handle = ret;
2048

2049
    return 0;
2050 2051 2052 2053
}

/**
 * xenHypervisorClose:
2054
 * @conn: pointer to the connection block
2055 2056 2057 2058 2059
 *
 * Close the connection to the Xen hypervisor.
 *
 * Returns 0 in case of success or -1 in case of error.
 */
2060
int
2061
xenHypervisorClose(virConnectPtr conn)
2062
{
2063
    int ret;
2064
    xenUnifiedPrivatePtr priv = conn->privateData;
2065

2066
    ret = VIR_CLOSE(priv->handle);
2067
    if (ret < 0)
2068
        return -1;
2069

2070
    return 0;
2071 2072 2073
}


2074 2075
/**
 * xenHypervisorGetVersion:
2076 2077
 * @conn: pointer to the connection block
 * @hvVer: where to store the version
2078 2079 2080
 *
 * Call the hypervisor to extracts his own internal API version
 *
2081
 * Returns 0 in case of success, -1 in case of error
2082
 */
2083
int
2084
xenHypervisorGetVersion(virConnectPtr conn ATTRIBUTE_UNUSED, unsigned long *hvVer)
2085
{
P
Philipp Hahn 已提交
2086
    *hvVer = (hv_versions.hv >> 16) * 1000000 + (hv_versions.hv & 0xFFFF) * 1000;
2087
    return 0;
2088 2089
}

2090
struct guest_arch {
2091
    virArch arch;
2092 2093 2094 2095 2096 2097 2098 2099
    int hvm;
    int pae;
    int nonpae;
    int ia64_be;
};


static virCapsPtr
2100
xenHypervisorBuildCapabilities(virConnectPtr conn, virArch hostarch,
2101
                               int host_pae,
2102
                               const char *hvm_type,
2103
                               struct guest_arch *guest_archs,
2104 2105
                               int nr_guest_archs)
{
2106
    virCapsPtr caps;
2107
    size_t i;
P
Philipp Hahn 已提交
2108 2109
    int hv_major = hv_versions.hv >> 16;
    int hv_minor = hv_versions.hv & 0xFFFF;
2110

2111
    if ((caps = virCapabilitiesNew(hostarch, 1, 1)) == NULL)
2112
        goto no_memory;
2113

2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
    if (hvm_type && STRNEQ(hvm_type, "") &&
        virCapabilitiesAddHostFeature(caps, hvm_type) < 0)
        goto no_memory;
    if (host_pae &&
        virCapabilitiesAddHostFeature(caps, "pae") < 0)
        goto no_memory;


    if (virCapabilitiesAddHostMigrateTransport(caps,
                                               "xenmigr") < 0)
        goto no_memory;


P
Philipp Hahn 已提交
2127
    if (hv_versions.sys_interface >= SYS_IFACE_MIN_VERS_NUMA && conn != NULL) {
2128
        if (xenDaemonNodeGetTopology(conn, caps) != 0) {
2129
            virObjectUnref(caps);
2130 2131 2132 2133 2134 2135
            return NULL;
        }
    }

    for (i = 0; i < nr_guest_archs; ++i) {
        virCapsGuestPtr guest;
2136 2137 2138
        char const *const xen_machines[] = {guest_archs[i].hvm ? "xenfv" : "xenpv"};
        virCapsGuestMachinePtr *machines;

2139
        if ((machines = virCapabilitiesAllocMachines(xen_machines, 1)) == NULL)
2140
            goto no_memory;
2141 2142 2143

        if ((guest = virCapabilitiesAddGuest(caps,
                                             guest_archs[i].hvm ? "hvm" : "xen",
2144 2145
                                             guest_archs[i].arch,
                                             (hostarch == VIR_ARCH_X86_64 ?
2146 2147 2148 2149 2150 2151
                                              "/usr/lib64/xen/bin/qemu-dm" :
                                              "/usr/lib/xen/bin/qemu-dm"),
                                             (guest_archs[i].hvm ?
                                              "/usr/lib/xen/boot/hvmloader" :
                                              NULL),
                                             1,
2152 2153
                                             machines)) == NULL) {
            virCapabilitiesFreeMachines(machines, 1);
2154
            goto no_memory;
2155
        }
2156
        machines = NULL;
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192

        if (virCapabilitiesAddGuestDomain(guest,
                                          "xen",
                                          NULL,
                                          NULL,
                                          0,
                                          NULL) == NULL)
            goto no_memory;

        if (guest_archs[i].pae &&
            virCapabilitiesAddGuestFeature(guest,
                                           "pae",
                                           1,
                                           0) == NULL)
            goto no_memory;

        if (guest_archs[i].nonpae &&
            virCapabilitiesAddGuestFeature(guest,
                                           "nonpae",
                                           1,
                                           0) == NULL)
            goto no_memory;

        if (guest_archs[i].ia64_be &&
            virCapabilitiesAddGuestFeature(guest,
                                           "ia64_be",
                                           1,
                                           0) == NULL)
            goto no_memory;

        if (guest_archs[i].hvm) {
            if (virCapabilitiesAddGuestFeature(guest,
                                               "acpi",
                                               1, 1) == NULL)
                goto no_memory;

2193
            /* In Xen 3.1.0, APIC is always on and can't be toggled */
2194 2195 2196 2197 2198 2199 2200
            if (virCapabilitiesAddGuestFeature(guest,
                                               "apic",
                                               1,
                                               (hv_major > 3 &&
                                                hv_minor > 0 ?
                                                0 : 1)) == NULL)
                goto no_memory;
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210

            /* Xen 3.3.x and beyond supports enabling/disabling
             * hardware assisted paging.  Default is off.
             */
            if ((hv_major == 3 && hv_minor >= 3) || (hv_major > 3))
                if (virCapabilitiesAddGuestFeature(guest,
                                                   "hap",
                                                   0,
                                                   1) == NULL)
                    goto no_memory;
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

            /* Xen 3.4.x and beyond supports the Viridian (Hyper-V)
             * enlightenment interface.  Default is off.
             */
            if ((hv_major == 3 && hv_minor >= 4) || (hv_major > 3))
                if (virCapabilitiesAddGuestFeature(guest,
                                                   "viridian",
                                                   0,
                                                   1) == NULL)
                    goto no_memory;
2221
        }
2222

2223 2224 2225 2226 2227
    }

    return caps;

 no_memory:
2228
    virObjectUnref(caps);
2229 2230 2231
    return NULL;
}

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
#ifdef __sun

static int
get_cpu_flags(virConnectPtr conn, const char **hvm, int *pae, int *longmode)
{
    struct {
        uint32_t r_eax, r_ebx, r_ecx, r_edx;
    } regs;

    char tmpbuf[20];
    int ret = 0;
    int fd;

    /* returns -1, errno 22 if in 32-bit mode */
    *longmode = (sysinfo(SI_ARCHITECTURE_64, tmpbuf, sizeof(tmpbuf)) != -1);

    if ((fd = open("/dev/cpu/self/cpuid", O_RDONLY)) == -1 ||
        pread(fd, &regs, sizeof(regs), 0) != sizeof(regs)) {
2250
        virReportSystemError(errno, "%s", _("could not read CPU flags"));
2251 2252 2253 2254 2255 2256 2257
        goto out;
    }

    *pae = 0;
    *hvm = "";

    if (STREQLEN((const char *)&regs.r_ebx, "AuthcAMDenti", 12)) {
2258
        if (pread(fd, &regs, sizeof(regs), 0x80000001) == sizeof(regs)) {
2259 2260 2261 2262 2263 2264 2265 2266
            /* Read secure virtual machine bit (bit 2 of ECX feature ID) */
            if ((regs.r_ecx >> 2) & 1) {
                *hvm = "svm";
            }
            if ((regs.r_edx >> 6) & 1)
                *pae = 1;
        }
    } else if (STREQLEN((const char *)&regs.r_ebx, "GenuntelineI", 12)) {
2267
        if (pread(fd, &regs, sizeof(regs), 0x00000001) == sizeof(regs)) {
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
            /* Read VMXE feature bit (bit 5 of ECX feature ID) */
            if ((regs.r_ecx >> 5) & 1)
                *hvm = "vmx";
            if ((regs.r_edx >> 6) & 1)
                *pae = 1;
        }
    }

    ret = 1;

out:
2279
    VIR_FORCE_CLOSE(fd);
2280 2281 2282 2283 2284 2285 2286
    return ret;
}

static virCapsPtr
xenHypervisorMakeCapabilitiesSunOS(virConnectPtr conn)
{
    struct guest_arch guest_arches[32];
2287
    size_t i = 0;
2288 2289 2290 2291 2292 2293 2294
    virCapsPtr caps = NULL;
    int pae, longmode;
    const char *hvm;

    if (!get_cpu_flags(conn, &hvm, &pae, &longmode))
        return NULL;

2295
    guest_arches[i].arch = VIR_ARCH_I686;
2296 2297 2298 2299 2300 2301 2302
    guest_arches[i].hvm = 0;
    guest_arches[i].pae = pae;
    guest_arches[i].nonpae = !pae;
    guest_arches[i].ia64_be = 0;
    i++;

    if (longmode) {
2303
        guest_arches[i].arch = VIR_ARCH_X86_64;
2304 2305 2306 2307 2308 2309 2310 2311
        guest_arches[i].hvm = 0;
        guest_arches[i].pae = 0;
        guest_arches[i].nonpae = 0;
        guest_arches[i].ia64_be = 0;
        i++;
    }

    if (hvm[0] != '\0') {
2312
        guest_arches[i].arch = VIR_ARCH_I686;
2313 2314 2315 2316 2317 2318 2319
        guest_arches[i].hvm = 1;
        guest_arches[i].pae = pae;
        guest_arches[i].nonpae = 1;
        guest_arches[i].ia64_be = 0;
        i++;

        if (longmode) {
2320
            guest_arches[i].arch = VIR_ARCH_X86_64;
2321 2322 2323 2324 2325 2326 2327 2328
            guest_arches[i].hvm = 1;
            guest_arches[i].pae = 0;
            guest_arches[i].nonpae = 0;
            guest_arches[i].ia64_be = 0;
            i++;
        }
    }

2329 2330 2331 2332
    caps = xenHypervisorBuildCapabilities(conn,
                                          virArchFromHost(),
                                          pae, hvm,
                                          guest_arches, i);
2333 2334 2335 2336 2337 2338

    return caps;
}

#endif /* __sun */

2339
/**
2340
 * xenHypervisorMakeCapabilitiesInternal:
2341
 * @conn: pointer to the connection block
2342 2343
 * @cpuinfo: file handle containing /proc/cpuinfo data, or NULL
 * @capabilities: file handle containing /sys/hypervisor/properties/capabilities data, or NULL
2344 2345 2346
 *
 * Return the capabilities of this hypervisor.
 */
2347
virCapsPtr
2348
xenHypervisorMakeCapabilitiesInternal(virConnectPtr conn,
2349
                                      virArch hostarch,
2350 2351
                                      FILE *cpuinfo,
                                      FILE *capabilities)
2352 2353
{
    char line[1024], *str, *token;
2354
    regmatch_t subs[4];
2355
    char *saveptr = NULL;
2356
    size_t i;
2357 2358 2359

    char hvm_type[4] = ""; /* "vmx" or "svm" (or "" if not in CPU). */
    int host_pae = 0;
2360
    struct guest_arch guest_archs[32];
2361
    int nr_guest_archs = 0;
2362
    virCapsPtr caps = NULL;
2363

2364 2365
    memset(guest_archs, 0, sizeof(guest_archs));

2366 2367 2368 2369
    /* /proc/cpuinfo: flags: Intel calls HVM "vmx", AMD calls it "svm".
     * It's not clear if this will work on IA64, let alone other
     * architectures and non-Linux. (XXX)
     */
2370
    if (cpuinfo) {
2371 2372
        while (fgets(line, sizeof(line), cpuinfo)) {
            if (regexec(&flags_hvm_rec, line, sizeof(subs)/sizeof(regmatch_t), subs, 0) == 0
2373
                && subs[0].rm_so != -1) {
C
Chris Lalancette 已提交
2374 2375 2376 2377
                if (virStrncpy(hvm_type,
                               &line[subs[1].rm_so],
                               subs[1].rm_eo-subs[1].rm_so,
                               sizeof(hvm_type)) == NULL)
2378
                    goto no_memory;
2379
            } else if (regexec(&flags_pae_rec, line, 0, NULL, 0) == 0)
2380 2381
                host_pae = 1;
        }
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
    }

    /* Most of the useful info is in /sys/hypervisor/properties/capabilities
     * which is documented in the code in xen-unstable.hg/xen/arch/.../setup.c.
     *
     * It is a space-separated list of supported guest architectures.
     *
     * For x86:
     *    TYP-VER-ARCH[p]
     *    ^   ^   ^    ^
     *    |   |   |    +-- PAE supported
     *    |   |   +------- x86_32 or x86_64
     *    |   +----------- the version of Xen, eg. "3.0"
     *    +--------------- "xen" or "hvm" for para or full virt respectively
     *
     * For PPC this file appears to be always empty (?)
     *
     * For IA64:
     *    TYP-VER-ARCH[be]
     *    ^   ^   ^    ^
     *    |   |   |    +-- Big-endian supported
     *    |   |   +------- always "ia64"
     *    |   +----------- the version of Xen, eg. "3.0"
     *    +--------------- "xen" or "hvm" for para or full virt respectively
     */

    /* Expecting one line in this file - ignore any more. */
2409
    if ((capabilities) && (fgets(line, sizeof(line), capabilities))) {
2410 2411 2412 2413
        /* Split the line into tokens.  strtok_r is OK here because we "own"
         * this buffer.  Parse out the features from each token.
         */
        for (str = line, nr_guest_archs = 0;
2414
             nr_guest_archs < sizeof(guest_archs) / sizeof(guest_archs[0])
2415
                 && (token = strtok_r(str, " ", &saveptr)) != NULL;
2416 2417
             str = NULL) {

2418 2419
            if (regexec(&xen_cap_rec, token, sizeof(subs) / sizeof(subs[0]),
                        subs, 0) == 0) {
2420
                int hvm = STRPREFIX(&token[subs[1].rm_so], "hvm");
2421 2422
                int pae = 0, nonpae = 0, ia64_be = 0;
                virArch arch;
2423 2424

                if (STRPREFIX(&token[subs[2].rm_so], "x86_32")) {
2425
                    arch = VIR_ARCH_I686;
2426 2427
                    if (subs[3].rm_so != -1 &&
                        STRPREFIX(&token[subs[3].rm_so], "p"))
2428 2429 2430 2431
                        pae = 1;
                    else
                        nonpae = 1;
                }
2432
                else if (STRPREFIX(&token[subs[2].rm_so], "x86_64")) {
2433
                    arch = VIR_ARCH_X86_64;
2434
                }
2435
                else if (STRPREFIX(&token[subs[2].rm_so], "ia64")) {
2436
                    arch = VIR_ARCH_ITANIUM;
2437 2438
                    if (subs[3].rm_so != -1 &&
                        STRPREFIX(&token[subs[3].rm_so], "be"))
2439 2440
                        ia64_be = 1;
                }
2441
                else if (STRPREFIX(&token[subs[2].rm_so], "powerpc64")) {
2442
                    arch = VIR_ARCH_PPC64;
2443
                } else {
2444
                    /* XXX surely no other Xen archs exist. Arrrrrrrrrm  */
2445 2446
                    continue;
                }
2447

2448
                /* Search for existing matching (model,hvm) tuple */
2449
                for (i = 0; i < nr_guest_archs; i++) {
2450
                    if (guest_archs[i].arch == arch &&
2451 2452 2453 2454
                        guest_archs[i].hvm == hvm) {
                        break;
                    }
                }
2455

2456
                /* Too many arch flavours - highly unlikely ! */
J
Jim Meyering 已提交
2457
                if (i >= ARRAY_CARDINALITY(guest_archs))
2458 2459 2460 2461 2462
                    continue;
                /* Didn't find a match, so create a new one */
                if (i == nr_guest_archs)
                    nr_guest_archs++;

2463
                guest_archs[i].arch = arch;
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
                guest_archs[i].hvm = hvm;

                /* Careful not to overwrite a previous positive
                   setting with a negative one here - some archs
                   can do both pae & non-pae, but Xen reports
                   separately capabilities so we're merging archs */
                if (pae)
                    guest_archs[i].pae = pae;
                if (nonpae)
                    guest_archs[i].nonpae = nonpae;
                if (ia64_be)
                    guest_archs[i].ia64_be = ia64_be;
2476 2477 2478 2479
            }
        }
    }

2480
    if ((caps = xenHypervisorBuildCapabilities(conn,
2481
                                               hostarch,
2482 2483 2484 2485 2486
                                               host_pae,
                                               hvm_type,
                                               guest_archs,
                                               nr_guest_archs)) == NULL)
        goto no_memory;
2487

2488
    return caps;
2489

2490
 no_memory:
2491
    virObjectUnref(caps);
2492 2493 2494 2495
    return NULL;
}

/**
2496
 * xenHypervisorMakeCapabilities:
2497 2498 2499
 *
 * Return the capabilities of this hypervisor.
 */
2500
virCapsPtr
2501
xenHypervisorMakeCapabilities(virConnectPtr conn)
2502
{
2503 2504 2505
#ifdef __sun
    return xenHypervisorMakeCapabilitiesSunOS(conn);
#else
2506
    virCapsPtr caps = NULL;
2507 2508
    FILE *cpuinfo, *capabilities;

2509
    cpuinfo = fopen("/proc/cpuinfo", "r");
2510 2511
    if (cpuinfo == NULL) {
        if (errno != ENOENT) {
2512
            virReportSystemError(errno,
2513 2514
                                 _("cannot read file %s"),
                                 "/proc/cpuinfo");
2515 2516 2517 2518
            return NULL;
        }
    }

2519
    capabilities = fopen("/sys/hypervisor/properties/capabilities", "r");
2520 2521
    if (capabilities == NULL) {
        if (errno != ENOENT) {
2522
            VIR_FORCE_FCLOSE(cpuinfo);
2523
            virReportSystemError(errno,
2524 2525
                                 _("cannot read file %s"),
                                 "/sys/hypervisor/properties/capabilities");
2526 2527 2528 2529
            return NULL;
        }
    }

2530
    caps = xenHypervisorMakeCapabilitiesInternal(conn,
2531
                                                 virArchFromHost(),
2532 2533
                                                 cpuinfo,
                                                 capabilities);
2534
    if (caps == NULL)
2535
        goto cleanup;
2536

2537 2538 2539
    if (virNodeSuspendGetTargetMask(&caps->host.powerMgmt) < 0)
        VIR_WARN("Failed to get host power management capabilities");

2540
cleanup:
2541 2542
    VIR_FORCE_FCLOSE(cpuinfo);
    VIR_FORCE_FCLOSE(capabilities);
2543

2544
    return caps;
2545
#endif /* __sun */
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
}



/**
 * xenHypervisorGetCapabilities:
 * @conn: pointer to the connection block
 *
 * Return the capabilities of this hypervisor.
 */
char *
2557
xenHypervisorGetCapabilities(virConnectPtr conn)
2558
{
2559
    xenUnifiedPrivatePtr priv = conn->privateData;
2560 2561 2562
    char *xml;

    if (!(xml = virCapabilitiesFormatXML(priv->caps))) {
2563
        virReportOOMError();
2564 2565 2566
        return NULL;
    }

2567
    return xml;
2568 2569
}

2570

2571
char *
2572 2573
xenHypervisorDomainGetOSType(virConnectPtr conn,
                             virDomainDefPtr def)
2574
{
2575
    xenUnifiedPrivatePtr priv = conn->privateData;
2576
    xen_getdomaininfo dominfo;
2577
    char *ostype = NULL;
2578 2579

    /* HV's earlier than 3.1.0 don't include the HVM flags in guests status*/
P
Philipp Hahn 已提交
2580 2581
    if (hv_versions.hypervisor < 2 ||
        hv_versions.dom_interface < 4) {
2582
        return xenDaemonDomainGetOSType(conn, def);
2583
    }
2584 2585 2586

    XEN_GETDOMAININFO_CLEAR(dominfo);

2587
    if (virXen_getdomaininfo(priv->handle, def->id, &dominfo) < 0) {
2588 2589
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
2590
        return NULL;
2591
    }
2592

2593
    if (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id) {
2594 2595
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
2596
        return NULL;
2597
    }
2598

2599 2600 2601
    ignore_value(VIR_STRDUP(ostype,
                            XEN_GETDOMAININFO_FLAGS(dominfo) & DOMFLAGS_HVM ?
                            "hvm" : "linux"));
2602
    return ostype;
2603 2604
}

2605
int
2606
xenHypervisorHasDomain(virConnectPtr conn, int id)
2607
{
2608
    xenUnifiedPrivatePtr priv = conn->privateData;
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
    xen_getdomaininfo dominfo;

    XEN_GETDOMAININFO_CLEAR(dominfo);

    if (virXen_getdomaininfo(priv->handle, id, &dominfo) < 0)
        return 0;

    if (XEN_GETDOMAININFO_DOMAIN(dominfo) != id)
        return 0;

    return 1;
}

2622 2623

virDomainDefPtr
2624
xenHypervisorLookupDomainByID(virConnectPtr conn, int id)
2625
{
2626
    xenUnifiedPrivatePtr priv = conn->privateData;
2627
    xen_getdomaininfo dominfo;
2628
    virDomainDefPtr ret;
2629 2630 2631 2632 2633
    char *name;

    XEN_GETDOMAININFO_CLEAR(dominfo);

    if (virXen_getdomaininfo(priv->handle, id, &dominfo) < 0)
2634
        return NULL;
2635 2636

    if (XEN_GETDOMAININFO_DOMAIN(dominfo) != id)
2637
        return NULL;
2638

D
Daniel P. Berrange 已提交
2639 2640 2641 2642
    xenUnifiedLock(priv);
    name = xenStoreDomainGetName(conn, id);
    xenUnifiedUnlock(priv);
    if (!name)
2643
        return NULL;
2644

2645 2646 2647
    ret = virDomainDefNew(name,
                          XEN_GETDOMAININFO_UUID(dominfo),
                          id);
2648
    VIR_FREE(name);
2649 2650 2651 2652
    return ret;
}


2653
virDomainDefPtr
2654
xenHypervisorLookupDomainByUUID(virConnectPtr conn, const unsigned char *uuid)
2655 2656
{
    xen_getdomaininfolist dominfos;
2657
    xenUnifiedPrivatePtr priv = conn->privateData;
2658
    virDomainDefPtr ret;
2659
    char *name;
2660 2661
    int maxids = 100, nids, id;
    size_t i;
2662 2663 2664

 retry:
    if (!(XEN_GETDOMAININFOLIST_ALLOC(dominfos, maxids))) {
2665
        virReportOOMError();
2666
        return NULL;
2667 2668 2669 2670 2671 2672 2673 2674
    }

    XEN_GETDOMAININFOLIST_CLEAR(dominfos, maxids);

    nids = virXen_getdomaininfolist(priv->handle, 0, maxids, &dominfos);

    if (nids < 0) {
        XEN_GETDOMAININFOLIST_FREE(dominfos);
2675
        return NULL;
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
    }

    /* Can't possibly have more than 65,000 concurrent guests
     * so limit how many times we try, to avoid increasing
     * without bound & thus allocating all of system memory !
     * XXX I'll regret this comment in a few years time ;-)
     */
    if (nids == maxids) {
        XEN_GETDOMAININFOLIST_FREE(dominfos);
        if (maxids < 65000) {
            maxids *= 2;
            goto retry;
        }
2689
        return NULL;
2690 2691 2692
    }

    id = -1;
2693
    for (i = 0; i < nids; i++) {
2694 2695 2696 2697 2698 2699 2700 2701
        if (memcmp(XEN_GETDOMAININFOLIST_UUID(dominfos, i), uuid, VIR_UUID_BUFLEN) == 0) {
            id = XEN_GETDOMAININFOLIST_DOMAIN(dominfos, i);
            break;
        }
    }
    XEN_GETDOMAININFOLIST_FREE(dominfos);

    if (id == -1)
2702
        return NULL;
2703

D
Daniel P. Berrange 已提交
2704 2705 2706 2707
    xenUnifiedLock(priv);
    name = xenStoreDomainGetName(conn, id);
    xenUnifiedUnlock(priv);
    if (!name)
2708
        return NULL;
2709

2710
    ret = virDomainDefNew(name, uuid, id);
2711 2712
    if (ret)
        ret->id = id;
2713
    VIR_FREE(name);
2714 2715 2716
    return ret;
}

2717
/**
2718
 * xenHypervisorGetMaxVcpus:
2719 2720 2721 2722
 *
 * Returns the maximum of CPU defined by Xen.
 */
int
2723 2724
xenHypervisorGetMaxVcpus(virConnectPtr conn ATTRIBUTE_UNUSED,
                         const char *type ATTRIBUTE_UNUSED)
2725 2726 2727 2728
{
    return MAX_VIRT_CPUS;
}

2729
/**
2730 2731
 * xenHypervisorDomMaxMemory:
 * @dom: domain
2732
 *
2733
 * Retrieve the maximum amount of physical memory allocated to a
2734
 * domain.
2735 2736 2737
 *
 * Returns the memory size in kilobytes or 0 in case of error.
 */
2738
unsigned long
2739 2740
xenHypervisorGetMaxMemory(virConnectPtr conn,
                          virDomainDefPtr def)
2741
{
2742
    xenUnifiedPrivatePtr priv = conn->privateData;
2743
    xen_getdomaininfo dominfo;
2744 2745
    int ret;

2746 2747
    if (kb_per_pages == 0) {
        kb_per_pages = sysconf(_SC_PAGESIZE) / 1024;
2748 2749
        if (kb_per_pages <= 0)
            kb_per_pages = 4;
2750 2751
    }

2752
    XEN_GETDOMAININFO_CLEAR(dominfo);
2753

2754
    ret = virXen_getdomaininfo(priv->handle, def->id, &dominfo);
2755

2756
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id))
2757
        return 0;
2758

2759
    return (unsigned long) XEN_GETDOMAININFO_MAX_PAGES(dominfo) * kb_per_pages;
2760 2761
}

2762

2763
/**
2764 2765 2766
 * xenHypervisorGetDomInfo:
 * @conn: connection data
 * @id: the domain ID
2767
 * @info: the place where information should be stored
2768
 *
E
Eric Blake 已提交
2769
 * Do a hypervisor call to get the related set of domain information.
2770 2771 2772 2773
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
2774
xenHypervisorGetDomInfo(virConnectPtr conn, int id, virDomainInfoPtr info)
2775
{
2776
    xenUnifiedPrivatePtr priv = conn->privateData;
2777
    xen_getdomaininfo dominfo;
2778
    int ret;
2779
    uint32_t domain_flags, domain_state, domain_shutdown_cause;
2780 2781 2782

    if (kb_per_pages == 0) {
        kb_per_pages = sysconf(_SC_PAGESIZE) / 1024;
2783 2784
        if (kb_per_pages <= 0)
            kb_per_pages = 4;
2785
    }
2786

2787
    memset(info, 0, sizeof(virDomainInfo));
2788
    XEN_GETDOMAININFO_CLEAR(dominfo);
2789

2790
    ret = virXen_getdomaininfo(priv->handle, id, &dominfo);
2791

2792
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != id))
2793
        return -1;
2794

2795
    domain_flags = XEN_GETDOMAININFO_FLAGS(dominfo);
2796 2797
    domain_flags &= ~DOMFLAGS_HVM; /* Mask out HVM flags */
    domain_state = domain_flags & 0xFF; /* Mask out high bits */
2798
    switch (domain_state) {
2799 2800 2801 2802
        case DOMFLAGS_DYING:
            info->state = VIR_DOMAIN_SHUTDOWN;
            break;
        case DOMFLAGS_SHUTDOWN:
2803 2804 2805 2806 2807 2808 2809 2810 2811
            /* The domain is shutdown.  Determine the cause. */
            domain_shutdown_cause = domain_flags >> DOMFLAGS_SHUTDOWNSHIFT;
            switch (domain_shutdown_cause) {
                case SHUTDOWN_crash:
                    info->state = VIR_DOMAIN_CRASHED;
                    break;
                default:
                    info->state = VIR_DOMAIN_SHUTOFF;
            }
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
            break;
        case DOMFLAGS_PAUSED:
            info->state = VIR_DOMAIN_PAUSED;
            break;
        case DOMFLAGS_BLOCKED:
            info->state = VIR_DOMAIN_BLOCKED;
            break;
        case DOMFLAGS_RUNNING:
            info->state = VIR_DOMAIN_RUNNING;
            break;
        default:
            info->state = VIR_DOMAIN_NOSTATE;
2824 2825 2826 2827 2828 2829 2830
    }

    /*
     * the API brings back the cpu time in nanoseconds,
     * convert to microseconds, same thing convert to
     * kilobytes from page counts
     */
2831
    info->cpuTime = XEN_GETDOMAININFO_CPUTIME(dominfo);
2832
    info->memory = XEN_GETDOMAININFO_TOT_PAGES(dominfo) * kb_per_pages;
2833
    info->maxMem = XEN_GETDOMAININFO_MAX_PAGES(dominfo);
2834
    if (info->maxMem != UINT_MAX)
2835
        info->maxMem *= kb_per_pages;
2836
    info->nrVirtCpu = XEN_GETDOMAININFO_CPUCOUNT(dominfo);
2837
    return 0;
2838 2839
}

2840 2841 2842
/**
 * xenHypervisorGetDomainInfo:
 * @domain: pointer to the domain block
2843
 * @info: the place where information should be stored
2844
 *
E
Eric Blake 已提交
2845
 * Do a hypervisor call to get the related set of domain information.
2846 2847 2848 2849
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
2850 2851 2852
xenHypervisorGetDomainInfo(virConnectPtr conn,
                           virDomainDefPtr def,
                           virDomainInfoPtr info)
2853
{
2854
    return xenHypervisorGetDomInfo(conn, def->id, info);
2855 2856
}

2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
/**
 * xenHypervisorGetDomainState:
 * @domain: pointer to the domain block
 * @state: returned state of the domain
 * @reason: returned reason for the state
 *
 * Do a hypervisor call to get the related set of domain information.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
2868 2869
xenHypervisorGetDomainState(virConnectPtr conn,
                            virDomainDefPtr def,
2870
                            int *state,
2871
                            int *reason)
2872 2873 2874
{
    virDomainInfo info;

2875
    if (xenHypervisorGetDomInfo(conn, def->id, &info) < 0)
2876 2877 2878 2879 2880 2881 2882 2883 2884
        return -1;

    *state = info.state;
    if (reason)
        *reason = 0;

    return 0;
}

2885 2886 2887 2888
/**
 * xenHypervisorNodeGetCellsFreeMemory:
 * @conn: pointer to the hypervisor connection
 * @freeMems: pointer to the array of unsigned long long
2889 2890
 * @startCell: index of first cell to return freeMems info on.
 * @maxCells: Maximum number of cells for which freeMems information can
2891 2892 2893 2894
 *            be returned.
 *
 * This call returns the amount of free memory in one or more NUMA cells.
 * The @freeMems array must be allocated by the caller and will be filled
2895 2896 2897
 * with the amount of free memory in kilobytes for each cell requested,
 * starting with startCell (in freeMems[0]), up to either
 * (startCell + maxCells), or the number of additional cells in the node,
2898 2899 2900 2901 2902
 * whichever is smaller.
 *
 * Returns the number of entries filled in freeMems, or -1 in case of error.
 */
int
2903 2904 2905 2906
xenHypervisorNodeGetCellsFreeMemory(virConnectPtr conn,
                                    unsigned long long *freeMems,
                                    int startCell,
                                    int maxCells)
2907 2908
{
    xen_op_v2_sys op_sys;
2909 2910 2911
    size_t i;
    int cell;
    int ret;
2912
    xenUnifiedPrivatePtr priv = conn->privateData;
D
Daniel P. Berrange 已提交
2913 2914

    if (priv->nbNodeCells < 0) {
2915 2916
        virReportError(VIR_ERR_XEN_CALL, "%s",
                       _("cannot determine actual number of cells"));
2917
        return -1;
2918 2919
    }

D
Daniel P. Berrange 已提交
2920
    if ((maxCells < 1) || (startCell >= priv->nbNodeCells)) {
2921 2922
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid argument"));
2923 2924
        return -1;
    }
2925

2926
    /*
P
Philipp Hahn 已提交
2927
     * Support only hv_versions.sys_interface >=4
2928
     */
P
Philipp Hahn 已提交
2929
    if (hv_versions.sys_interface < SYS_IFACE_MIN_VERS_NUMA) {
2930 2931
        virReportError(VIR_ERR_XEN_CALL, "%s",
                       _("unsupported in sys interface < 4"));
2932 2933 2934 2935 2936 2937
        return -1;
    }

    memset(&op_sys, 0, sizeof(op_sys));
    op_sys.cmd = XEN_V2_OP_GETAVAILHEAP;

2938 2939
    for (cell = startCell, i = 0;
         cell < priv->nbNodeCells && i < maxCells; cell++, i++) {
P
Philipp Hahn 已提交
2940
        if (hv_versions.sys_interface >= 5)
2941
            op_sys.u.availheap5.node = cell;
2942
        else
2943
            op_sys.u.availheap.node = cell;
2944 2945
        ret = xenHypervisorDoV2Sys(priv->handle, &op_sys);
        if (ret < 0) {
2946
            return -1;
2947
        }
P
Philipp Hahn 已提交
2948
        if (hv_versions.sys_interface >= 5)
2949
            freeMems[i] = op_sys.u.availheap5.avail_bytes;
2950
        else
2951
            freeMems[i] = op_sys.u.availheap.avail_bytes;
2952
    }
2953
    return i;
2954 2955 2956
}


2957 2958
/**
 * xenHypervisorSetMaxMemory:
2959
 * @domain: pointer to the domain block
2960 2961
 * @memory: the max memory size in kilobytes.
 *
E
Eric Blake 已提交
2962
 * Do a hypervisor call to change the maximum amount of memory used
2963 2964 2965 2966
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
2967 2968 2969
xenHypervisorSetMaxMemory(virConnectPtr conn,
                          virDomainDefPtr def,
                          unsigned long memory)
2970
{
2971
    int ret;
2972
    xenUnifiedPrivatePtr priv = conn->privateData;
2973

2974
    ret = virXen_setmaxmem(priv->handle, def->id, memory);
2975
    if (ret < 0)
2976 2977
        return -1;
    return 0;
2978
}
2979

2980

2981 2982 2983 2984 2985 2986
/**
 * xenHypervisorPinVcpu:
 * @domain: pointer to domain object
 * @vcpu: virtual CPU number
 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes)
 * @maplen: length of cpumap in bytes
2987
 *
2988 2989 2990 2991 2992 2993
 * Dynamically change the real CPUs which can be allocated to a virtual CPU.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */

int
2994 2995 2996 2997 2998
xenHypervisorPinVcpu(virConnectPtr conn,
                     virDomainDefPtr def,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
2999
{
3000
    int ret;
3001
    xenUnifiedPrivatePtr priv = conn->privateData;
3002

3003
    ret = virXen_setvcpumap(priv->handle, def->id, vcpu,
3004 3005
                            cpumap, maplen);
    if (ret < 0)
3006 3007
        return -1;
    return 0;
3008 3009 3010 3011 3012 3013 3014
}

/**
 * virDomainGetVcpus:
 * @domain: pointer to domain object, or NULL for Domain0
 * @info: pointer to an array of virVcpuInfo structures (OUT)
 * @maxinfo: number of structures in info array
E
Eric Blake 已提交
3015
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this domain (in 8-bit bytes) (OUT)
D
Daniel Veillard 已提交
3016
 *	If cpumaps is NULL, then no cpumap information is returned by the API.
3017 3018 3019 3020 3021 3022
 *	It's assumed there is <maxinfo> cpumap in cpumaps array.
 *	The memory allocated to cpumaps must be (maxinfo * maplen) bytes
 *	(ie: calloc(maxinfo, maplen)).
 *	One cpumap inside cpumaps has the format described in virDomainPinVcpu() API.
 * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in
 *	underlying virtualization system (Xen...).
3023
 *
3024
 * Extract information about virtual CPUs of domain, store it in info array
R
Richard W.M. Jones 已提交
3025
 * and also in cpumaps if this pointer isn't NULL.
3026 3027 3028 3029
 *
 * Returns the number of info filled in case of success, -1 in case of failure.
 */
int
3030 3031
xenHypervisorGetVcpus(virConnectPtr conn,
                      virDomainDefPtr def,
3032 3033 3034 3035
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
3036
{
3037
    xen_getdomaininfo dominfo;
3038
    int ret;
3039
    xenUnifiedPrivatePtr priv = conn->privateData;
3040
    virVcpuInfoPtr ipt;
3041 3042
    int nbinfo;
    size_t i;
3043

3044
    if (sizeof(cpumap_t) & 7) {
3045
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3046
                       _("invalid cpumap_t size"));
3047
        return -1;
3048
    }
3049

3050
    /* first get the number of virtual CPUs in this domain */
3051
    XEN_GETDOMAININFO_CLEAR(dominfo);
3052
    ret = virXen_getdomaininfo(priv->handle, def->id,
3053
                               &dominfo);
3054

3055
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id)) {
3056 3057
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
3058
        return -1;
3059
    }
3060
    nbinfo = XEN_GETDOMAININFO_CPUCOUNT(dominfo) + 1;
3061 3062 3063
    if (nbinfo > maxinfo) nbinfo = maxinfo;

    if (cpumaps != NULL)
3064
        memset(cpumaps, 0, maxinfo * maplen);
3065

3066 3067
    for (i = 0, ipt = info; i < nbinfo; i++, ipt++) {
        if ((cpumaps != NULL) && (i < maxinfo)) {
3068
            ret = virXen_getvcpusinfo(priv->handle, def->id, i,
3069 3070 3071
                                      ipt,
                                      (unsigned char *)VIR_GET_CPUMAP(cpumaps, maplen, i),
                                      maplen);
3072
            if (ret < 0) {
3073 3074
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get VCPUs info"));
3075
                return -1;
3076
            }
3077
        } else {
3078
            ret = virXen_getvcpusinfo(priv->handle, def->id, i,
3079
                                      ipt, NULL, 0);
3080
            if (ret < 0) {
3081 3082
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get VCPUs info"));
3083
                return -1;
3084
            }
3085
        }
3086 3087 3088
    }
    return nbinfo;
}
3089

3090 3091 3092 3093 3094 3095 3096 3097 3098
/**
 * xenHypervisorGetVcpuMax:
 *
 *  Returns the maximum number of virtual CPUs supported for
 *  the guest VM. If the guest is inactive, this is the maximum
 *  of CPU defined by Xen. If the guest is running this reflect
 *  the maximum number of virtual CPUs the guest was booted with.
 */
int
3099 3100
xenHypervisorGetVcpuMax(virConnectPtr conn,
                        virDomainDefPtr def)
3101 3102 3103 3104
{
    xen_getdomaininfo dominfo;
    int ret;
    int maxcpu;
3105
    xenUnifiedPrivatePtr priv = conn->privateData;
3106 3107

    /* inactive domain */
3108
    if (def->id < 0) {
3109 3110 3111
        maxcpu = MAX_VIRT_CPUS;
    } else {
        XEN_GETDOMAININFO_CLEAR(dominfo);
3112
        ret = virXen_getdomaininfo(priv->handle, def->id,
3113 3114
                                   &dominfo);

3115
        if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id))
3116
            return -1;
3117 3118 3119 3120 3121 3122
        maxcpu = XEN_GETDOMAININFO_MAXCPUID(dominfo) + 1;
    }

    return maxcpu;
}

J
John Levon 已提交
3123 3124 3125 3126 3127 3128
/**
 * xenHavePrivilege()
 *
 * Return true if the current process should be able to connect to Xen.
 */
int
3129
xenHavePrivilege(void)
J
John Levon 已提交
3130 3131
{
#ifdef __sun
3132
    return priv_ineffect(PRIV_XVM_CONTROL);
J
John Levon 已提交
3133
#else
3134
    return access(XEN_HYPERVISOR_SOCKET, R_OK) == 0;
J
John Levon 已提交
3135 3136
#endif
}