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

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 57 58 59 60 61
    class MiniSubtest(test_module.Subtest):
        """
        subtest base class for actual tests
        """
        def __new__(cls, *args, **kargs):
            self = test.__new__(cls)
            ret = None
            if args is None:
                args = []
            try:
                ret = self.test(*args, **kargs)
            finally:
                if hasattr(self, "clean"):
                    self.clean()
            return ret

        def clean(self):
            """
            cleans up running VM instance
            """
            if (hasattr(self, "vm")):
                vm = getattr(self, "vm")
                if vm.is_alive():
                    vm.pause()
                    vm.destroy(gracefully=False)

        def test(self):
            """
            stub for actual test code
            """
            raise error.TestFail("test() must be redifined in subtest")

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    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
89 90 91

    class test_qemu_cpu_models_list(MiniSubtest):
        """
92
        check CPU models returned by <qemu> -cpu '?' are what is expected
93 94 95 96 97
        """
        def test(self):
            """
            test method
            """
98
            cpu_models = cpu_models_to_test()
99
            qemu_models = utils_misc.get_qemu_cpu_models(qemu_binary)
100 101
            missing = set(cpu_models) - set(qemu_models)
            if missing:
102
                raise error.TestFail("Some CPU models not in QEMU CPU model list: %s")
103 104
            added = set(qemu_models) - set(cpu_models)
            if added:
105
                logging.info("Extra CPU models in QEMU CPU listing: %s", added)
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    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


147
    def get_guest_cpuid(self, cpu_model, feature=None, extra_params=None):
148 149
        test_kernel_dir = os.path.join(test.virtdir, "deps",
                                       "cpuid_test_kernel")
150 151 152
        os.chdir(test_kernel_dir)
        utils.make("cpuid_dump_kernel.bin")

153
        vm_name = params['main_vm']
154 155 156 157 158 159
        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"]
160 161
        if extra_params:
            params_b.update(extra_params)
162 163 164 165 166 167 168 169 170 171 172
        env_process.preprocess_vm(self, params_b, env, vm_name)
        vm = env.get_vm(vm_name)
        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.")

173 174
        test_output = parse_cpuid_dump(vm.serial_console.get_output())
        if test_output is None:
175
            raise error.TestFail("Test output signature not found in "
176 177
                                 "output:\n %s", vm.serial_console.get_output())
        self.clean()
178
        return test_output
179

180
    def cpuid_to_vendor(cpuid_dump, idx):
181
        r = cpuid_dump[idx, 0]
182
        dst =  []
I
Igor Mammedov 已提交
183 184 185 186 187 188
        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))
189 190 191 192 193 194 195 196
        return ''.join(dst)

    class default_vendor(MiniSubtest):
        """
        Boot qemu with specified cpu models and
        verify that CPU vendor matches requested
        """
        def test(self):
197
            cpu_models = cpu_models_to_test()
198

199 200 201 202 203
            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()
204 205 206 207 208 209

            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)
210
                guest_vendor = cpuid_to_vendor(out, 0x00000000)
211 212 213 214 215 216
                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))

I
Igor Mammedov 已提交
217 218 219 220 221 222
    class custom_vendor(MiniSubtest):
        """
        Boot qemu with specified vendor
        """
        def test(self):
            has_error = False
223
            vendor = params["vendor"]
I
Igor Mammedov 已提交
224 225 226

            try:
                out = get_guest_cpuid(self, cpu_model, "vendor=" + vendor)
227 228
                guest_vendor0 = cpuid_to_vendor(out, 0x00000000)
                guest_vendor80000000 = cpuid_to_vendor(out, 0x80000000)
I
Igor Mammedov 已提交
229 230 231
                logging.debug("Guest's vendor[0]: " + guest_vendor0)
                logging.debug("Guest's vendor[0x80000000]: " +
                              guest_vendor80000000)
232
                if guest_vendor0 != vendor:
I
Igor Mammedov 已提交
233 234 235
                    raise error.TestFail("Guest vendor[0] [%s], doesn't match "
                                         "required vendor [%s] for CPU [%s]" %
                                         (guest_vendor0, vendor, cpu_model))
236
                if guest_vendor80000000 != vendor:
I
Igor Mammedov 已提交
237 238 239 240 241 242 243 244 245 246 247 248
                    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 已提交
249
    def cpuid_to_level(cpuid_dump):
250
        r = cpuid_dump[0, 0]
I
Igor Mammedov 已提交
251 252 253 254 255 256 257 258
        return r['eax']

    class custom_level(MiniSubtest):
        """
        Boot qemu with specified level
        """
        def test(self):
            has_error = False
259
            level = params["level"]
I
Igor Mammedov 已提交
260
            try:
261
                out = get_guest_cpuid(self, cpu_model, "level=" + level)
I
Igor Mammedov 已提交
262
                guest_level = str(cpuid_to_level(out))
263
                if guest_level != level:
I
Igor Mammedov 已提交
264 265
                    raise error.TestFail("Guest's level [%s], doesn't match "
                                         "required level [%s]" %
266
                                         (guest_level, level))
I
Igor Mammedov 已提交
267 268 269 270 271 272 273
            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 已提交
274 275 276 277
    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)
278
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
279 280 281 282 283 284 285 286 287 288 289 290
        family = (eax >> 8) & 0xf
        if family  == 0xf:
            # extract extendend family
            return family + ((eax >> 20) & 0xff)
        return family

    class custom_family(MiniSubtest):
        """
        Boot qemu with specified family
        """
        def test(self):
            has_error = False
291
            family = params["family"]
I
Igor Mammedov 已提交
292
            try:
293
                out = get_guest_cpuid(self, cpu_model, "family=" + family)
I
Igor Mammedov 已提交
294
                guest_family = str(cpuid_to_family(out))
295
                if guest_family != family:
I
Igor Mammedov 已提交
296 297
                    raise error.TestFail("Guest's family [%s], doesn't match "
                                         "required family [%s]" %
298
                                         (guest_family, family))
I
Igor Mammedov 已提交
299 300 301 302 303 304 305
            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 已提交
306 307 308 309
    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)
310
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
311 312 313 314 315 316 317 318 319 320 321
        model = (eax >> 4) & 0xf
        # extended model
        model |= (eax >> 12) & 0xf0
        return model

    class custom_model(MiniSubtest):
        """
        Boot qemu with specified model
        """
        def test(self):
            has_error = False
322
            model = params["model"]
I
Igor Mammedov 已提交
323
            try:
324
                out = get_guest_cpuid(self, cpu_model, "model=" + model)
I
Igor Mammedov 已提交
325
                guest_model = str(cpuid_to_model(out))
326
                if guest_model != model:
I
Igor Mammedov 已提交
327 328
                    raise error.TestFail("Guest's model [%s], doesn't match "
                                         "required model [%s]" %
329
                                         (guest_model, model))
I
Igor Mammedov 已提交
330 331 332 333 334 335 336
            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 已提交
337 338 339 340
    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)
341
        eax = cpuid_dump[1, 0]['eax']
I
Igor Mammedov 已提交
342 343 344 345 346 347 348 349 350
        stepping = eax & 0xf
        return stepping

    class custom_stepping(MiniSubtest):
        """
        Boot qemu with specified stepping
        """
        def test(self):
            has_error = False
351
            stepping = params["stepping"]
I
Igor Mammedov 已提交
352
            try:
353
                out = get_guest_cpuid(self, cpu_model, "stepping=" + stepping)
I
Igor Mammedov 已提交
354
                guest_stepping = str(cpuid_to_stepping(out))
355
                if guest_stepping != stepping:
I
Igor Mammedov 已提交
356 357
                    raise error.TestFail("Guest's stepping [%s], doesn't match "
                                         "required stepping [%s]" %
358
                                         (guest_stepping, stepping))
I
Igor Mammedov 已提交
359 360 361 362 363 364 365
            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 已提交
366 367 368 369
    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)
370
        return cpuid_dump[0x80000000, 0x00]['eax']
I
Igor Mammedov 已提交
371 372 373 374 375 376 377

    class custom_xlevel(MiniSubtest):
        """
        Boot qemu with specified xlevel
        """
        def test(self):
            has_error = False
378
            xlevel = params["xlevel"]
I
Igor Mammedov 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
            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 已提交
397 398 399 400 401 402
    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 = ""
403 404
        for idx in (0x80000002, 0x80000003, 0x80000004):
            regs = cpuid_dump[idx, 0]
I
Igor Mammedov 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418
            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

    class custom_model_id(MiniSubtest):
        """
        Boot qemu with specified model_id
        """
        def test(self):
            has_error = False
419
            model_id = params["model_id"]
I
Igor Mammedov 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

            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")

436
    def cpuid_regs_to_string(cpuid_dump, leaf, idx, regs):
437
        r = cpuid_dump[leaf, idx]
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        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

    class cpuid_signature(MiniSubtest):
        """
        test signature in specified leaf:index:regs
        """
        def test(self):
            has_error = False
            flags = params.get("flags","")
457 458
            leaf = int(params.get("leaf","0x40000000"), 0)
            idx = int(params.get("index","0x00"), 0)
459
            regs = params.get("regs","ebx ecx edx").split()
460
            signature = params["signature"]
461 462
            try:
                out = get_guest_cpuid(self, cpu_model, flags)
463 464
                _signature = cpuid_regs_to_string(out, leaf, idx, regs)
                if _signature != signature:
465 466
                    raise error.TestFail("Guest's signature [%s], doesn't"
                                         "match required signature [%s]" %
467
                                         (_signature, signature))
468 469 470 471 472 473 474
            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")

475 476 477 478 479 480 481
    class cpuid_bit_test(MiniSubtest):
        """
        test bits in specified leaf:func:reg
        """
        def test(self):
            has_error = False
            flags = params.get("flags","")
482 483
            leaf = int(params.get("leaf","0x40000000"), 0)
            idx = int(params.get("index","0x00"), 0)
484
            reg = params.get("reg","eax")
485
            bits = params["bits"].split()
486 487
            try:
                out = get_guest_cpuid(self, cpu_model, flags)
488
                r = out[leaf, idx][reg]
489 490 491 492 493 494 495 496 497 498 499 500
                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")

I
Igor Mammedov 已提交
501 502 503 504 505 506 507
    class cpuid_reg_test(MiniSubtest):
        """
        test register value in specified leaf:index:reg
        """
        def test(self):
            has_error = False
            flags = params.get("flags","")
508 509
            leaf = int(params.get("leaf", "0x00"), 0)
            idx = int(params.get("index","0x00"), 0)
I
Igor Mammedov 已提交
510
            reg = params.get("reg","eax")
511
            val = int(params["value"], 0)
I
Igor Mammedov 已提交
512 513
            try:
                out = get_guest_cpuid(self, cpu_model, flags)
514
                r = out[leaf, idx][reg]
I
Igor Mammedov 已提交
515 516 517 518 519 520 521 522 523 524 525
                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")

526 527

    # subtests runner
528
    test_type = params["test_type"]
529 530
    if test_type in locals():
        tests_group = locals()[test_type]
531
        tests_group()
532 533 534
    else:
        raise error.TestError("Test group '%s' is not defined in"
                              " test" % test_type)