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
/*
 * Copyright (c) 2009-2016 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@
 */
#include <mach_assert.h>

#include <sys/errno.h>
#include <i386/param.h>
#include <i386/misc_protos.h>
#include <i386/cpu_data.h>
#include <i386/machine_routines.h>
#include <i386/cpuid.h>
#include <i386/vmx.h>
#include <vm/pmap.h>
#include <vm/vm_map.h>
#include <vm/vm_kern.h>
#include <vm/vm_fault.h>

#include <sys/kdebug.h>

static int copyio(int, user_addr_t, char *, vm_size_t, vm_size_t *, int);
static int copyio_phys(addr64_t, addr64_t, vm_size_t, int);

/*
 * Copy sizes bigger than this value will cause a kernel panic.
 *
 * Yes, this is an arbitrary fixed limit, but it's almost certainly
 * a programming error to be copying more than this amount between
 * user and wired kernel memory in a single invocation on this
 * platform.
 */
#define COPYSIZELIMIT_PANIC     (64*MB)

/*
 * The copy engine has the following characteristics
 *   - copyio() handles copies to/from user or kernel space
 *   - copypv() deals with physical or virtual addresses
 *
 * Readers familiar with the 32-bit kernel will expect Joe's thesis at this
 * point describing the full glory of the copy window implementation. In K64,
 * however, there is no need for windowing. Thanks to the vast shared address
 * space, the kernel has direct access to userspace and to physical memory.
 *
 * User virtual addresses are accessible provided the user's cr3 is loaded.
 * Physical addresses are accessible via the direct map and the PHYSMAP_PTOV()
 * translation.
 *
 * Copyin/out variants all boil done to just these 2 routines in locore.s which
 * provide fault-recoverable copying:
 */
extern int _bcopy(const void *, void *, vm_size_t);
extern int _bcopystr(const void *, void *, vm_size_t, vm_size_t *);
extern int _copyin_word(const char *src, uint64_t *dst, vm_size_t len);


/*
 * Types of copies:
 */
#define COPYIN		0	/* from user virtual to kernel virtual */
#define COPYOUT		1	/* from kernel virtual to user virtual */
#define COPYINSTR	2	/* string variant of copyout */
#define COPYINPHYS	3	/* from user virtual to kernel physical */
#define COPYOUTPHYS	4	/* from kernel physical to user virtual */
#define COPYINWORD	5	/* from user virtual to kernel virtual */

#if ENABLE_SMAPLOG
typedef struct {
	uint64_t 	timestamp;
	thread_t	thread;
	uintptr_t	cr4;
	uint8_t		cpuid;
	uint8_t		smap_state;
	uint8_t		copyio_active;
} smaplog_entry_t;

#define SMAPLOG_BUFFER_SIZE (50)
static smaplog_entry_t	smaplog_cbuf[SMAPLOG_BUFFER_SIZE];
static uint32_t		smaplog_head = 0;

static void
smaplog_add_entry(boolean_t enabling)
{
	uint32_t index = 0;
	thread_t thread = current_thread();

	do {
		index = smaplog_head;
	} while (!OSCompareAndSwap(index, (index + 1) % SMAPLOG_BUFFER_SIZE, &smaplog_head));

	assert(index < SMAPLOG_BUFFER_SIZE);
	assert(smaplog_head < SMAPLOG_BUFFER_SIZE);
	assert(thread);

	smaplog_cbuf[index].timestamp = mach_absolute_time();
	smaplog_cbuf[index].thread = thread;
	smaplog_cbuf[index].cpuid = cpu_number();
	smaplog_cbuf[index].cr4 = get_cr4();
	smaplog_cbuf[index].smap_state = enabling;
	smaplog_cbuf[index].copyio_active = (thread->machine.specFlags & CopyIOActive) ? 1 : 0;
}
#endif /* ENABLE_SMAPLOG */

extern boolean_t pmap_smap_enabled;
static inline void user_access_enable(void) {
	if (pmap_smap_enabled) {
		stac();
#if ENABLE_SMAPLOG
		smaplog_add_entry(TRUE);
#endif
	}
}
static inline void user_access_disable(void) {
	if (pmap_smap_enabled) {
		clac();
#if ENABLE_SMAPLOG
		smaplog_add_entry(FALSE);
#endif
	}
}

#if COPYIO_TRACE_ENABLED
#define COPYIO_TRACE(x, a, b, c, d, e) KERNEL_DEBUG_CONSTANT(x, a, b, c, d, e)
#else
#define COPYIO_TRACE(x, a, b, c, d, e) do { } while(0)
#endif

static int
copyio(int copy_type, user_addr_t user_addr, char *kernel_addr,
       vm_size_t nbytes, vm_size_t *lencopied, int use_kernel_map)
{
        thread_t	thread = current_thread();
	pmap_t		pmap;
	vm_size_t	bytes_copied;
	int		error = 0;
	boolean_t	istate = FALSE;
	boolean_t	recursive_CopyIOActive;
#if	COPYIO_TRACE_ENABLED
	int		debug_type = 0xeff70010;
	debug_type += (copy_type << 2);
#endif
	boolean_t nopagezero = thread->map->pmap->pagezero_accessible;

	assert(nbytes < COPYSIZELIMIT_PANIC);

	COPYIO_TRACE(debug_type | DBG_FUNC_START,
	    user_addr, kernel_addr, nbytes, use_kernel_map, 0);

	if (__improbable(nbytes == 0))
		goto out;

        pmap = thread->map->pmap;

	if (__improbable((copy_type != COPYINPHYS) && (copy_type != COPYOUTPHYS) && ((vm_offset_t)kernel_addr < VM_MIN_KERNEL_AND_KEXT_ADDRESS))) {
		panic("Invalid copy parameter, copy type: %d, kernel address: %p", copy_type, kernel_addr);
	}

	/* Sanity and security check for addresses to/from a user */

	if (__improbable(((pmap != kernel_pmap) && (use_kernel_map == 0)) &&
		((nbytes && (user_addr+nbytes <= user_addr)) || ((user_addr + nbytes) > vm_map_max(thread->map))))) {
		error = EFAULT;
		goto out;
	}

	/*
	 * If the no_shared_cr3 boot-arg is set (true), the kernel runs on 
	 * its own pmap and cr3 rather than the user's -- so that wild accesses
	 * from kernel or kexts can be trapped. So, during copyin and copyout,
	 * we need to switch back to the user's map/cr3. The thread is flagged
	 * "CopyIOActive" at this time so that if the thread is pre-empted,
	 * we will later restore the correct cr3.
	 */
	recursive_CopyIOActive = thread->machine.specFlags & CopyIOActive;

	boolean_t pdswitch = no_shared_cr3 || nopagezero;

	if (__improbable(pdswitch)) {
		istate = ml_set_interrupts_enabled(FALSE);
		if (nopagezero && pmap_pcid_ncpus) {
			pmap_pcid_activate(pmap, cpu_number(), TRUE, TRUE);
		} else if (get_cr3_base() != pmap->pm_cr3) {
			set_cr3_raw(pmap->pm_cr3);
		}
		thread->machine.specFlags |= CopyIOActive;
	} else {
		thread->machine.specFlags |= CopyIOActive;
	}

	user_access_enable();

#if DEVELOPMENT || DEBUG	
	/*
	 * Ensure that we're running on the target thread's cr3.
	 */
	if ((pmap != kernel_pmap) && !use_kernel_map &&
	    (get_cr3_base() != pmap->pm_cr3)) {
		panic("copyio(%d,%p,%p,%ld,%p,%d) cr3 is %p expects %p",
			copy_type, (void *)user_addr, kernel_addr, nbytes, lencopied, use_kernel_map,
			(void *) get_cr3_raw(), (void *) pmap->pm_cr3);
	}
#endif

	if (__improbable(pdswitch)) {
		(void) ml_set_interrupts_enabled(istate);
	}

	COPYIO_TRACE(0xeff70044 | DBG_FUNC_NONE, user_addr,
		     kernel_addr, nbytes, 0, 0);

        switch (copy_type) {

	case COPYIN:
	        error = _bcopy((const void *) user_addr,
				kernel_addr,
				nbytes);
		break;
			
	case COPYOUT:
	        error = _bcopy(kernel_addr,
				(void *) user_addr,
				nbytes);
		break;

	case COPYINPHYS:
	        error = _bcopy((const void *) user_addr,
				PHYSMAP_PTOV(kernel_addr),
				nbytes);
		break;

	case COPYOUTPHYS:
	        error = _bcopy((const void *) PHYSMAP_PTOV(kernel_addr),
				(void *) user_addr,
				nbytes);
		break;

	case COPYINWORD:
		error = _copyin_word((const void *) user_addr,
				(void *) kernel_addr,
				nbytes);
		break;

	case COPYINSTR:
	        error = _bcopystr((const void *) user_addr,
				kernel_addr,
				(int) nbytes,
				&bytes_copied);

		/*
		 * lencopied should be updated on success
		 * or ENAMETOOLONG...  but not EFAULT
		 */
		if (error != EFAULT)
		        *lencopied = bytes_copied;

		if (error) {
#if KDEBUG
		        nbytes = *lencopied;
#endif
		        break;
		}
		if (*(kernel_addr + bytes_copied - 1) == 0) {
		        /*
			 * we found a NULL terminator... we're done
			 */
#if KDEBUG
		        nbytes = *lencopied;
#endif
			break;
		} else {
		        /*
			 * no more room in the buffer and we haven't
			 * yet come across a NULL terminator
			 */
#if KDEBUG
		        nbytes = *lencopied;
#endif
		        error = ENAMETOOLONG;
			break;
		}
	}

	user_access_disable();

	if (__improbable(pdswitch)) {
		istate = ml_set_interrupts_enabled(FALSE);
		if  (!recursive_CopyIOActive && (get_cr3_raw() != kernel_pmap->pm_cr3)) {
			if (nopagezero && pmap_pcid_ncpus) {
				pmap_pcid_activate(pmap, cpu_number(), TRUE, FALSE);
			} else {
				set_cr3_raw(kernel_pmap->pm_cr3);
			}
		}

		if (!recursive_CopyIOActive) {
			thread->machine.specFlags &= ~CopyIOActive;
		}
		(void) ml_set_interrupts_enabled(istate);
	} else if (!recursive_CopyIOActive) {
		thread->machine.specFlags &= ~CopyIOActive;
	}

out:
	COPYIO_TRACE(debug_type | DBG_FUNC_END, user_addr, kernel_addr, nbytes, error, 0);

	return (error);
}


static int
copyio_phys(addr64_t source, addr64_t sink, vm_size_t csize, int which)
{
        char	    *paddr;
	user_addr_t vaddr;
	int         ctype;

	if (which & cppvPsnk) {
		paddr  = (char *)sink;
	        vaddr  = (user_addr_t)source;
		ctype  = COPYINPHYS;
	} else {
	        paddr  = (char *)source;
		vaddr  = (user_addr_t)sink;
		ctype  = COPYOUTPHYS;
	}
	return copyio(ctype, vaddr, paddr, csize, NULL, which & cppvKmap);
}

int
copyinmsg(const user_addr_t user_addr, char *kernel_addr, mach_msg_size_t nbytes)
{
    return copyio(COPYIN, user_addr, kernel_addr, nbytes, NULL, 0);
}    

int
copyin(const user_addr_t user_addr, char *kernel_addr, vm_size_t nbytes)
{
    return copyio(COPYIN, user_addr, kernel_addr, nbytes, NULL, 0);
}

/*
 * copyin_word
 * Read an aligned value from userspace as a single memory transaction.
 * This function supports userspace synchronization features
 */
int
copyin_word(const user_addr_t user_addr, uint64_t *kernel_addr, vm_size_t nbytes)
{
	/* Verify sizes */
	if ((nbytes != 4) && (nbytes != 8))
		return EINVAL;

	/* Test alignment */
	if (user_addr & (nbytes - 1))
		return EINVAL;
	return copyio(COPYINWORD, user_addr, (char *)(uintptr_t)kernel_addr, nbytes, NULL, 0);
}

int
copyinstr(const user_addr_t user_addr,  char *kernel_addr, vm_size_t nbytes, vm_size_t *lencopied)
{
    *lencopied = 0;

    return copyio(COPYINSTR, user_addr, kernel_addr, nbytes, lencopied, 0);
}

int
copyoutmsg(const char *kernel_addr, user_addr_t user_addr, mach_msg_size_t nbytes)
{
    return copyio(COPYOUT, user_addr, (char *)(uintptr_t)kernel_addr, nbytes, NULL, 0);
}

int
copyout(const void *kernel_addr, user_addr_t user_addr, vm_size_t nbytes)
{
    return copyio(COPYOUT, user_addr, (char *)(uintptr_t)kernel_addr, nbytes, NULL, 0);
}


kern_return_t
copypv(addr64_t src64, addr64_t snk64, unsigned int size, int which)
{
	unsigned int lop, csize;
	int bothphys = 0;
	
	KERNEL_DEBUG(0xeff7004c | DBG_FUNC_START, (unsigned)src64,
		     (unsigned)snk64, size, which, 0);

	if ((which & (cppvPsrc | cppvPsnk)) == 0 )				/* Make sure that only one is virtual */
		panic("copypv: no more than 1 parameter may be virtual\n");	/* Not allowed */

	if ((which & (cppvPsrc | cppvPsnk)) == (cppvPsrc | cppvPsnk))
	        bothphys = 1;							/* both are physical */

	while (size) {
	  
	        if (bothphys) {
		        lop = (unsigned int)(PAGE_SIZE - (snk64 & (PAGE_SIZE - 1)));		/* Assume sink smallest */

			if (lop > (unsigned int)(PAGE_SIZE - (src64 & (PAGE_SIZE - 1))))
			        lop = (unsigned int)(PAGE_SIZE - (src64 & (PAGE_SIZE - 1)));	/* No, source is smaller */
		} else {
		        /*
			 * only need to compute the resid for the physical page
			 * address... we don't care about where we start/finish in
			 * the virtual since we just call the normal copyin/copyout
			 */
		        if (which & cppvPsrc)
			        lop = (unsigned int)(PAGE_SIZE - (src64 & (PAGE_SIZE - 1)));
			else
			        lop = (unsigned int)(PAGE_SIZE - (snk64 & (PAGE_SIZE - 1)));
		}
		csize = size;						/* Assume we can copy it all */
		if (lop < size)
		        csize = lop;					/* Nope, we can't do it all */
#if 0		
		/*
		 * flush_dcache64 is currently a nop on the i386... 
		 * it's used when copying to non-system memory such
		 * as video capture cards... on PPC there was a need
		 * to flush due to how we mapped this memory... not
		 * sure if it's needed on i386.
		 */
		if (which & cppvFsrc)
		        flush_dcache64(src64, csize, 1);		/* If requested, flush source before move */
		if (which & cppvFsnk)
		        flush_dcache64(snk64, csize, 1);		/* If requested, flush sink before move */
#endif
		if (bothphys)
		        bcopy_phys(src64, snk64, csize);		/* Do a physical copy, virtually */
		else {
		        if (copyio_phys(src64, snk64, csize, which))
			        return (KERN_FAILURE);
		}
#if 0
		if (which & cppvFsrc)
		        flush_dcache64(src64, csize, 1);	/* If requested, flush source after move */
		if (which & cppvFsnk)
		        flush_dcache64(snk64, csize, 1);	/* If requested, flush sink after move */
#endif
		size   -= csize;					/* Calculate what is left */
		snk64 += csize;					/* Bump sink to next physical address */
		src64 += csize;					/* Bump source to next physical address */
	}
	KERNEL_DEBUG(0xeff7004c | DBG_FUNC_END, (unsigned)src64,
		     (unsigned)snk64, size, which, 0);

	return KERN_SUCCESS;
}