Loading...
  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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
 * Copyright (c) 1998-2014 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

#define IOKIT_ENABLE_SHARED_PTR

#include <ptrauth.h>
#include <IOKit/IOInterruptEventSource.h>
#include <IOKit/IOKitDebug.h>
#include <IOKit/IOLib.h>
#include <IOKit/IOService.h>
#include <IOKit/IOInterrupts.h>
#include <IOKit/IOTimeStamp.h>
#include <IOKit/IOWorkLoop.h>
#include <IOKit/IOInterruptAccountingPrivate.h>
#include <libkern/Block_private.h>

#if IOKITSTATS

#define IOStatisticsInitializeCounter() \
do { \
	IOStatistics::setCounterType(IOEventSource::reserved->counter, kIOStatisticsInterruptEventSourceCounter); \
} while (0)

#define IOStatisticsCheckForWork() \
do { \
	IOStatistics::countInterruptCheckForWork(IOEventSource::reserved->counter); \
} while (0)

#define IOStatisticsInterrupt() \
do { \
	IOStatistics::countInterrupt(IOEventSource::reserved->counter); \
} while (0)

#else

#define IOStatisticsInitializeCounter()
#define IOStatisticsCheckForWork()
#define IOStatisticsInterrupt()

#endif // IOKITSTATS

#define super IOEventSource

OSDefineMetaClassAndStructors(IOInterruptEventSource, IOEventSource)
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 0);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 1);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 2);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 3);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 4);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 5);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 6);
OSMetaClassDefineReservedUnused(IOInterruptEventSource, 7);

bool
IOInterruptEventSource::init(OSObject *inOwner,
    Action inAction,
    IOService *inProvider,
    int inIntIndex)
{
	bool res = true;

	if (!super::init(inOwner, (IOEventSourceAction) inAction)) {
		return false;
	}

	reserved = IONew(ExpansionData, 1);

	if (!reserved) {
		return false;
	}

	bzero(reserved, sizeof(ExpansionData));

	provider = inProvider;
	producerCount = consumerCount = 0;
	autoDisable = explicitDisable = false;
	intIndex = ~inIntIndex;

	// Assumes inOwner holds a reference(retain) on the provider
	if (inProvider) {
		if (IA_ANY_STATISTICS_ENABLED) {
			/*
			 * We only treat this as an "interrupt" if it has a provider; if it does,
			 * set up the objects necessary to track interrupt statistics.  Interrupt
			 * event sources without providers are most likely being used as simple
			 * event source in order to poke at workloops and kick off work.
			 *
			 * We also avoid try to avoid interrupt accounting overhead if none of
			 * the statistics are enabled.
			 */
			reserved->statistics = IONew(IOInterruptAccountingData, 1);

			if (!reserved->statistics) {
				/*
				 * We rely on the free() routine to clean up after us if init fails
				 * midway.
				 */
				return false;
			}

			bzero(reserved->statistics, sizeof(IOInterruptAccountingData));

			reserved->statistics->owner = this;
		}

		res = (kIOReturnSuccess == registerInterruptHandler(inProvider, inIntIndex));

		if (res) {
			intIndex = inIntIndex;
		}
	}

	IOStatisticsInitializeCounter();

	return res;
}

IOReturn
IOInterruptEventSource::registerInterruptHandler(IOService *inProvider,
    int inIntIndex)
{
	IOReturn ret;
	int intType;
	IOInterruptAction intHandler;

	ret = inProvider->getInterruptType(inIntIndex, &intType);
	if (kIOReturnSuccess != ret) {
		return ret;
	}

	autoDisable = (intType == kIOInterruptTypeLevel);
	if (autoDisable) {
		intHandler = OSMemberFunctionCast(IOInterruptAction,
		    this, &IOInterruptEventSource::disableInterruptOccurred);
	} else {
		intHandler = OSMemberFunctionCast(IOInterruptAction,
		    this, &IOInterruptEventSource::normalInterruptOccurred);
	}

	ret = provider->registerInterrupt(inIntIndex, this, intHandler);

	/*
	 * Add statistics to the provider.  The setWorkLoop convention should ensure
	 * that we always go down the unregister path before we register (outside of
	 * init()), so we don't have to worry that we will invoke addInterruptStatistics
	 * erroneously.
	 */
	if ((ret == kIOReturnSuccess) && (reserved->statistics)) {
		/*
		 * Stash the normal index value, for the sake of debugging.
		 */
		reserved->statistics->interruptIndex = inIntIndex;

		/*
		 * We need to hook the interrupt information up to the provider so that it
		 * can find the statistics for this interrupt when desired.  The provider is
		 * responsible for maintaining the reporter for a particular interrupt, and
		 * needs a handle on the statistics so that it can request that the reporter
		 * be updated as needed.  Errors are considered "soft" for the moment (it
		 * will either panic, or fail in a way such that we can still service the
		 * interrupt).
		 */
		provider->addInterruptStatistics(reserved->statistics, inIntIndex);

		/*
		 * Add the statistics object to the global list of statistics objects; this
		 * is an aid to debugging (we can trivially find statistics for all eligible
		 * interrupts, and dump them; potentially helpful if the system is wedged
		 * due to interrupt activity).
		 */
		interruptAccountingDataAddToList(reserved->statistics);
	}

	return ret;
}

void
IOInterruptEventSource::unregisterInterruptHandler(IOService *inProvider,
    int inIntIndex)
{
	if (reserved->statistics) {
		interruptAccountingDataRemoveFromList(reserved->statistics);
		provider->removeInterruptStatistics(reserved->statistics->interruptIndex);
	}

	provider->unregisterInterrupt(inIntIndex);
}


OSSharedPtr<IOInterruptEventSource>
IOInterruptEventSource::interruptEventSource(OSObject *inOwner,
    Action inAction,
    IOService *inProvider,
    int inIntIndex)
{
	OSSharedPtr<IOInterruptEventSource> me = OSMakeShared<IOInterruptEventSource>();

	if (me && !me->init(inOwner, inAction, inProvider, inIntIndex)) {
		return nullptr;
	}

	return me;
}

OSSharedPtr<IOInterruptEventSource>
IOInterruptEventSource::interruptEventSource(OSObject *inOwner,
    IOService *inProvider,
    int inIntIndex,
    ActionBlock inAction)
{
	OSSharedPtr<IOInterruptEventSource> ies;
	ies = IOInterruptEventSource::interruptEventSource(inOwner, (Action) NULL, inProvider, inIntIndex);
	if (ies) {
		ies->setActionBlock((IOEventSource::ActionBlock) inAction);
	}

	return ies;
}

void
IOInterruptEventSource::free()
{
	if (provider && intIndex >= 0) {
		unregisterInterruptHandler(provider, intIndex);
	}

	if (reserved) {
		if (reserved->statistics) {
			IODelete(reserved->statistics, IOInterruptAccountingData, 1);
		}

		IODelete(reserved, ExpansionData, 1);
	}

	super::free();
}

void
IOInterruptEventSource::enable()
{
	if (provider && intIndex >= 0) {
		provider->enableInterrupt(intIndex);
		explicitDisable = false;
		enabled = true;
	}
}

void
IOInterruptEventSource::disable()
{
	if (provider && intIndex >= 0) {
		provider->disableInterrupt(intIndex);
		explicitDisable = true;
		enabled = false;
	}
}

void
IOInterruptEventSource::setWorkLoop(IOWorkLoop *inWorkLoop)
{
	if (inWorkLoop) {
		super::setWorkLoop(inWorkLoop);
	}

	if (provider) {
		if (!inWorkLoop) {
			if (intIndex >= 0) {
				/*
				 * It isn't necessarily safe to wait until free() to unregister the interrupt;
				 * our provider may disappear.
				 */
				unregisterInterruptHandler(provider, intIndex);
				intIndex = ~intIndex;
			}
		} else if ((intIndex < 0) && (kIOReturnSuccess == registerInterruptHandler(provider, ~intIndex))) {
			intIndex = ~intIndex;
		}
	}

	if (!inWorkLoop) {
		super::setWorkLoop(inWorkLoop);
	}
}

const IOService *
IOInterruptEventSource::getProvider() const
{
	return provider;
}

int
IOInterruptEventSource::getIntIndex() const
{
	return intIndex;
}

bool
IOInterruptEventSource::getAutoDisable() const
{
	return autoDisable;
}

bool
IOInterruptEventSource::checkForWork()
{
	uint64_t startSystemTime = 0;
	uint64_t endSystemTime = 0;
	uint64_t startCPUTime = 0;
	uint64_t endCPUTime = 0;
	unsigned int cacheProdCount = producerCount;
	int numInts = cacheProdCount - consumerCount;
	IOEventSource::Action intAction = action;
	ActionBlock intActionBlock = (ActionBlock) actionBlock;
	void *address;
	bool trace = (gIOKitTrace & kIOTraceIntEventSource) ? true : false;

	if (kActionBlock & flags) {
		address = ptrauth_nop_cast(void *, _Block_get_invoke_fn((struct Block_layout *)intActionBlock));
	} else {
		address = ptrauth_nop_cast(void *, intAction);
	}

	IOStatisticsCheckForWork();

	if (numInts > 0) {
		if (trace) {
			IOTimeStampStartConstant(IODBG_INTES(IOINTES_ACTION),
			    VM_KERNEL_ADDRHIDE(address),
			    VM_KERNEL_ADDRHIDE(owner),
			    VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(workLoop));
		}

		if (reserved->statistics) {
			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelSystemTimeIndex)) {
				startSystemTime = mach_absolute_time();
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCPUTimeIndex)) {
				startCPUTime = thread_get_runtime_self();
			}
		}

		// Call the handler
		if (kActionBlock & flags) {
			(intActionBlock)(this, numInts);
		} else {
			((IOInterruptEventAction)intAction)(owner, this, numInts);
		}

		if (reserved->statistics) {
			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCountIndex)) {
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelCountIndex], 1);
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCPUTimeIndex)) {
				endCPUTime = thread_get_runtime_self();
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelCPUTimeIndex], endCPUTime - startCPUTime);
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelSystemTimeIndex)) {
				endSystemTime = mach_absolute_time();
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelSystemTimeIndex], endSystemTime - startSystemTime);
			}
		}

		if (trace) {
			IOTimeStampEndConstant(IODBG_INTES(IOINTES_ACTION),
			    VM_KERNEL_ADDRHIDE(address),
			    VM_KERNEL_ADDRHIDE(owner),
			    VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(workLoop));
		}

		consumerCount = cacheProdCount;
		if (autoDisable && !explicitDisable) {
			enable();
		}
	} else if (numInts < 0) {
		if (trace) {
			IOTimeStampStartConstant(IODBG_INTES(IOINTES_ACTION),
			    VM_KERNEL_ADDRHIDE(address),
			    VM_KERNEL_ADDRHIDE(owner),
			    VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(workLoop));
		}

		if (reserved->statistics) {
			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelSystemTimeIndex)) {
				startSystemTime = mach_absolute_time();
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCPUTimeIndex)) {
				startCPUTime = thread_get_runtime_self();
			}
		}

		// Call the handler
		if (kActionBlock & flags) {
			(intActionBlock)(this, numInts);
		} else {
			((IOInterruptEventAction)intAction)(owner, this, numInts);
		}

		if (reserved->statistics) {
			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCountIndex)) {
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelCountIndex], 1);
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelCPUTimeIndex)) {
				endCPUTime = thread_get_runtime_self();
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelCPUTimeIndex], endCPUTime - startCPUTime);
			}

			if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingSecondLevelSystemTimeIndex)) {
				endSystemTime = mach_absolute_time();
				IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingSecondLevelSystemTimeIndex], endSystemTime - startSystemTime);
			}
		}

		if (trace) {
			IOTimeStampEndConstant(IODBG_INTES(IOINTES_ACTION),
			    VM_KERNEL_ADDRHIDE(address),
			    VM_KERNEL_ADDRHIDE(owner),
			    VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(workLoop));
		}

		consumerCount = cacheProdCount;
		if (autoDisable && !explicitDisable) {
			enable();
		}
	}

	return false;
}

void
IOInterruptEventSource::normalInterruptOccurred
(void */*refcon*/, IOService */*prov*/, int /*source*/)
{
	bool trace = (gIOKitTrace & kIOTraceIntEventSource) ? true : false;

	IOStatisticsInterrupt();
	producerCount++;

	if (trace) {
		IOTimeStampStartConstant(IODBG_INTES(IOINTES_SEMA), VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(owner));
	}

	if (reserved->statistics) {
		if (reserved->statistics->enablePrimaryTimestamp) {
			reserved->statistics->primaryTimestamp = mach_absolute_time();
		}
		if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingFirstLevelCountIndex)) {
			IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingFirstLevelCountIndex], 1);
		}
	}

	signalWorkAvailable();

	if (trace) {
		IOTimeStampEndConstant(IODBG_INTES(IOINTES_SEMA), VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(owner));
	}
}

void
IOInterruptEventSource::disableInterruptOccurred
(void */*refcon*/, IOService *prov, int source)
{
	bool trace = (gIOKitTrace & kIOTraceIntEventSource) ? true : false;

	prov->disableInterrupt(source); /* disable the interrupt */

	IOStatisticsInterrupt();
	producerCount++;

	if (trace) {
		IOTimeStampStartConstant(IODBG_INTES(IOINTES_SEMA), VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(owner));
	}

	if (reserved->statistics) {
		if (reserved->statistics->enablePrimaryTimestamp) {
			reserved->statistics->primaryTimestamp = mach_absolute_time();
		}
		if (IA_GET_STATISTIC_ENABLED(kInterruptAccountingFirstLevelCountIndex)) {
			IA_ADD_VALUE(&reserved->statistics->interruptStatistics[kInterruptAccountingFirstLevelCountIndex], 1);
		}
	}

	signalWorkAvailable();

	if (trace) {
		IOTimeStampEndConstant(IODBG_INTES(IOINTES_SEMA), VM_KERNEL_ADDRHIDE(this), VM_KERNEL_ADDRHIDE(owner));
	}
}

void
IOInterruptEventSource::interruptOccurred
(void *_refcon, IOService *prov, int source)
{
	if (autoDisable && prov) {
		disableInterruptOccurred(_refcon, prov, source);
	} else {
		normalInterruptOccurred(_refcon, prov, source);
	}
}

IOReturn
IOInterruptEventSource::warmCPU
(uint64_t abstime)
{
	return ml_interrupt_prewarm(abstime);
}

void
IOInterruptEventSource::enablePrimaryInterruptTimestamp(bool enable)
{
	if (reserved->statistics) {
		reserved->statistics->enablePrimaryTimestamp = enable;
	}
}

uint64_t
IOInterruptEventSource::getPrimaryInterruptTimestamp()
{
	if (reserved->statistics && reserved->statistics->enablePrimaryTimestamp) {
		return reserved->statistics->primaryTimestamp;
	}
	return -1ULL;
}