xen_hypervisor.c 99.3 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 "virstats.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;
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;
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
        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;

1363
        switch (op_sys.u.getschedulerid.sched_id) {
1364 1365 1366
        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
                              const char *path,
1426
                              virDomainBlockStatsPtr 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
                                  const char *path,
1454
                                  virDomainInterfaceStatsPtr 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 virNetInterfaceStats(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
            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;
1667
            } else {
1668
                ipt->state = VIR_VCPU_OFFLINE;
1669
            }
1670 1671 1672 1673 1674 1675 1676 1677 1678

            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;
1679
            } else {
1680
                ipt->state = VIR_VCPU_OFFLINE;
1681
            }
1682 1683 1684

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

1690
            memset(cpumap, 0, maplen);
1691 1692 1693
            memset(&op, 0, sizeof(op));
            op.cmd = XEN_V2_OP_GETVCPUMAP;
            op.domain = (domid_t) id;
P
Philipp Hahn 已提交
1694
            if (hv_versions.dom_interface < 5) {
1695 1696 1697 1698 1699 1700 1701 1702
                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;
            }
1703
            ret = xenHypervisorDoV2Dom(handle, &op);
1704
            if (unlock_pages(cpumap, maplen) < 0)
1705 1706
                ret = -1;
        }
1707
    } else {
1708 1709 1710 1711 1712
        int mapl = maplen;
        int cpu;

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

P
Philipp Hahn 已提交
1714
        if (hv_versions.hypervisor == 1) {
1715 1716 1717 1718 1719 1720 1721 1722
            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)
1723
                return -1;
1724
            ipt->number = vcpu;
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
            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 已提交
1738
        } else if (hv_versions.hypervisor == 0) {
1739 1740 1741 1742 1743 1744 1745 1746
            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)
1747
                return -1;
1748
            ipt->number = vcpu;
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
            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);
                }
            }
        }
1763
    }
1764
    return ret;
1765
}
1766

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

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

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

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

1828 1829 1830 1831
    /*
     * The size of the hypervisor call block changed July 2006
     * this detect if we are using the new or old hypercall_t structure
     */
1832 1833 1834 1835 1836 1837 1838 1839
    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)) {
1840
        VIR_DEBUG("Using new hypervisor call: %X", ret);
P
Philipp Hahn 已提交
1841
        hv_versions.hv = ret;
1842 1843
        xen_ioctl_hypercall_cmd = cmd;
        goto detect_v2;
1844
    }
1845

1846
#ifndef __sun
1847 1848 1849 1850 1851 1852 1853 1854
    /*
     * 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);
1855
    if ((ret != -1) && (ret != 0)) {
1856
        VIR_DEBUG("Using old hypervisor call: %X", ret);
P
Philipp Hahn 已提交
1857
        hv_versions.hv = ret;
1858
        xen_ioctl_hypercall_cmd = cmd;
P
Philipp Hahn 已提交
1859
        hv_versions.hypervisor = 0;
1860
        goto done;
1861
    }
1862
#endif
1863

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

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

1875
 detect_v2:
1876 1877 1878 1879 1880
    /*
     * 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 已提交
1881
    hv_versions.hypervisor = 2;
1882

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

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

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

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

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

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

1959 1960 1961 1962 1963 1964 1965
    /* 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 */
1966
        if (virXen_getvcpusinfo(fd, 0, 0, ipt, NULL, 0) == 0) {
1967 1968 1969 1970
            VIR_DEBUG("Using hypervisor call v2, sys ver9 dom ver8");
            goto done;
        }
    }
1971

1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    /* 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 已提交
1985 1986 1987 1988 1989 1990 1991
    hv_versions.hypervisor = 1;
    hv_versions.sys_interface = -1;
    if (virXen_getdomaininfo(fd, 0, &info) == 1) {
        VIR_DEBUG("Using hypervisor call v1");
        goto done;
    }

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

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

2010

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

VIR_ONCE_GLOBAL_INIT(xenHypervisor)

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

2036
    virCheckFlags(VIR_CONNECT_RO, -1);
E
Eric Blake 已提交
2037

2038
    if (xenHypervisorInitialize() < 0)
2039
        return -1;
2040

2041
    priv->handle = -1;
2042

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

    priv->handle = ret;
2050

2051
    return 0;
2052 2053 2054 2055
}

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

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

2072
    return 0;
2073 2074 2075
}


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

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


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

2113
    if ((caps = virCapabilitiesNew(hostarch, true, true)) == NULL)
2114
        goto no_memory;
2115

2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
    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 已提交
2129
    if (hv_versions.sys_interface >= SYS_IFACE_MIN_VERS_NUMA && conn != NULL) {
2130
        if (xenDaemonNodeGetTopology(conn, caps) != 0) {
2131
            virObjectUnref(caps);
2132 2133 2134 2135 2136 2137
            return NULL;
        }
    }

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

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

        if ((guest = virCapabilitiesAddGuest(caps,
                                             guest_archs[i].hvm ? "hvm" : "xen",
2146 2147
                                             guest_archs[i].arch,
                                             (hostarch == VIR_ARCH_X86_64 ?
2148 2149 2150 2151 2152 2153
                                              "/usr/lib64/xen/bin/qemu-dm" :
                                              "/usr/lib/xen/bin/qemu-dm"),
                                             (guest_archs[i].hvm ?
                                              "/usr/lib/xen/boot/hvmloader" :
                                              NULL),
                                             1,
2154 2155
                                             machines)) == NULL) {
            virCapabilitiesFreeMachines(machines, 1);
2156
            goto no_memory;
2157
        }
2158
        machines = NULL;
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170

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

        if (guest_archs[i].pae &&
            virCapabilitiesAddGuestFeature(guest,
                                           "pae",
2171 2172
                                           true,
                                           false) == NULL)
2173 2174 2175 2176 2177
            goto no_memory;

        if (guest_archs[i].nonpae &&
            virCapabilitiesAddGuestFeature(guest,
                                           "nonpae",
2178 2179
                                           true,
                                           false) == NULL)
2180 2181 2182 2183 2184
            goto no_memory;

        if (guest_archs[i].ia64_be &&
            virCapabilitiesAddGuestFeature(guest,
                                           "ia64_be",
2185 2186
                                           true,
                                           false) == NULL)
2187 2188 2189 2190 2191
            goto no_memory;

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

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

            /* 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",
2209 2210
                                                   false,
                                                   true) == NULL)
2211
                    goto no_memory;
2212 2213 2214 2215 2216 2217 2218

            /* 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",
2219 2220
                                                   false,
                                                   true) == NULL)
2221
                    goto no_memory;
2222
        }
2223

2224 2225 2226 2227 2228
    }

    return caps;

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

2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
#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)) {
2251
        virReportSystemError(errno, "%s", _("could not read CPU flags"));
2252 2253 2254 2255 2256 2257 2258
        goto out;
    }

    *pae = 0;
    *hvm = "";

    if (STREQLEN((const char *)&regs.r_ebx, "AuthcAMDenti", 12)) {
2259
        if (pread(fd, &regs, sizeof(regs), 0x80000001) == sizeof(regs)) {
2260
            /* Read secure virtual machine bit (bit 2 of ECX feature ID) */
2261
            if ((regs.r_ecx >> 2) & 1)
2262 2263 2264 2265 2266
                *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
            /* 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;

2278
 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
                host_pae = 1;
2381
            }
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 2409
    }

    /* 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. */
2410
    if ((capabilities) && (fgets(line, sizeof(line), capabilities))) {
2411 2412 2413 2414
        /* 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;
2415
             nr_guest_archs < sizeof(guest_archs) / sizeof(guest_archs[0])
2416
                 && (token = strtok_r(str, " ", &saveptr)) != NULL;
2417 2418
             str = NULL) {

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

                if (STRPREFIX(&token[subs[2].rm_so], "x86_32")) {
2426
                    arch = VIR_ARCH_I686;
2427 2428
                    if (subs[3].rm_so != -1 &&
                        STRPREFIX(&token[subs[3].rm_so], "p"))
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
                } else if (STRPREFIX(&token[subs[2].rm_so], "ia64")) {
2435
                    arch = VIR_ARCH_ITANIUM;
2436 2437
                    if (subs[3].rm_so != -1 &&
                        STRPREFIX(&token[subs[3].rm_so], "be"))
2438
                        ia64_be = 1;
2439
                } else if (STRPREFIX(&token[subs[2].rm_so], "powerpc64")) {
2440
                    arch = VIR_ARCH_PPC64;
2441
                } else {
2442
                    /* XXX surely no other Xen archs exist. Arrrrrrrrrm  */
2443 2444
                    continue;
                }
2445

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

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

2461
                guest_archs[i].arch = arch;
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
                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;
2474 2475 2476 2477
            }
        }
    }

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

2486
    return caps;
2487

2488
 no_memory:
2489
    virObjectUnref(caps);
2490 2491 2492 2493
    return NULL;
}

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

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

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

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

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

2538
 cleanup:
2539 2540
    VIR_FORCE_FCLOSE(cpuinfo);
    VIR_FORCE_FCLOSE(capabilities);
2541

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



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

2559
    return virCapabilitiesFormatXML(priv->caps);
2560 2561
}

2562

2563
char *
2564 2565
xenHypervisorDomainGetOSType(virConnectPtr conn,
                             virDomainDefPtr def)
2566
{
2567
    xenUnifiedPrivatePtr priv = conn->privateData;
2568
    xen_getdomaininfo dominfo;
2569
    char *ostype = NULL;
2570 2571

    /* HV's earlier than 3.1.0 don't include the HVM flags in guests status*/
P
Philipp Hahn 已提交
2572 2573
    if (hv_versions.hypervisor < 2 ||
        hv_versions.dom_interface < 4) {
2574
        return xenDaemonDomainGetOSType(conn, def);
2575
    }
2576 2577 2578

    XEN_GETDOMAININFO_CLEAR(dominfo);

2579
    if (virXen_getdomaininfo(priv->handle, def->id, &dominfo) < 0) {
2580 2581
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
2582
        return NULL;
2583
    }
2584

2585
    if (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id) {
2586 2587
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
2588
        return NULL;
2589
    }
2590

2591 2592 2593
    ignore_value(VIR_STRDUP(ostype,
                            XEN_GETDOMAININFO_FLAGS(dominfo) & DOMFLAGS_HVM ?
                            "hvm" : "linux"));
2594
    return ostype;
2595 2596
}

2597
int
2598
xenHypervisorHasDomain(virConnectPtr conn, int id)
2599
{
2600
    xenUnifiedPrivatePtr priv = conn->privateData;
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
    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;
}

2614 2615

virDomainDefPtr
2616
xenHypervisorLookupDomainByID(virConnectPtr conn, int id)
2617
{
2618
    xenUnifiedPrivatePtr priv = conn->privateData;
2619
    xen_getdomaininfo dominfo;
2620
    virDomainDefPtr ret;
2621 2622 2623 2624 2625
    char *name;

    XEN_GETDOMAININFO_CLEAR(dominfo);

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

    if (XEN_GETDOMAININFO_DOMAIN(dominfo) != id)
2629
        return NULL;
2630

D
Daniel P. Berrange 已提交
2631 2632 2633 2634
    xenUnifiedLock(priv);
    name = xenStoreDomainGetName(conn, id);
    xenUnifiedUnlock(priv);
    if (!name)
2635
        return NULL;
2636

2637 2638 2639
    ret = virDomainDefNew(name,
                          XEN_GETDOMAININFO_UUID(dominfo),
                          id);
2640
    VIR_FREE(name);
2641 2642 2643 2644
    return ret;
}


2645
virDomainDefPtr
2646
xenHypervisorLookupDomainByUUID(virConnectPtr conn, const unsigned char *uuid)
2647 2648
{
    xen_getdomaininfolist dominfos;
2649
    xenUnifiedPrivatePtr priv = conn->privateData;
2650
    virDomainDefPtr ret;
2651
    char *name;
2652 2653
    int maxids = 100, nids, id;
    size_t i;
2654 2655 2656

 retry:
    if (!(XEN_GETDOMAININFOLIST_ALLOC(dominfos, maxids))) {
2657
        virReportOOMError();
2658
        return NULL;
2659 2660 2661 2662 2663 2664 2665 2666
    }

    XEN_GETDOMAININFOLIST_CLEAR(dominfos, maxids);

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

    if (nids < 0) {
        XEN_GETDOMAININFOLIST_FREE(dominfos);
2667
        return NULL;
2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
    }

    /* 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;
        }
2681
        return NULL;
2682 2683 2684
    }

    id = -1;
2685
    for (i = 0; i < nids; i++) {
2686 2687 2688 2689 2690 2691 2692 2693
        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)
2694
        return NULL;
2695

D
Daniel P. Berrange 已提交
2696 2697 2698 2699
    xenUnifiedLock(priv);
    name = xenStoreDomainGetName(conn, id);
    xenUnifiedUnlock(priv);
    if (!name)
2700
        return NULL;
2701

2702
    ret = virDomainDefNew(name, uuid, id);
2703 2704
    if (ret)
        ret->id = id;
2705
    VIR_FREE(name);
2706 2707 2708
    return ret;
}

2709
/**
2710
 * xenHypervisorGetMaxVcpus:
2711 2712 2713 2714
 *
 * Returns the maximum of CPU defined by Xen.
 */
int
2715 2716
xenHypervisorGetMaxVcpus(virConnectPtr conn ATTRIBUTE_UNUSED,
                         const char *type ATTRIBUTE_UNUSED)
2717 2718 2719 2720
{
    return MAX_VIRT_CPUS;
}

2721
/**
2722 2723
 * xenHypervisorDomMaxMemory:
 * @dom: domain
2724
 *
2725
 * Retrieve the maximum amount of physical memory allocated to a
2726
 * domain.
2727 2728 2729
 *
 * Returns the memory size in kilobytes or 0 in case of error.
 */
2730
unsigned long
2731 2732
xenHypervisorGetMaxMemory(virConnectPtr conn,
                          virDomainDefPtr def)
2733
{
2734
    xenUnifiedPrivatePtr priv = conn->privateData;
2735
    xen_getdomaininfo dominfo;
2736 2737
    int ret;

2738
    if (kb_per_pages == 0) {
2739
        kb_per_pages = virGetSystemPageSizeKB();
2740 2741
        if (kb_per_pages <= 0)
            kb_per_pages = 4;
2742 2743
    }

2744
    XEN_GETDOMAININFO_CLEAR(dominfo);
2745

2746
    ret = virXen_getdomaininfo(priv->handle, def->id, &dominfo);
2747

2748
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id))
2749
        return 0;
2750

2751
    return (unsigned long) XEN_GETDOMAININFO_MAX_PAGES(dominfo) * kb_per_pages;
2752 2753
}

2754

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

    if (kb_per_pages == 0) {
2774
        kb_per_pages = virGetSystemPageSizeKB();
2775 2776
        if (kb_per_pages <= 0)
            kb_per_pages = 4;
2777
    }
2778

2779
    memset(info, 0, sizeof(virDomainInfo));
2780
    XEN_GETDOMAININFO_CLEAR(dominfo);
2781

2782
    ret = virXen_getdomaininfo(priv->handle, id, &dominfo);
2783

2784
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != id))
2785
        return -1;
2786

2787
    domain_flags = XEN_GETDOMAININFO_FLAGS(dominfo);
2788 2789
    domain_flags &= ~DOMFLAGS_HVM; /* Mask out HVM flags */
    domain_state = domain_flags & 0xFF; /* Mask out high bits */
2790
    switch (domain_state) {
2791 2792 2793 2794
        case DOMFLAGS_DYING:
            info->state = VIR_DOMAIN_SHUTDOWN;
            break;
        case DOMFLAGS_SHUTDOWN:
2795 2796 2797 2798 2799 2800 2801 2802 2803
            /* 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;
            }
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
            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;
2816 2817 2818 2819 2820 2821 2822
    }

    /*
     * the API brings back the cpu time in nanoseconds,
     * convert to microseconds, same thing convert to
     * kilobytes from page counts
     */
2823
    info->cpuTime = XEN_GETDOMAININFO_CPUTIME(dominfo);
2824
    info->memory = XEN_GETDOMAININFO_TOT_PAGES(dominfo) * kb_per_pages;
2825
    info->maxMem = XEN_GETDOMAININFO_MAX_PAGES(dominfo);
2826
    if (info->maxMem != UINT_MAX)
2827
        info->maxMem *= kb_per_pages;
2828
    info->nrVirtCpu = XEN_GETDOMAININFO_CPUCOUNT(dominfo);
2829
    return 0;
2830 2831
}

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

2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
/**
 * 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
2860 2861
xenHypervisorGetDomainState(virConnectPtr conn,
                            virDomainDefPtr def,
2862
                            int *state,
2863
                            int *reason)
2864 2865 2866
{
    virDomainInfo info;

2867
    if (xenHypervisorGetDomInfo(conn, def->id, &info) < 0)
2868 2869 2870 2871 2872 2873 2874 2875 2876
        return -1;

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

    return 0;
}

2877 2878 2879 2880
/**
 * xenHypervisorNodeGetCellsFreeMemory:
 * @conn: pointer to the hypervisor connection
 * @freeMems: pointer to the array of unsigned long long
2881 2882
 * @startCell: index of first cell to return freeMems info on.
 * @maxCells: Maximum number of cells for which freeMems information can
2883 2884 2885 2886
 *            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
2887 2888 2889
 * 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,
2890 2891 2892 2893 2894
 * whichever is smaller.
 *
 * Returns the number of entries filled in freeMems, or -1 in case of error.
 */
int
2895 2896 2897 2898
xenHypervisorNodeGetCellsFreeMemory(virConnectPtr conn,
                                    unsigned long long *freeMems,
                                    int startCell,
                                    int maxCells)
2899 2900
{
    xen_op_v2_sys op_sys;
2901 2902 2903
    size_t i;
    int cell;
    int ret;
2904
    xenUnifiedPrivatePtr priv = conn->privateData;
D
Daniel P. Berrange 已提交
2905 2906

    if (priv->nbNodeCells < 0) {
2907 2908
        virReportError(VIR_ERR_XEN_CALL, "%s",
                       _("cannot determine actual number of cells"));
2909
        return -1;
2910 2911
    }

D
Daniel P. Berrange 已提交
2912
    if ((maxCells < 1) || (startCell >= priv->nbNodeCells)) {
2913 2914
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("invalid argument"));
2915 2916
        return -1;
    }
2917

2918
    /*
P
Philipp Hahn 已提交
2919
     * Support only hv_versions.sys_interface >=4
2920
     */
P
Philipp Hahn 已提交
2921
    if (hv_versions.sys_interface < SYS_IFACE_MIN_VERS_NUMA) {
2922 2923
        virReportError(VIR_ERR_XEN_CALL, "%s",
                       _("unsupported in sys interface < 4"));
2924 2925 2926 2927 2928 2929
        return -1;
    }

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

2930 2931
    for (cell = startCell, i = 0;
         cell < priv->nbNodeCells && i < maxCells; cell++, i++) {
P
Philipp Hahn 已提交
2932
        if (hv_versions.sys_interface >= 5)
2933
            op_sys.u.availheap5.node = cell;
2934
        else
2935
            op_sys.u.availheap.node = cell;
2936
        ret = xenHypervisorDoV2Sys(priv->handle, &op_sys);
2937
        if (ret < 0)
2938
            return -1;
P
Philipp Hahn 已提交
2939
        if (hv_versions.sys_interface >= 5)
2940
            freeMems[i] = op_sys.u.availheap5.avail_bytes;
2941
        else
2942
            freeMems[i] = op_sys.u.availheap.avail_bytes;
2943
    }
2944
    return i;
2945 2946 2947
}


2948 2949
/**
 * xenHypervisorSetMaxMemory:
2950
 * @domain: pointer to the domain block
2951 2952
 * @memory: the max memory size in kilobytes.
 *
E
Eric Blake 已提交
2953
 * Do a hypervisor call to change the maximum amount of memory used
2954 2955 2956 2957
 *
 * Returns 0 in case of success, -1 in case of error.
 */
int
2958 2959 2960
xenHypervisorSetMaxMemory(virConnectPtr conn,
                          virDomainDefPtr def,
                          unsigned long memory)
2961
{
2962
    int ret;
2963
    xenUnifiedPrivatePtr priv = conn->privateData;
2964

2965
    ret = virXen_setmaxmem(priv->handle, def->id, memory);
2966
    if (ret < 0)
2967 2968
        return -1;
    return 0;
2969
}
2970

2971

2972 2973 2974 2975 2976 2977
/**
 * 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
2978
 *
2979 2980 2981 2982 2983 2984
 * 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
2985 2986 2987 2988 2989
xenHypervisorPinVcpu(virConnectPtr conn,
                     virDomainDefPtr def,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
2990
{
2991
    int ret;
2992
    xenUnifiedPrivatePtr priv = conn->privateData;
2993

2994
    ret = virXen_setvcpumap(priv->handle, def->id, vcpu,
2995 2996
                            cpumap, maplen);
    if (ret < 0)
2997 2998
        return -1;
    return 0;
2999 3000 3001 3002 3003 3004 3005
}

/**
 * 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 已提交
3006
 * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this domain (in 8-bit bytes) (OUT)
D
Daniel Veillard 已提交
3007
 *	If cpumaps is NULL, then no cpumap information is returned by the API.
3008 3009 3010 3011 3012 3013
 *	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...).
3014
 *
3015
 * Extract information about virtual CPUs of domain, store it in info array
R
Richard W.M. Jones 已提交
3016
 * and also in cpumaps if this pointer isn't NULL.
3017 3018 3019 3020
 *
 * Returns the number of info filled in case of success, -1 in case of failure.
 */
int
3021 3022
xenHypervisorGetVcpus(virConnectPtr conn,
                      virDomainDefPtr def,
3023 3024 3025 3026
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
3027
{
3028
    xen_getdomaininfo dominfo;
3029
    int ret;
3030
    xenUnifiedPrivatePtr priv = conn->privateData;
3031
    virVcpuInfoPtr ipt;
3032 3033
    int nbinfo;
    size_t i;
3034

3035
    if (sizeof(cpumap_t) & 7) {
3036
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3037
                       _("invalid cpumap_t size"));
3038
        return -1;
3039
    }
3040

3041
    /* first get the number of virtual CPUs in this domain */
3042
    XEN_GETDOMAININFO_CLEAR(dominfo);
3043
    ret = virXen_getdomaininfo(priv->handle, def->id,
3044
                               &dominfo);
3045

3046
    if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id)) {
3047 3048
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get domain details"));
3049
        return -1;
3050
    }
3051
    nbinfo = XEN_GETDOMAININFO_CPUCOUNT(dominfo) + 1;
3052 3053 3054
    if (nbinfo > maxinfo) nbinfo = maxinfo;

    if (cpumaps != NULL)
3055
        memset(cpumaps, 0, maxinfo * maplen);
3056

3057 3058
    for (i = 0, ipt = info; i < nbinfo; i++, ipt++) {
        if ((cpumaps != NULL) && (i < maxinfo)) {
3059
            ret = virXen_getvcpusinfo(priv->handle, def->id, i,
3060 3061 3062
                                      ipt,
                                      (unsigned char *)VIR_GET_CPUMAP(cpumaps, maplen, i),
                                      maplen);
3063
            if (ret < 0) {
3064 3065
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get VCPUs info"));
3066
                return -1;
3067
            }
3068
        } else {
3069
            ret = virXen_getvcpusinfo(priv->handle, def->id, i,
3070
                                      ipt, NULL, 0);
3071
            if (ret < 0) {
3072 3073
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get VCPUs info"));
3074
                return -1;
3075
            }
3076
        }
3077 3078 3079
    }
    return nbinfo;
}
3080

3081 3082 3083 3084 3085 3086 3087 3088 3089
/**
 * 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
3090 3091
xenHypervisorGetVcpuMax(virConnectPtr conn,
                        virDomainDefPtr def)
3092 3093 3094 3095
{
    xen_getdomaininfo dominfo;
    int ret;
    int maxcpu;
3096
    xenUnifiedPrivatePtr priv = conn->privateData;
3097 3098

    /* inactive domain */
3099
    if (def->id < 0) {
3100 3101 3102
        maxcpu = MAX_VIRT_CPUS;
    } else {
        XEN_GETDOMAININFO_CLEAR(dominfo);
3103
        ret = virXen_getdomaininfo(priv->handle, def->id,
3104 3105
                                   &dominfo);

3106
        if ((ret < 0) || (XEN_GETDOMAININFO_DOMAIN(dominfo) != def->id))
3107
            return -1;
3108 3109 3110 3111 3112 3113
        maxcpu = XEN_GETDOMAININFO_MAXCPUID(dominfo) + 1;
    }

    return maxcpu;
}

J
John Levon 已提交
3114 3115 3116 3117 3118 3119
/**
 * xenHavePrivilege()
 *
 * Return true if the current process should be able to connect to Xen.
 */
int
3120
xenHavePrivilege(void)
J
John Levon 已提交
3121 3122
{
#ifdef __sun
3123
    return priv_ineffect(PRIV_XVM_CONTROL);
J
John Levon 已提交
3124
#else
3125
    return access(XEN_HYPERVISOR_SOCKET, R_OK) == 0;
J
John Levon 已提交
3126 3127
#endif
}