Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c5a5ee9d9104dcb59806db88a8900e9261fd360a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
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
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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*******************************************************************************
 * Copyright (c) 2014 École Polytechnique de Montréal
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Mohamad Gebai - Initial API and implementation
 *******************************************************************************/

package org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.module;

import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.tracecompass.common.core.NonNullUtils;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.Activator;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.VcpuStateValues;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.VmAttributes;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.model.HostThread;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.model.IVirtualMachineModel;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.model.VirtualCPU;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.model.VirtualMachine;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.analysis.vm.model.qemukvm.QemuKvmVmModel;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.trace.layout.IKernelAnalysisEventLayout;
import org.eclipse.tracecompass.internal.lttng2.kernel.core.trace.layout.LttngEventLayout;
import org.eclipse.tracecompass.lttng2.kernel.core.analysis.kernel.LttngKernelAnalysis;
import org.eclipse.tracecompass.lttng2.kernel.core.analysis.kernel.LttngKernelThreadInformationProvider;
import org.eclipse.tracecompass.lttng2.kernel.core.trace.LttngKernelTrace;
import org.eclipse.tracecompass.statesystem.core.ITmfStateSystemBuilder;
import org.eclipse.tracecompass.statesystem.core.exceptions.AttributeNotFoundException;
import org.eclipse.tracecompass.statesystem.core.exceptions.StateValueTypeException;
import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
import org.eclipse.tracecompass.statesystem.core.statevalue.ITmfStateValue;
import org.eclipse.tracecompass.statesystem.core.statevalue.TmfStateValue;
import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
import org.eclipse.tracecompass.tmf.core.event.aspect.TmfCpuAspect;
import org.eclipse.tracecompass.tmf.core.statesystem.AbstractTmfStateProvider;
import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;
import org.eclipse.tracecompass.tmf.core.trace.experiment.TmfExperiment;
import org.eclipse.tracecompass.tmf.core.trace.experiment.TmfExperimentUtils;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;

/**
 * This is the state provider which translates the virtual machine experiment
 * events to a state system.
 *
 * Attribute tree:
 *
 * <pre>
 * |- Virtual Machines
 * |  |- <Guest Host ID> -> Friendly name (trace name)
 * |  |  |- <VCPU number>
 * |  |  |  |- Status -> <Status value>
 * </pre>
 *
 * The status value of the VCPUs are either {@link VcpuStateValues#VCPU_IDLE},
 * {@link VcpuStateValues#VCPU_UNKNOWN} or {@link VcpuStateValues#VCPU_RUNNING}.
 * Those three values are ORed with flags {@link VcpuStateValues#VCPU_VMM}
 * and/or {@link VcpuStateValues#VCPU_PREEMPT} to indicate respectively whether
 * they are in hypervisor mode or preempted on the host.
 *
 * @author Mohamad Gebai
 */
public class VirtualMachineStateProvider extends AbstractTmfStateProvider {

    /**
     * Version number of this state provider. Please bump this if you modify the
     * contents of the generated state history in some way.
     */
    private static final int VERSION = 1;

    private static final int SCHED_SWITCH_INDEX = 0;

    /* TODO: An analysis should support many hypervisor models */
    private IVirtualMachineModel fModel;
    private final Table<ITmfTrace, String, Integer> fEventNames;
    private final Map<ITmfTrace, IKernelAnalysisEventLayout> fLayouts;

    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------

    /**
     * Constructor
     *
     * @param experiment
     *            The virtual machine experiment
     */
    public VirtualMachineStateProvider(TmfExperiment experiment) {
        super(experiment, ITmfEvent.class, "Virtual Machine State Provider"); //$NON-NLS-1$

        fModel = new QemuKvmVmModel(experiment);
        Table<ITmfTrace, String, Integer> table = NonNullUtils.checkNotNull(HashBasedTable.<ITmfTrace, String, Integer> create());
        fEventNames = table;
        fLayouts = new HashMap<>();
    }

    // ------------------------------------------------------------------------
    // Event names management
    // ------------------------------------------------------------------------

    private void buildEventNames(ITmfTrace trace) {
        IKernelAnalysisEventLayout layout;
        if (trace instanceof LttngKernelTrace) {
            layout = ((LttngKernelTrace) trace).getEventLayout();
        } else {
            /* Fall-back to the base LttngEventLayout */
            layout = LttngEventLayout.getInstance();
        }
        fLayouts.put(trace, layout);
        fEventNames.put(trace, layout.eventSchedSwitch(), SCHED_SWITCH_INDEX);
    }

    // ------------------------------------------------------------------------
    // IStateChangeInput
    // ------------------------------------------------------------------------

    @Override
    public TmfExperiment getTrace() {
        ITmfTrace trace = super.getTrace();
        if (trace instanceof TmfExperiment) {
            return (TmfExperiment) trace;
        }
        throw new IllegalStateException("VirtualMachineStateProvider: The associated trace should be an experiment"); //$NON-NLS-1$
    }

    @Override
    public int getVersion() {
        return VERSION;
    }

    @Override
    public VirtualMachineStateProvider getNewInstance() {
        TmfExperiment trace = getTrace();
        return new VirtualMachineStateProvider(trace);
    }

    @Override
    protected void eventHandle(@Nullable ITmfEvent event) {
        if (event == null) {
            return;
        }

        /* Is the event managed by this analysis */
        final String eventName = event.getType().getName();

        /* TODO When requirements work again, don't hardcode this */
        if (!eventName.equals("sched_switch") && //$NON-NLS-1$
                !fModel.getRequiredEvents().contains(eventName)) {
            return;
        }

        ITmfStateSystemBuilder ss = checkNotNull(getStateSystemBuilder());
        ITmfStateValue value;

        final ITmfEventField content = event.getContent();
        final long ts = event.getTimestamp().getValue();
        final String hostId = event.getTrace().getHostId();
        try {
            /* Do we know this trace's role yet? */
            VirtualMachine host = fModel.getCurrentMachine(event);
            if (host == null) {
                return;
            }

            /* Make sure guest traces are added to the state system */
            if (host.isGuest()) {
                /*
                 * If event from a guest OS, make sure the guest exists in the
                 * state system
                 */
                int vmQuark = -1;
                try {
                    vmQuark = ss.getQuarkRelative(getNodeVirtualMachines(), host.getHostId());
                } catch (AttributeNotFoundException e) {
                    /*
                     * We should enter this catch only once per machine, so it
                     * is not so costly to do compared with adding the trace's
                     * name for each guest event
                     */
                    vmQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), host.getHostId());
                    TmfStateValue machineName = TmfStateValue.newValueString(event.getTrace().getName());
                    ss.modifyAttribute(ts, machineName, vmQuark);
                }
            }

            /* Have the hypervisor models handle the event first */
            fModel.handleEvent(event);

            /* Handle the event here */
            if (!fEventNames.containsRow(event.getTrace())) {
                buildEventNames(event.getTrace());
            }
            Integer idx = fEventNames.get(event.getTrace(), eventName);
            int intval = (idx == null ? -1 : idx.intValue());
            switch (intval) {
            case SCHED_SWITCH_INDEX: // "sched_switch":
            /*
             * Fields: string prev_comm, int32 prev_tid, int32 prev_prio, int64
             * prev_state, string next_comm, int32 next_tid, int32 next_prio
             */
            {
                Integer prevTid = ((Long) content.getField(fLayouts.get(event.getTrace()).fieldPrevTid()).getValue()).intValue();
                Integer nextTid = ((Long) content.getField(fLayouts.get(event.getTrace()).fieldNextTid()).getValue()).intValue();

                if (prevTid == null || nextTid == null) {
                    break;
                }

                if (host.isGuest()) {
                    /* Get the event's CPU */
                    Integer cpu = null;
                    Iterable<TmfCpuAspect> aspects = TmfTraceUtils.getEventAspectsOfClass(event.getTrace(), TmfCpuAspect.class);
                    for (TmfCpuAspect aspect : aspects) {
                        if (!aspect.resolve(event).equals(TmfCpuAspect.CPU_UNAVAILABLE)) {
                            cpu = aspect.resolve(event);
                            break;
                        }
                    }
                    if (cpu == null) {
                        /*
                         * We couldn't find any CPU information, ignore this
                         * event
                         */
                        break;
                    }

                    /*
                     * If sched switch is from a guest, just update the status
                     * of the virtual CPU to either idle or running
                     */
                    int curStatusQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), host.getHostId(),
                            cpu.toString(), VmAttributes.STATUS);
                    value = TmfStateValue.newValueInt(VcpuStateValues.VCPU_IDLE);
                    if (nextTid > 0) {
                        value = TmfStateValue.newValueInt(VcpuStateValues.VCPU_RUNNING);
                    }
                    ss.modifyAttribute(ts, value, curStatusQuark);
                    break;
                }

                /* Event is not from a guest */
                /* Verify if the previous thread corresponds to a virtual CPU */
                HostThread ht = new HostThread(hostId, prevTid);
                VirtualCPU vcpu = fModel.getVirtualCpu(ht);

                /*
                 * If previous thread is virtual CPU, update status of the
                 * virtual CPU to preempted
                 */
                if (vcpu != null) {
                    VirtualMachine vm = vcpu.getVm();

                    int curStatusQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), vm.getHostId(),
                            vcpu.getCpuId().toString(), VmAttributes.STATUS);

                    /* Add the preempted flag to the status */
                    value = ss.queryOngoingState(curStatusQuark);
                    int newVal = Math.max(VcpuStateValues.VCPU_UNKNOWN, value.unboxInt());
                    value = TmfStateValue.newValueInt(newVal | VcpuStateValues.VCPU_PREEMPT);
                    ss.modifyAttribute(ts, value, curStatusQuark);
                }

                /* Verify if the next thread corresponds to a virtual CPU */
                ht = new HostThread(hostId, nextTid);
                vcpu = fModel.getVirtualCpu(ht);

                /*
                 * If next thread is virtual CPU, update status of the virtual
                 * CPU the previous status
                 */
                if (vcpu != null) {
                    VirtualMachine vm = vcpu.getVm();
                    int curStatusQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), vm.getHostId(),
                            vcpu.getCpuId().toString(), VmAttributes.STATUS);

                    /* Remove the preempted flag from the status */
                    value = ss.queryOngoingState(curStatusQuark);
                    int newVal = Math.max(VcpuStateValues.VCPU_UNKNOWN, value.unboxInt());
                    value = TmfStateValue.newValueInt(newVal & ~VcpuStateValues.VCPU_PREEMPT);
                    ss.modifyAttribute(ts, value, curStatusQuark);

                }

            }
                break;

            default:
            /* Other events not covered by the main switch */
            {
                HostThread ht = getCurrentHostThread(event, ts);
                if (ht == null) {
                    break;
                }

                /*
                 * Are we entering the hypervisor mode and if so, which virtual
                 * CPU is concerned?
                 */
                VirtualCPU virtualCpu = fModel.getVCpuEnteringHypervisorMode(event, ht);
                if (virtualCpu != null) {
                    /* Add the hypervisor flag to the status */
                    VirtualMachine vm = virtualCpu.getVm();
                    int curStatusQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), vm.getHostId(),
                            Long.toString(virtualCpu.getCpuId()), VmAttributes.STATUS);
                    value = ss.queryOngoingState(curStatusQuark);
                    int newVal = Math.max(VcpuStateValues.VCPU_UNKNOWN, value.unboxInt());
                    value = TmfStateValue.newValueInt(newVal | VcpuStateValues.VCPU_VMM);
                    ss.modifyAttribute(ts, value, curStatusQuark);
                }

                /*
                 * Are we exiting the hypervisor mode and if so, which virtual
                 * CPU is concerned?
                 */
                virtualCpu = fModel.getVCpuExitingHypervisorMode(event, ht);
                if (virtualCpu != null) {
                    /* Remove the hypervisor flag from the status */
                    VirtualMachine vm = virtualCpu.getVm();
                    int curStatusQuark = ss.getQuarkRelativeAndAdd(getNodeVirtualMachines(), vm.getHostId(),
                            Long.toString(virtualCpu.getCpuId()), VmAttributes.STATUS);
                    value = ss.queryOngoingState(curStatusQuark);
                    int newVal = Math.max(VcpuStateValues.VCPU_UNKNOWN, value.unboxInt());
                    value = TmfStateValue.newValueInt(newVal & ~VcpuStateValues.VCPU_VMM);
                    ss.modifyAttribute(ts, value, curStatusQuark);
                }

            }
                break;
            }

        } catch (AttributeNotFoundException | TimeRangeException | StateValueTypeException e) {
            Activator.getDefault().logError("Error handling event in VirtualMachineStateProvider", e); //$NON-NLS-1$
        }
    }

    // ------------------------------------------------------------------------
    // Convenience methods for commonly-used attribute tree locations
    // ------------------------------------------------------------------------

    private int getNodeVirtualMachines() {
        return checkNotNull(getStateSystemBuilder()).getQuarkAbsoluteAndAdd(VmAttributes.VIRTUAL_MACHINES);
    }

    private @Nullable HostThread getCurrentHostThread(ITmfEvent event, long ts) {
        /* Get the LTTng kernel analysis for the host */
        String hostId = event.getTrace().getHostId();
        LttngKernelAnalysis module = TmfExperimentUtils.getAnalysisModuleOfClassForHost(getTrace(), hostId, LttngKernelAnalysis.class);
        if (module == null) {
            return null;
        }

        /* Get the CPU the event is running on */
        Integer cpu = null;
        Iterable<TmfCpuAspect> aspects = TmfTraceUtils.getEventAspectsOfClass(event.getTrace(), TmfCpuAspect.class);
        for (TmfCpuAspect aspect : aspects) {
            if (!aspect.resolve(event).equals(TmfCpuAspect.CPU_UNAVAILABLE)) {
                cpu = aspect.resolve(event);
                break;
            }
        }
        if (cpu == null) {
            /* We couldn't find any CPU information, ignore this event */
            return null;
        }

        Integer currentTid = LttngKernelThreadInformationProvider.getThreadOnCpu(module, cpu, ts);
        if (currentTid == null) {
            return null;
        }
        return new HostThread(hostId, currentTid);
    }

}

Back to the top