cpuid.py 21.7 KB
Newer Older
1 2 3
"""
Group of cpuid tests for X86 CPU
"""
4
import re, sys, os, string
5 6
from autotest.client.shared import error, utils
from autotest.client.shared import test as test_module
7
from virttest import utils_misc, env_process, virt_vm
8

9 10 11 12
import logging
logger = logging.getLogger(__name__)
dbg = logger.debug
info = logger.info
13 14 15 16 17 18 19 20 21

def run_cpuid(test, params, env):
    """
    Boot guest with different cpu_models and cpu flags and check if guest works correctly.

    @param test: kvm test object.
    @param params: Dictionary with the test parameters.
    @param env: Dictionary with test environment.
    """
22
    qemu_binary = utils_misc.get_qemu_binary(params)
23

I
Igor Mammedov 已提交
24 25 26 27 28 29
    cpu_model = params.get("cpu_model", "qemu64")

    xfail = False
    if (params.get("xfail") is not None) and (params.get("xfail") == "yes"):
        xfail = True

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    def cpu_models_to_test():
        """Return the list of CPU models to be tested, based on the
        cpu_models and cpu_model config options.

        Config option "cpu_model" may be used to ask a single CPU model
        to be tested. Config option "cpu_models" may be used to ask
        multiple CPU models to be tested.

        If cpu_models is "*", all CPU models reported by QEMU will be tested.
        """
        models_opt = params.get("cpu_models")
        model_opt = params.get("cpu_model")

        if (models_opt is None and model_opt is None):
            raise error.TestError("No cpu_models or cpu_model option is set")

        cpu_models = set()

        if models_opt == '*':
            cpu_models.update(utils_misc.get_qemu_cpu_models(qemu_binary))
        elif models_opt:
            cpu_models.update(models_opt.split())

        if model_opt:
            cpu_models.add(model_opt)

        return cpu_models
57

58
    def test_qemu_cpu_models_list(self):
59
        """
60
        check CPU models returned by <qemu> -cpu '?' are what is expected
61
        """
62 63 64 65 66 67 68
        """
        test method
        """
        cpu_models = cpu_models_to_test()
        qemu_models = utils_misc.get_qemu_cpu_models(qemu_binary)
        missing = set(cpu_models) - set(qemu_models)
        if missing:
69
            raise error.TestFail("Some CPU models not in QEMU CPU model list: %r" % (missing))
70 71 72
        added = set(qemu_models) - set(cpu_models)
        if added:
            logging.info("Extra CPU models in QEMU CPU listing: %s", added)
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    def compare_cpuid_output(a, b):
        """
        Generates a list of (register, bit, va, vb) tuples for
        each bit that is different between a and b.
        """
        for reg in ('eax', 'ebx', 'ecx', 'edx'):
            for bit in range(32):
                ba = (a[reg] & (1 << bit)) >> bit
                bb = (b[reg] & (1 << bit)) >> bit
                if ba <> bb:
                    yield (reg, bit, ba, bb)

    def parse_cpuid_dump(output):
        dbg("parsing cpuid dump: %r", output)
        cpuid_re = re.compile("^ *(0x[0-9a-f]+) +0x([0-9a-f]+): +eax=0x([0-9a-f]+) ebx=0x([0-9a-f]+) ecx=0x([0-9a-f]+) edx=0x([0-9a-f]+)$")
        out_lines = output.splitlines()
        if out_lines[0] <> '==START TEST==' or out_lines[-1] <> '==END TEST==':
            dbg("cpuid dump doesn't have expected delimiters")
            return None
        if out_lines[1] <> 'CPU:':
            dbg("cpuid dump doesn't start with 'CPU:' line")
            return None
        result = {}
        for l in out_lines[2:-1]:
            m = cpuid_re.match(l)
            if m is None:
                dbg("invalid cpuid dump line: %r", l)
                return None
            in_eax = int(m.group(1), 16)
            in_ecx = int(m.group(2), 16)
            out = {
                'eax':int(m.group(3), 16),
                'ebx':int(m.group(4), 16),
                'ecx':int(m.group(5), 16),
                'edx':int(m.group(6), 16),
            }
            result[(in_eax, in_ecx)] = out
        return result


114
    def get_guest_cpuid(self, cpu_model, feature=None, extra_params=None):
115 116
        test_kernel_dir = os.path.join(test.virtdir, "deps",
                                       "cpuid_test_kernel")
117 118 119
        os.chdir(test_kernel_dir)
        utils.make("cpuid_dump_kernel.bin")

120
        vm_name = params['main_vm']
121 122 123 124 125 126
        params_b = params.copy()
        params_b["kernel"] = os.path.join(test_kernel_dir, "cpuid_dump_kernel.bin")
        params_b["cpu_model"] = cpu_model
        params_b["cpu_model_flags"] = feature
        del params_b["images"]
        del params_b["nics"]
127 128
        if extra_params:
            params_b.update(extra_params)
129 130
        env_process.preprocess_vm(self, params_b, env, vm_name)
        vm = env.get_vm(vm_name)
131
        dbg('is dead: %r', vm.is_dead())
132 133 134 135 136 137 138 139 140
        vm.create()
        self.vm = vm
        vm.resume()

        timeout = float(params.get("login_timeout", 240))
        f = lambda: re.search("==END TEST==", vm.serial_console.get_output())
        if not utils_misc.wait_for(f, timeout, 1):
            raise error.TestFail("Could not get test complete message.")

141 142
        test_output = parse_cpuid_dump(vm.serial_console.get_output())
        if test_output is None:
143
            raise error.TestFail("Test output signature not found in "
144
                                 "output:\n %s", vm.serial_console.get_output())
145
        vm.destroy(gracefully=False)
146
        return test_output
147

148
    def cpuid_to_vendor(cpuid_dump, idx):
149
        r = cpuid_dump[idx, 0]
150
        dst =  []
I
Igor Mammedov 已提交
151 152 153 154 155 156
        map(lambda i:
            dst.append((chr(r['ebx'] >> (8 * i) & 0xff))), range(0, 4))
        map(lambda i:
            dst.append((chr(r['edx'] >> (8 * i) & 0xff))), range(0, 4))
        map(lambda i:
            dst.append((chr(r['ecx'] >> (8 * i) & 0xff))), range(0, 4))
157 158
        return ''.join(dst)

159
    def default_vendor(self):
160 161 162 163
        """
        Boot qemu with specified cpu models and
        verify that CPU vendor matches requested
        """
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        cpu_models = cpu_models_to_test()

        vendor = params.get("vendor")
        if vendor is None or vendor == "host":
            cmd = "grep 'vendor_id' /proc/cpuinfo | head -n1 | awk '{print $3}'"
            cmd_result = utils.run(cmd, ignore_status=True)
            vendor = cmd_result.stdout.strip()

        ignore_cpus = set(params.get("ignore_cpu_models","").split(' '))
        cpu_models = cpu_models - ignore_cpus

        for cpu_model in cpu_models:
            out = get_guest_cpuid(self, cpu_model)
            guest_vendor = cpuid_to_vendor(out, 0x00000000)
            logging.debug("Guest's vendor: " + guest_vendor)
            if guest_vendor != vendor:
                raise error.TestFail("Guest vendor [%s], doesn't match "
                                     "required vendor [%s] for CPU [%s]" %
                                     (guest_vendor, vendor, cpu_model))

    def custom_vendor(self):
I
Igor Mammedov 已提交
185 186 187
        """
        Boot qemu with specified vendor
        """
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        has_error = False
        vendor = params["vendor"]

        try:
            out = get_guest_cpuid(self, cpu_model, "vendor=" + vendor)
            guest_vendor0 = cpuid_to_vendor(out, 0x00000000)
            guest_vendor80000000 = cpuid_to_vendor(out, 0x80000000)
            logging.debug("Guest's vendor[0]: " + guest_vendor0)
            logging.debug("Guest's vendor[0x80000000]: " +
                          guest_vendor80000000)
            if guest_vendor0 != vendor:
                raise error.TestFail("Guest vendor[0] [%s], doesn't match "
                                     "required vendor [%s] for CPU [%s]" %
                                     (guest_vendor0, vendor, cpu_model))
            if guest_vendor80000000 != vendor:
                raise error.TestFail("Guest vendor[0x80000000] [%s], "
                                     "doesn't match required vendor "
                                     "[%s] for CPU [%s]" %
                                     (guest_vendor80000000, vendor,
                                      cpu_model))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
214

I
Igor Mammedov 已提交
215
    def cpuid_to_level(cpuid_dump):
216
        r = cpuid_dump[0, 0]
I
Igor Mammedov 已提交
217 218
        return r['eax']

219
    def custom_level(self):
I
Igor Mammedov 已提交
220 221 222
        """
        Boot qemu with specified level
        """
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        has_error = False
        level = params["level"]
        try:
            out = get_guest_cpuid(self, cpu_model, "level=" + level)
            guest_level = str(cpuid_to_level(out))
            if guest_level != level:
                raise error.TestFail("Guest's level [%s], doesn't match "
                                     "required level [%s]" %
                                     (guest_level, level))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
238

I
Igor Mammedov 已提交
239 240 241 242
    def cpuid_to_family(cpuid_dump):
        # Intel Processor Identification and the CPUID Instruction
        # http://www.intel.com/Assets/PDF/appnote/241618.pdf
        # 5.1.2 Feature Information (Function 01h)
243
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
244 245 246 247 248 249
        family = (eax >> 8) & 0xf
        if family  == 0xf:
            # extract extendend family
            return family + ((eax >> 20) & 0xff)
        return family

250
    def custom_family(self):
I
Igor Mammedov 已提交
251 252 253
        """
        Boot qemu with specified family
        """
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        has_error = False
        family = params["family"]
        try:
            out = get_guest_cpuid(self, cpu_model, "family=" + family)
            guest_family = str(cpuid_to_family(out))
            if guest_family != family:
                raise error.TestFail("Guest's family [%s], doesn't match "
                                     "required family [%s]" %
                                     (guest_family, family))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
269

I
Igor Mammedov 已提交
270 271 272 273
    def cpuid_to_model(cpuid_dump):
        # Intel Processor Identification and the CPUID Instruction
        # http://www.intel.com/Assets/PDF/appnote/241618.pdf
        # 5.1.2 Feature Information (Function 01h)
274
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
275 276 277 278 279
        model = (eax >> 4) & 0xf
        # extended model
        model |= (eax >> 12) & 0xf0
        return model

280
    def custom_model(self):
I
Igor Mammedov 已提交
281 282 283
        """
        Boot qemu with specified model
        """
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        has_error = False
        model = params["model"]
        try:
            out = get_guest_cpuid(self, cpu_model, "model=" + model)
            guest_model = str(cpuid_to_model(out))
            if guest_model != model:
                raise error.TestFail("Guest's model [%s], doesn't match "
                                     "required model [%s]" %
                                     (guest_model, model))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
299

I
Igor Mammedov 已提交
300 301 302 303
    def cpuid_to_stepping(cpuid_dump):
        # Intel Processor Identification and the CPUID Instruction
        # http://www.intel.com/Assets/PDF/appnote/241618.pdf
        # 5.1.2 Feature Information (Function 01h)
304
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
305 306 307
        stepping = eax & 0xf
        return stepping

308
    def custom_stepping(self):
I
Igor Mammedov 已提交
309 310 311
        """
        Boot qemu with specified stepping
        """
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        has_error = False
        stepping = params["stepping"]
        try:
            out = get_guest_cpuid(self, cpu_model, "stepping=" + stepping)
            guest_stepping = str(cpuid_to_stepping(out))
            if guest_stepping != stepping:
                raise error.TestFail("Guest's stepping [%s], doesn't match "
                                     "required stepping [%s]" %
                                     (guest_stepping, stepping))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
327

I
Igor Mammedov 已提交
328 329 330 331
    def cpuid_to_xlevel(cpuid_dump):
        # Intel Processor Identification and the CPUID Instruction
        # http://www.intel.com/Assets/PDF/appnote/241618.pdf
        # 5.2.1 Largest Extendend Function # (Function 80000000h)
332
        return cpuid_dump[0x80000000, 0x00]['eax']
I
Igor Mammedov 已提交
333

334
    def custom_xlevel(self):
I
Igor Mammedov 已提交
335 336 337
        """
        Boot qemu with specified xlevel
        """
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        has_error = False
        xlevel = params["xlevel"]
        if params.get("expect_xlevel") is not None:
            xlevel = params.get("expect_xlevel")

        try:
            out = get_guest_cpuid(self, cpu_model, "xlevel=" +
                                  params.get("xlevel"))
            guest_xlevel = str(cpuid_to_xlevel(out))
            if guest_xlevel != xlevel:
                raise error.TestFail("Guest's xlevel [%s], doesn't match "
                                     "required xlevel [%s]" %
                                     (guest_xlevel, xlevel))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
357

I
Igor Mammedov 已提交
358 359 360 361 362 363
    def cpuid_to_model_id(cpuid_dump):
        # Intel Processor Identification and the CPUID Instruction
        # http://www.intel.com/Assets/PDF/appnote/241618.pdf
        # 5.2.3 Processor Brand String (Functions 80000002h, 80000003h,
        # 80000004h)
        m_id = ""
364 365
        for idx in (0x80000002, 0x80000003, 0x80000004):
            regs = cpuid_dump[idx, 0]
I
Igor Mammedov 已提交
366 367 368 369 370 371 372 373
            for name in ('eax', 'ebx', 'ecx', 'edx'):
                for shift in range(4):
                    c = ((regs[name] >> (shift * 8)) & 0xff)
                    if c == 0: # drop trailing \0-s
                        break
                    m_id += chr(c)
        return m_id

374
    def custom_model_id(self):
I
Igor Mammedov 已提交
375 376 377
        """
        Boot qemu with specified model_id
        """
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        has_error = False
        model_id = params["model_id"]

        try:
            out = get_guest_cpuid(self, cpu_model, "model_id='%s'" %
                                  model_id)
            guest_model_id = cpuid_to_model_id(out)
            if guest_model_id != model_id:
                raise error.TestFail("Guest's model_id [%s], doesn't match "
                                     "required model_id [%s]" %
                                     (guest_model_id, model_id))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
395

396
    def cpuid_regs_to_string(cpuid_dump, leaf, idx, regs):
397
        r = cpuid_dump[leaf, idx]
398 399 400 401 402 403 404 405 406 407 408 409
        signature = ""
        for i in regs:
            for shift in range(0, 4):
                c = chr((r[i] >> (shift * 8)) & 0xFF)
                if c in string.printable:
                    signature = signature + c
                else:
                    signature = "%s\\x%02x" % (signature, ord(c))
        logging.debug("(%s.%s:%s: signature: %s" % (leaf, idx, str(regs),
                                                    signature))
        return signature

410
    def cpuid_signature(self):
411 412 413
        """
        test signature in specified leaf:index:regs
        """
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        has_error = False
        flags = params.get("flags","")
        leaf = int(params.get("leaf","0x40000000"), 0)
        idx = int(params.get("index","0x00"), 0)
        regs = params.get("regs","ebx ecx edx").split()
        signature = params["signature"]
        try:
            out = get_guest_cpuid(self, cpu_model, flags)
            _signature = cpuid_regs_to_string(out, leaf, idx, regs)
            if _signature != signature:
                raise error.TestFail("Guest's signature [%s], doesn't"
                                     "match required signature [%s]" %
                                     (_signature, signature))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")

    def cpuid_bit_test(self):
435 436 437
        """
        test bits in specified leaf:func:reg
        """
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
        has_error = False
        flags = params.get("flags","")
        leaf = int(params.get("leaf","0x40000000"), 0)
        idx = int(params.get("index","0x00"), 0)
        reg = params.get("reg","eax")
        bits = params["bits"].split()
        try:
            out = get_guest_cpuid(self, cpu_model, flags)
            r = out[leaf, idx][reg]
            logging.debug("CPUID(%s.%s).%s=0x%08x" % (leaf, idx, reg, r))
            for i in bits:
                if (r & (1 << int(i))) == 0:
                    raise error.TestFail("CPUID(%s.%s).%s[%s] is not set" %
                                         (leaf, idx, reg, i))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")

    def cpuid_reg_test(self):
I
Igor Mammedov 已提交
460 461 462
        """
        test register value in specified leaf:index:reg
        """
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        has_error = False
        flags = params.get("flags","")
        leaf = int(params.get("leaf", "0x00"), 0)
        idx = int(params.get("index","0x00"), 0)
        reg = params.get("reg","eax")
        val = int(params["value"], 0)
        try:
            out = get_guest_cpuid(self, cpu_model, flags)
            r = out[leaf, idx][reg]
            logging.debug("CPUID(%s.%s).%s=0x%08x" % (leaf, idx, reg, r))
            if r != val:
                raise error.TestFail("CPUID(%s.%s).%s is not 0x%08x" %
                                     (leaf, idx, reg, val))
        except:
            has_error = True
            if xfail is False:
                raise
        if (has_error is False) and (xfail is True):
            raise error.TestFail("Test was expected to fail, but it didn't")
I
Igor Mammedov 已提交
482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    def check_cpuid_dump(self):
        """
        Compare full CPUID dump data
        """
        machine_type = params.get("machine_type_to_check","")
        kvm_enabled = params.get("enable_kvm", "yes") == "yes"

        ignore_cpuid_leaves = params.get("ignore_cpuid_leaves", "")
        ignore_cpuid_leaves = ignore_cpuid_leaves.split()
        whitelist = []
        for l in ignore_cpuid_leaves:
            l = l.split(',')
            # syntax of ignore_cpuid_leaves:
            # <in_eax>[,<in_ecx>[,<register>[ ,<bit>]]] ...
            for i in 0,1,3: # integer fields:
                if len(l) > i:
                    l[i] = int(l[i], 0)
            whitelist.append(tuple(l))

        if not machine_type:
            raise error.TestNAError("No machine_type_to_check defined")
504 505 506 507 508
        cpu_model_flags = params.get('cpu_model_flags', '')
        full_cpu_model_name = cpu_model
        if cpu_model_flags:
            full_cpu_model_name += ','
            full_cpu_model_name += cpu_model_flags.lstrip(',')
509 510 511
        ref_file = os.path.join(test.virtdir, "deps",
                                "cpuid_dumps",
                                kvm_enabled and "kvm" or "nokvm",
512
                                machine_type, '%s-dump.txt' % (full_cpu_model_name))
513 514 515 516 517 518 519 520 521
        if not os.path.exists(ref_file):
            raise error.TestNAError("no cpuid dump file: %s" % (ref_file))
        reference = open(ref_file, 'r').read()
        if not reference:
            raise error.TestNAError("no cpuid dump data on file: %s" % (ref_file))
        reference = parse_cpuid_dump(reference)
        if reference is None:
            raise error.TestNAError("couldn't parse reference cpuid dump from file; %s" % (ref_file))
        try:
522
            out = get_guest_cpuid(self, cpu_model, cpu_model_flags + ',enforce',
523 524 525 526
                                  extra_params=dict(machine_type=machine_type, smp=1))
        except virt_vm.VMCreateError,e:
            if "host doesn't support requested feature:" in e.output \
                or ("host cpuid" in e.output and \
527 528
                    ("lacks requested flag" in e.output or
                     "flag restricted to guest" in e.output)):
529
                raise error.TestNAError("Can't run CPU model %s on this host" % (full_cpu_model_name))
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
            else:
                raise
        dbg('ref_file: %r', ref_file)
        dbg('ref: %r', reference)
        dbg('out: %r', out)
        ok = True
        for k in reference.keys():
            in_eax,in_ecx = k
            if k not in out:
                info("Missing CPUID data from output: CPUID[0x%x,0x%x]", in_eax, in_ecx)
                ok = False
                continue
            diffs = compare_cpuid_output(reference[k], out[k])
            for d in diffs:
                reg, bit, vreference, vout =d
                whitelisted = (in_eax,) in whitelist \
                    or (in_eax, in_ecx) in whitelist \
                    or (in_eax, in_ecx, reg) in whitelist \
                    or (in_eax, in_ecx, reg, bit) in whitelist
                info("Non-matching bit: CPUID[0x%x,0x%x].%s[%d]: found %s instead of %s%s",
                     in_eax, in_ecx, reg, bit, vout, vreference,
                     whitelisted and " (whitelisted)" or "")
                if not whitelisted:
                    ok = False
        if not ok:
            raise error.TestFail("Unexpected CPUID data")
556 557

    # subtests runner
558
    test_type = params["test_type"]
559 560
    if test_type not in locals():
        raise error.TestError("Test function '%s' is not defined in"
561
                              " test" % test_type)
562 563 564

    test_func = locals()[test_type]
    return test_func(test)