source: mainline/kernel/generic/src/mm/as.c@ 2fc3b2d

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 2fc3b2d was 2fc3b2d, checked in by jxsvoboda <5887334+jxsvoboda@…>, 7 years ago

Replace B+tree with ordered dict. for used space

Replace the use of B+tree with ordered dictionary for used space,
adding a little bit more abstraction around used space tracking.
This allows performing TLB shootdown while shrinking an area
in a single sequence. A generic used_space_remove() is no longer
needed.

  • Property mode set to 100644
File size: 54.3 KB
Line 
1/*
2 * Copyright (c) 2010 Jakub Jermar
3 * Copyright (c) 2018 Jiri Svoboda
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup kernel_generic_mm
31 * @{
32 */
33
34/**
35 * @file
36 * @brief Address space related functions.
37 *
38 * This file contains address space manipulation functions.
39 * Roughly speaking, this is a higher-level client of
40 * Virtual Address Translation (VAT) subsystem.
41 *
42 * Functionality provided by this file allows one to
43 * create address spaces and create, resize and share
44 * address space areas.
45 *
46 * @see page.c
47 *
48 */
49
50#include <mm/as.h>
51#include <arch/mm/as.h>
52#include <mm/page.h>
53#include <mm/frame.h>
54#include <mm/slab.h>
55#include <mm/tlb.h>
56#include <arch/mm/page.h>
57#include <genarch/mm/page_pt.h>
58#include <genarch/mm/page_ht.h>
59#include <mm/asid.h>
60#include <arch/mm/asid.h>
61#include <preemption.h>
62#include <synch/spinlock.h>
63#include <synch/mutex.h>
64#include <adt/list.h>
65#include <proc/task.h>
66#include <proc/thread.h>
67#include <arch/asm.h>
68#include <panic.h>
69#include <assert.h>
70#include <stdio.h>
71#include <mem.h>
72#include <macros.h>
73#include <bitops.h>
74#include <arch.h>
75#include <errno.h>
76#include <config.h>
77#include <align.h>
78#include <typedefs.h>
79#include <syscall/copy.h>
80#include <arch/interrupt.h>
81#include <interrupt.h>
82#include <stdlib.h>
83
84/**
85 * Each architecture decides what functions will be used to carry out
86 * address space operations such as creating or locking page tables.
87 */
88as_operations_t *as_operations = NULL;
89
90/** Cache for as_t objects */
91static slab_cache_t *as_cache;
92
93/** Cache for as_page_mapping_t objects */
94static slab_cache_t *as_page_mapping_cache;
95
96/** Cache for used_space_ival_t objects */
97static slab_cache_t *used_space_ival_cache;
98
99/** ASID subsystem lock.
100 *
101 * This lock protects:
102 * - inactive_as_with_asid_list
103 * - as->asid for each as of the as_t type
104 * - asids_allocated counter
105 *
106 */
107SPINLOCK_INITIALIZE(asidlock);
108
109/**
110 * Inactive address spaces (on all processors)
111 * that have valid ASID.
112 */
113LIST_INITIALIZE(inactive_as_with_asid_list);
114
115/** Kernel address space. */
116as_t *AS_KERNEL = NULL;
117
118static void *as_areas_getkey(odlink_t *);
119static int as_areas_cmp(void *, void *);
120
121static void used_space_initialize(used_space_t *);
122static void used_space_finalize(used_space_t *);
123static void *used_space_getkey(odlink_t *);
124static int used_space_cmp(void *, void *);
125static used_space_ival_t *used_space_last(used_space_t *);
126static void used_space_remove_ival(used_space_ival_t *);
127static void used_space_shorten_ival(used_space_ival_t *, size_t);
128
129NO_TRACE static errno_t as_constructor(void *obj, unsigned int flags)
130{
131 as_t *as = (as_t *) obj;
132
133 link_initialize(&as->inactive_as_with_asid_link);
134 mutex_initialize(&as->lock, MUTEX_PASSIVE);
135
136 return as_constructor_arch(as, flags);
137}
138
139NO_TRACE static size_t as_destructor(void *obj)
140{
141 return as_destructor_arch((as_t *) obj);
142}
143
144/** Initialize address space subsystem. */
145void as_init(void)
146{
147 as_arch_init();
148
149 as_cache = slab_cache_create("as_t", sizeof(as_t), 0,
150 as_constructor, as_destructor, SLAB_CACHE_MAGDEFERRED);
151
152 as_page_mapping_cache = slab_cache_create("as_page_mapping_t",
153 sizeof(as_page_mapping_t), 0, NULL, NULL, SLAB_CACHE_MAGDEFERRED);
154
155 used_space_ival_cache = slab_cache_create("used_space_ival_t",
156 sizeof(used_space_ival_t), 0, NULL, NULL, SLAB_CACHE_MAGDEFERRED);
157
158 AS_KERNEL = as_create(FLAG_AS_KERNEL);
159 if (!AS_KERNEL)
160 panic("Cannot create kernel address space.");
161}
162
163/** Create address space.
164 *
165 * @param flags Flags that influence the way in wich the address
166 * space is created.
167 *
168 */
169as_t *as_create(unsigned int flags)
170{
171 as_t *as = (as_t *) slab_alloc(as_cache, FRAME_ATOMIC);
172 if (!as)
173 return NULL;
174
175 (void) as_create_arch(as, 0);
176
177 odict_initialize(&as->as_areas, as_areas_getkey, as_areas_cmp);
178
179 if (flags & FLAG_AS_KERNEL)
180 as->asid = ASID_KERNEL;
181 else
182 as->asid = ASID_INVALID;
183
184 refcount_init(&as->refcount);
185 as->cpu_refcount = 0;
186
187#ifdef AS_PAGE_TABLE
188 as->genarch.page_table = page_table_create(flags);
189#else
190 page_table_create(flags);
191#endif
192
193 return as;
194}
195
196/** Destroy adress space.
197 *
198 * When there are no tasks referencing this address space (i.e. its refcount is
199 * zero), the address space can be destroyed.
200 *
201 * We know that we don't hold any spinlock.
202 *
203 * @param as Address space to be destroyed.
204 *
205 */
206static void as_destroy(as_t *as)
207{
208 DEADLOCK_PROBE_INIT(p_asidlock);
209
210 assert(as != AS);
211 assert(refcount_unique(&as->refcount));
212
213 /*
214 * Since there is no reference to this address space, it is safe not to
215 * lock its mutex.
216 */
217
218 /*
219 * We need to avoid deadlock between TLB shootdown and asidlock.
220 * We therefore try to take asid conditionally and if we don't succeed,
221 * we enable interrupts and try again. This is done while preemption is
222 * disabled to prevent nested context switches. We also depend on the
223 * fact that so far no spinlocks are held.
224 */
225 preemption_disable();
226 ipl_t ipl = interrupts_read();
227
228retry:
229 interrupts_disable();
230 if (!spinlock_trylock(&asidlock)) {
231 interrupts_enable();
232 DEADLOCK_PROBE(p_asidlock, DEADLOCK_THRESHOLD);
233 goto retry;
234 }
235
236 /* Interrupts disabled, enable preemption */
237 preemption_enable();
238
239 if ((as->asid != ASID_INVALID) && (as != AS_KERNEL)) {
240 if (as->cpu_refcount == 0)
241 list_remove(&as->inactive_as_with_asid_link);
242
243 asid_put(as->asid);
244 }
245
246 spinlock_unlock(&asidlock);
247 interrupts_restore(ipl);
248
249 /*
250 * Destroy address space areas of the address space.
251 * Need to start from the beginning each time since we are destroying
252 * the areas.
253 */
254 as_area_t *area = as_area_first(as);
255 while (area != NULL) {
256 /*
257 * XXX We already have as_area_t, but as_area_destroy will
258 * have to search for it. This could be made faster.
259 */
260 as_area_destroy(as, area->base);
261 area = as_area_first(as);
262 }
263
264 odict_finalize(&as->as_areas);
265
266#ifdef AS_PAGE_TABLE
267 page_table_destroy(as->genarch.page_table);
268#else
269 page_table_destroy(NULL);
270#endif
271
272 slab_free(as_cache, as);
273}
274
275/** Hold a reference to an address space.
276 *
277 * Holding a reference to an address space prevents destruction
278 * of that address space.
279 *
280 * @param as Address space to be held.
281 *
282 */
283NO_TRACE void as_hold(as_t *as)
284{
285 refcount_up(&as->refcount);
286}
287
288/** Release a reference to an address space.
289 *
290 * The last one to release a reference to an address space
291 * destroys the address space.
292 *
293 * @param as Address space to be released.
294 *
295 */
296NO_TRACE void as_release(as_t *as)
297{
298 if (refcount_down(&as->refcount))
299 as_destroy(as);
300}
301
302/** Return first address space area.
303 *
304 * @param as Address space
305 * @return First area in @a as (i.e. area with the lowest base address)
306 * or @c NULL if there is none
307 */
308as_area_t *as_area_first(as_t *as)
309{
310 odlink_t *odlink = odict_first(&as->as_areas);
311 if (odlink == NULL)
312 return NULL;
313
314 return odict_get_instance(odlink, as_area_t, las_areas);
315}
316
317/** Return next address space area.
318 *
319 * @param cur Current area
320 * @return Next area in the same address space or @c NULL if @a cur is the
321 * last area.
322 */
323as_area_t *as_area_next(as_area_t *cur)
324{
325 odlink_t *odlink = odict_next(&cur->las_areas, &cur->as->as_areas);
326 if (odlink == NULL)
327 return NULL;
328
329 return odict_get_instance(odlink, as_area_t, las_areas);
330}
331
332/** Determine if area with specified parameters would conflict with
333 * a specific existing address space area.
334 *
335 * @param addr Starting virtual address of the area being tested.
336 * @param count Number of pages in the area being tested.
337 * @param guarded True if the area being tested is protected by guard pages.
338 * @param area Area against which we are testing.
339 *
340 * @return True if the two areas conflict, false otherwise.
341 */
342NO_TRACE static bool area_is_conflicting(uintptr_t addr,
343 size_t count, bool guarded, as_area_t *area)
344{
345 assert((addr % PAGE_SIZE) == 0);
346
347 size_t gsize = P2SZ(count);
348 size_t agsize = P2SZ(area->pages);
349
350 /*
351 * A guarded area has one guard page before, one page after.
352 * What we do here is: if either area is guarded, we add
353 * PAGE_SIZE to the size of both areas. That guarantees
354 * they will be spaced at least one page apart.
355 */
356 if (guarded || (area->flags & AS_AREA_GUARD) != 0) {
357 /* Add guard page size unless area is at the end of VA domain */
358 if (!overflows(addr, P2SZ(count)))
359 gsize += PAGE_SIZE;
360
361 /* Add guard page size unless area is at the end of VA domain */
362 if (!overflows(area->base, P2SZ(area->pages)))
363 agsize += PAGE_SIZE;
364 }
365
366 return overlaps(addr, gsize, area->base, agsize);
367
368}
369
370/** Check area conflicts with other areas.
371 *
372 * @param as Address space.
373 * @param addr Starting virtual address of the area being tested.
374 * @param count Number of pages in the area being tested.
375 * @param guarded True if the area being tested is protected by guard pages.
376 * @param avoid Do not touch this area. I.e. this area is not considered
377 * as presenting a conflict.
378 *
379 * @return True if there is no conflict, false otherwise.
380 *
381 */
382NO_TRACE static bool check_area_conflicts(as_t *as, uintptr_t addr,
383 size_t count, bool guarded, as_area_t *avoid)
384{
385 assert((addr % PAGE_SIZE) == 0);
386 assert(mutex_locked(&as->lock));
387
388 /*
389 * If the addition of the supposed area address and size overflows,
390 * report conflict.
391 */
392 if (overflows_into_positive(addr, P2SZ(count)))
393 return false;
394
395 /*
396 * We don't want any area to have conflicts with NULL page.
397 */
398 if (overlaps(addr, P2SZ(count), (uintptr_t) NULL, PAGE_SIZE))
399 return false;
400
401 /*
402 * To determine if we overlap with another area, we just need
403 * to look at overlap with the last area with base address <=
404 * to ours and on the first area with base address > than ours.
405 *
406 * First find last area with <= base address.
407 */
408 odlink_t *odlink = odict_find_leq(&as->as_areas, &addr, NULL);
409 if (odlink != NULL) {
410 as_area_t *area = odict_get_instance(odlink, as_area_t,
411 las_areas);
412
413 if (area != avoid) {
414 mutex_lock(&area->lock);
415 if (area_is_conflicting(addr, count, guarded, area)) {
416 mutex_unlock(&area->lock);
417 return false;
418 }
419
420 mutex_unlock(&area->lock);
421 }
422
423 /* Next area */
424 odlink = odict_next(odlink, &as->as_areas);
425 }
426
427 /*
428 * Next area, if any, is the first with base > than our base address.
429 * If there was no area with <= base, we need to look at the first area.
430 */
431 if (odlink == NULL)
432 odlink = odict_first(&as->as_areas);
433
434 if (odlink != NULL) {
435 as_area_t *area = odict_get_instance(odlink, as_area_t,
436 las_areas);
437
438 if (area != avoid) {
439 mutex_lock(&area->lock);
440 if (area_is_conflicting(addr, count, guarded, area)) {
441 mutex_unlock(&area->lock);
442 return false;
443 }
444
445 mutex_unlock(&area->lock);
446 }
447 }
448
449 /*
450 * So far, the area does not conflict with other areas.
451 * Check if it is contained in the user address space.
452 */
453 if (!KERNEL_ADDRESS_SPACE_SHADOWED) {
454 return iswithin(USER_ADDRESS_SPACE_START,
455 (USER_ADDRESS_SPACE_END - USER_ADDRESS_SPACE_START) + 1,
456 addr, P2SZ(count));
457 }
458
459 return true;
460}
461
462/** Return pointer to unmapped address space area
463 *
464 * The address space must be already locked when calling
465 * this function.
466 *
467 * @param as Address space.
468 * @param bound Lowest address bound.
469 * @param size Requested size of the allocation.
470 * @param guarded True if the allocation must be protected by guard pages.
471 *
472 * @return Address of the beginning of unmapped address space area.
473 * @return -1 if no suitable address space area was found.
474 *
475 */
476NO_TRACE static uintptr_t as_get_unmapped_area(as_t *as, uintptr_t bound,
477 size_t size, bool guarded)
478{
479 assert(mutex_locked(&as->lock));
480
481 if (size == 0)
482 return (uintptr_t) -1;
483
484 /*
485 * Make sure we allocate from page-aligned
486 * address. Check for possible overflow in
487 * each step.
488 */
489
490 size_t pages = SIZE2FRAMES(size);
491
492 /*
493 * Find the lowest unmapped address aligned on the size
494 * boundary, not smaller than bound and of the required size.
495 */
496
497 /* First check the bound address itself */
498 uintptr_t addr = ALIGN_UP(bound, PAGE_SIZE);
499 if (addr >= bound) {
500 if (guarded) {
501 /*
502 * Leave an unmapped page between the lower
503 * bound and the area's start address.
504 */
505 addr += P2SZ(1);
506 }
507
508 if (check_area_conflicts(as, addr, pages, guarded, NULL))
509 return addr;
510 }
511
512 /* Eventually check the addresses behind each area */
513 as_area_t *area = as_area_first(as);
514 while (area != NULL) {
515 mutex_lock(&area->lock);
516
517 addr = area->base + P2SZ(area->pages);
518
519 if (guarded || area->flags & AS_AREA_GUARD) {
520 /*
521 * We must leave an unmapped page
522 * between the two areas.
523 */
524 addr += P2SZ(1);
525 }
526
527 bool avail =
528 ((addr >= bound) && (addr >= area->base) &&
529 (check_area_conflicts(as, addr, pages, guarded, area)));
530
531 mutex_unlock(&area->lock);
532
533 if (avail)
534 return addr;
535
536 area = as_area_next(area);
537 }
538
539 /* No suitable address space area found */
540 return (uintptr_t) -1;
541}
542
543/** Get key function for pagemap ordered dictionary.
544 *
545 * The key is the virtual address of the page (as_page_mapping_t.vaddr)
546 *
547 * @param odlink Link to as_pagemap_t.map ordered dictionary
548 * @return Pointer to virtual address cast as @c void *
549 */
550static void *as_pagemap_getkey(odlink_t *odlink)
551{
552 as_page_mapping_t *mapping;
553
554 mapping = odict_get_instance(odlink, as_page_mapping_t, lpagemap);
555 return (void *) &mapping->vaddr;
556}
557
558/** Comparison function for pagemap ordered dictionary.
559 *
560 * @param a Pointer to virtual address cast as @c void *
561 * @param b Pointer to virtual address cast as @c void *
562 * @return <0, =0, >0 if virtual address a is less than, equal to, or
563 * greater than b, respectively.
564 */
565static int as_pagemap_cmp(void *a, void *b)
566{
567 uintptr_t va = *(uintptr_t *)a;
568 uintptr_t vb = *(uintptr_t *)b;
569
570 if (va < vb)
571 return -1;
572 else if (va == vb)
573 return 0;
574 else
575 return +1;
576}
577
578/** Initialize pagemap.
579 *
580 * @param pagemap Pagemap
581 */
582NO_TRACE void as_pagemap_initialize(as_pagemap_t *pagemap)
583{
584 odict_initialize(&pagemap->map, as_pagemap_getkey, as_pagemap_cmp);
585}
586
587/** Finalize pagemap.
588 *
589 * Destroy any entries in the pagemap.
590 *
591 * @param pagemap Pagemap
592 */
593NO_TRACE void as_pagemap_finalize(as_pagemap_t *pagemap)
594{
595 as_page_mapping_t *mapping = as_pagemap_first(pagemap);
596 while (mapping != NULL) {
597 as_pagemap_remove(mapping);
598 mapping = as_pagemap_first(pagemap);
599 }
600 odict_finalize(&pagemap->map);
601}
602
603/** Get first page mapping.
604 *
605 * @param pagemap Pagemap
606 * @return First mapping or @c NULL if there is none
607 */
608NO_TRACE as_page_mapping_t *as_pagemap_first(as_pagemap_t *pagemap)
609{
610 odlink_t *odlink;
611
612 odlink = odict_first(&pagemap->map);
613 if (odlink == NULL)
614 return NULL;
615
616 return odict_get_instance(odlink, as_page_mapping_t, lpagemap);
617}
618
619/** Get next page mapping.
620 *
621 * @param cur Current mapping
622 * @return Next mapping or @c NULL if @a cur is the last one
623 */
624NO_TRACE as_page_mapping_t *as_pagemap_next(as_page_mapping_t *cur)
625{
626 odlink_t *odlink;
627
628 odlink = odict_next(&cur->lpagemap, &cur->pagemap->map);
629 if (odlink == NULL)
630 return NULL;
631
632 return odict_get_instance(odlink, as_page_mapping_t, lpagemap);
633}
634
635/** Find frame by virtual address.
636 *
637 * @param pagemap Pagemap
638 * @param vaddr Virtual address of page
639 * @param rframe Place to store physical frame address
640 * @return EOK on succcess or ENOENT if no mapping found
641 */
642NO_TRACE errno_t as_pagemap_find(as_pagemap_t *pagemap, uintptr_t vaddr,
643 uintptr_t *rframe)
644{
645 odlink_t *odlink;
646 as_page_mapping_t *mapping;
647
648 odlink = odict_find_eq(&pagemap->map, &vaddr, NULL);
649 if (odlink == NULL)
650 return ENOENT;
651
652 mapping = odict_get_instance(odlink, as_page_mapping_t, lpagemap);
653 *rframe = mapping->frame;
654 return EOK;
655}
656
657/** Insert new page mapping.
658 *
659 * This function can block to allocate kernel memory.
660 *
661 * @param pagemap Pagemap
662 * @param vaddr Virtual page address
663 * @param frame Physical frame address
664 */
665NO_TRACE void as_pagemap_insert(as_pagemap_t *pagemap, uintptr_t vaddr,
666 uintptr_t frame)
667{
668 as_page_mapping_t *mapping;
669
670 mapping = slab_alloc(as_page_mapping_cache, 0);
671 mapping->pagemap = pagemap;
672 odlink_initialize(&mapping->lpagemap);
673 mapping->vaddr = vaddr;
674 mapping->frame = frame;
675 odict_insert(&mapping->lpagemap, &pagemap->map, NULL);
676}
677
678/** Remove page mapping.
679 *
680 * @param mapping Mapping
681 */
682NO_TRACE void as_pagemap_remove(as_page_mapping_t *mapping)
683{
684 odict_remove(&mapping->lpagemap);
685 slab_free(as_page_mapping_cache, mapping);
686}
687
688/** Remove reference to address space area share info.
689 *
690 * If the reference count drops to 0, the sh_info is deallocated.
691 *
692 * @param sh_info Pointer to address space area share info.
693 *
694 */
695NO_TRACE static void sh_info_remove_reference(share_info_t *sh_info)
696{
697 bool dealloc = false;
698
699 mutex_lock(&sh_info->lock);
700 assert(sh_info->refcount);
701
702 if (--sh_info->refcount == 0) {
703 dealloc = true;
704
705 /*
706 * Now walk carefully the pagemap B+tree and free/remove
707 * reference from all frames found there.
708 */
709 as_page_mapping_t *mapping = as_pagemap_first(&sh_info->pagemap);
710 while (mapping != NULL) {
711 frame_free(mapping->frame, 1);
712 mapping = as_pagemap_next(mapping);
713 }
714
715 }
716 mutex_unlock(&sh_info->lock);
717
718 if (dealloc) {
719 if (sh_info->backend && sh_info->backend->destroy_shared_data) {
720 sh_info->backend->destroy_shared_data(
721 sh_info->backend_shared_data);
722 }
723 as_pagemap_finalize(&sh_info->pagemap);
724 free(sh_info);
725 }
726}
727
728/** Create address space area of common attributes.
729 *
730 * The created address space area is added to the target address space.
731 *
732 * @param as Target address space.
733 * @param flags Flags of the area memory.
734 * @param size Size of area.
735 * @param attrs Attributes of the area.
736 * @param backend Address space area backend. NULL if no backend is used.
737 * @param backend_data NULL or a pointer to custom backend data.
738 * @param base Starting virtual address of the area.
739 * If set to AS_AREA_ANY, a suitable mappable area is
740 * found.
741 * @param bound Lowest address bound if base is set to AS_AREA_ANY.
742 * Otherwise ignored.
743 *
744 * @return Address space area on success or NULL on failure.
745 *
746 */
747as_area_t *as_area_create(as_t *as, unsigned int flags, size_t size,
748 unsigned int attrs, mem_backend_t *backend,
749 mem_backend_data_t *backend_data, uintptr_t *base, uintptr_t bound)
750{
751 if ((*base != (uintptr_t) AS_AREA_ANY) && !IS_ALIGNED(*base, PAGE_SIZE))
752 return NULL;
753
754 if (size == 0)
755 return NULL;
756
757 size_t pages = SIZE2FRAMES(size);
758
759 /* Writeable executable areas are not supported. */
760 if ((flags & AS_AREA_EXEC) && (flags & AS_AREA_WRITE))
761 return NULL;
762
763 bool const guarded = flags & AS_AREA_GUARD;
764
765 mutex_lock(&as->lock);
766
767 if (*base == (uintptr_t) AS_AREA_ANY) {
768 *base = as_get_unmapped_area(as, bound, size, guarded);
769 if (*base == (uintptr_t) -1) {
770 mutex_unlock(&as->lock);
771 return NULL;
772 }
773 }
774
775 if (overflows_into_positive(*base, size)) {
776 mutex_unlock(&as->lock);
777 return NULL;
778 }
779
780 if (!check_area_conflicts(as, *base, pages, guarded, NULL)) {
781 mutex_unlock(&as->lock);
782 return NULL;
783 }
784
785 as_area_t *area = (as_area_t *) malloc(sizeof(as_area_t));
786 if (!area) {
787 mutex_unlock(&as->lock);
788 return NULL;
789 }
790
791 mutex_initialize(&area->lock, MUTEX_PASSIVE);
792
793 area->as = as;
794 odlink_initialize(&area->las_areas);
795 area->flags = flags;
796 area->attributes = attrs;
797 area->pages = pages;
798 area->base = *base;
799 area->backend = backend;
800 area->sh_info = NULL;
801
802 if (backend_data)
803 area->backend_data = *backend_data;
804 else
805 memsetb(&area->backend_data, sizeof(area->backend_data), 0);
806
807 share_info_t *si = NULL;
808
809 /*
810 * Create the sharing info structure.
811 * We do this in advance for every new area, even if it is not going
812 * to be shared.
813 */
814 if (!(attrs & AS_AREA_ATTR_PARTIAL)) {
815 si = (share_info_t *) malloc(sizeof(share_info_t));
816 if (!si) {
817 free(area);
818 mutex_unlock(&as->lock);
819 return NULL;
820 }
821 mutex_initialize(&si->lock, MUTEX_PASSIVE);
822 si->refcount = 1;
823 si->shared = false;
824 si->backend_shared_data = NULL;
825 si->backend = backend;
826 as_pagemap_initialize(&si->pagemap);
827
828 area->sh_info = si;
829
830 if (area->backend && area->backend->create_shared_data) {
831 if (!area->backend->create_shared_data(area)) {
832 free(area);
833 mutex_unlock(&as->lock);
834 sh_info_remove_reference(si);
835 return NULL;
836 }
837 }
838 }
839
840 if (area->backend && area->backend->create) {
841 if (!area->backend->create(area)) {
842 free(area);
843 mutex_unlock(&as->lock);
844 if (!(attrs & AS_AREA_ATTR_PARTIAL))
845 sh_info_remove_reference(si);
846 return NULL;
847 }
848 }
849
850 used_space_initialize(&area->used_space);
851 odict_insert(&area->las_areas, &as->as_areas, NULL);
852
853 mutex_unlock(&as->lock);
854
855 return area;
856}
857
858/** Find address space area and lock it.
859 *
860 * @param as Address space.
861 * @param va Virtual address.
862 *
863 * @return Locked address space area containing va on success or
864 * NULL on failure.
865 *
866 */
867NO_TRACE static as_area_t *find_area_and_lock(as_t *as, uintptr_t va)
868{
869 assert(mutex_locked(&as->lock));
870
871 odlink_t *odlink = odict_find_leq(&as->as_areas, &va, NULL);
872 if (odlink == NULL)
873 return NULL;
874
875 as_area_t *area = odict_get_instance(odlink, as_area_t, las_areas);
876 mutex_lock(&area->lock);
877
878 assert(area->base <= va);
879
880 if (va <= area->base + (P2SZ(area->pages) - 1))
881 return area;
882
883 mutex_unlock(&area->lock);
884 return NULL;
885}
886
887/** Find address space area and change it.
888 *
889 * @param as Address space.
890 * @param address Virtual address belonging to the area to be changed.
891 * Must be page-aligned.
892 * @param size New size of the virtual memory block starting at
893 * address.
894 * @param flags Flags influencing the remap operation. Currently unused.
895 *
896 * @return Zero on success or a value from @ref errno.h otherwise.
897 *
898 */
899errno_t as_area_resize(as_t *as, uintptr_t address, size_t size, unsigned int flags)
900{
901 if (!IS_ALIGNED(address, PAGE_SIZE))
902 return EINVAL;
903
904 mutex_lock(&as->lock);
905
906 /*
907 * Locate the area.
908 */
909 as_area_t *area = find_area_and_lock(as, address);
910 if (!area) {
911 mutex_unlock(&as->lock);
912 return ENOENT;
913 }
914
915 if (!area->backend->is_resizable(area)) {
916 /*
917 * The backend does not support resizing for this area.
918 */
919 mutex_unlock(&area->lock);
920 mutex_unlock(&as->lock);
921 return ENOTSUP;
922 }
923
924 mutex_lock(&area->sh_info->lock);
925 if (area->sh_info->shared) {
926 /*
927 * Remapping of shared address space areas
928 * is not supported.
929 */
930 mutex_unlock(&area->sh_info->lock);
931 mutex_unlock(&area->lock);
932 mutex_unlock(&as->lock);
933 return ENOTSUP;
934 }
935 mutex_unlock(&area->sh_info->lock);
936
937 size_t pages = SIZE2FRAMES((address - area->base) + size);
938 if (!pages) {
939 /*
940 * Zero size address space areas are not allowed.
941 */
942 mutex_unlock(&area->lock);
943 mutex_unlock(&as->lock);
944 return EPERM;
945 }
946
947 if (pages < area->pages) {
948 uintptr_t start_free = area->base + P2SZ(pages);
949
950 /*
951 * Shrinking the area.
952 * No need to check for overlaps.
953 */
954
955 page_table_lock(as, false);
956
957 /*
958 * Start TLB shootdown sequence.
959 */
960
961 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES,
962 as->asid, area->base + P2SZ(pages),
963 area->pages - pages);
964
965 /*
966 * Remove frames belonging to used space starting from
967 * the highest addresses downwards until an overlap with
968 * the resized address space area is found.
969 */
970 bool cond = true;
971 while (cond) {
972 used_space_ival_t *ival =
973 used_space_last(&area->used_space);
974 assert(ival != NULL);
975
976 uintptr_t ptr = ival->page;
977 size_t pcount = ival->count;
978 size_t i = 0;
979
980 if (overlaps(ptr, P2SZ(pcount), area->base,
981 P2SZ(pages))) {
982
983 if (ptr + P2SZ(pcount) <= start_free) {
984 /*
985 * The whole interval fits completely
986 * in the resized address space area.
987 */
988 break;
989 }
990
991 /*
992 * Part of the interval corresponding to b and
993 * c overlaps with the resized address space
994 * area.
995 */
996
997 /* We are almost done */
998 cond = false;
999 i = (start_free - ptr) >> PAGE_WIDTH;
1000
1001 /* Shorten the interval to @c i pages */
1002 used_space_shorten_ival(ival, i);
1003 } else {
1004 /*
1005 * The interval of used space can be completely
1006 * removed.
1007 */
1008 used_space_remove_ival(ival);
1009 }
1010
1011 for (; i < pcount; i++) {
1012 pte_t pte;
1013 bool found = page_mapping_find(as,
1014 ptr + P2SZ(i), false, &pte);
1015
1016 (void) found;
1017 assert(found);
1018 assert(PTE_VALID(&pte));
1019 assert(PTE_PRESENT(&pte));
1020
1021 if ((area->backend) &&
1022 (area->backend->frame_free)) {
1023 area->backend->frame_free(area,
1024 ptr + P2SZ(i),
1025 PTE_GET_FRAME(&pte));
1026 }
1027
1028 page_mapping_remove(as, ptr + P2SZ(i));
1029 }
1030
1031 }
1032
1033 /*
1034 * Finish TLB shootdown sequence.
1035 */
1036
1037 tlb_invalidate_pages(as->asid,
1038 area->base + P2SZ(pages),
1039 area->pages - pages);
1040
1041 /*
1042 * Invalidate software translation caches
1043 * (e.g. TSB on sparc64, PHT on ppc32).
1044 */
1045 as_invalidate_translation_cache(as,
1046 area->base + P2SZ(pages),
1047 area->pages - pages);
1048 tlb_shootdown_finalize(ipl);
1049
1050 page_table_unlock(as, false);
1051 } else {
1052 /*
1053 * Growing the area.
1054 */
1055
1056 if (overflows_into_positive(address, P2SZ(pages)))
1057 return EINVAL;
1058
1059 /*
1060 * Check for overlaps with other address space areas.
1061 */
1062 bool const guarded = area->flags & AS_AREA_GUARD;
1063 if (!check_area_conflicts(as, address, pages, guarded, area)) {
1064 mutex_unlock(&area->lock);
1065 mutex_unlock(&as->lock);
1066 return EADDRNOTAVAIL;
1067 }
1068 }
1069
1070 if (area->backend && area->backend->resize) {
1071 if (!area->backend->resize(area, pages)) {
1072 mutex_unlock(&area->lock);
1073 mutex_unlock(&as->lock);
1074 return ENOMEM;
1075 }
1076 }
1077
1078 area->pages = pages;
1079
1080 mutex_unlock(&area->lock);
1081 mutex_unlock(&as->lock);
1082
1083 return 0;
1084}
1085
1086/** Destroy address space area.
1087 *
1088 * @param as Address space.
1089 * @param address Address within the area to be deleted.
1090 *
1091 * @return Zero on success or a value from @ref errno.h on failure.
1092 *
1093 */
1094errno_t as_area_destroy(as_t *as, uintptr_t address)
1095{
1096 mutex_lock(&as->lock);
1097
1098 as_area_t *area = find_area_and_lock(as, address);
1099 if (!area) {
1100 mutex_unlock(&as->lock);
1101 return ENOENT;
1102 }
1103
1104 if (area->backend && area->backend->destroy)
1105 area->backend->destroy(area);
1106
1107 page_table_lock(as, false);
1108 /*
1109 * Start TLB shootdown sequence.
1110 */
1111 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES, as->asid, area->base,
1112 area->pages);
1113
1114 /*
1115 * Visit only the pages mapped by used_space.
1116 */
1117 used_space_ival_t *ival = used_space_first(&area->used_space);
1118 while (ival != NULL) {
1119 uintptr_t ptr = ival->page;
1120
1121 for (size_t size = 0; size < ival->count; size++) {
1122 pte_t pte;
1123 bool found = page_mapping_find(as,
1124 ptr + P2SZ(size), false, &pte);
1125
1126 (void) found;
1127 assert(found);
1128 assert(PTE_VALID(&pte));
1129 assert(PTE_PRESENT(&pte));
1130
1131 if ((area->backend) &&
1132 (area->backend->frame_free)) {
1133 area->backend->frame_free(area,
1134 ptr + P2SZ(size),
1135 PTE_GET_FRAME(&pte));
1136 }
1137
1138 page_mapping_remove(as, ptr + P2SZ(size));
1139 }
1140
1141 used_space_remove_ival(ival);
1142 ival = used_space_first(&area->used_space);
1143 }
1144
1145 /*
1146 * Finish TLB shootdown sequence.
1147 */
1148
1149 tlb_invalidate_pages(as->asid, area->base, area->pages);
1150
1151 /*
1152 * Invalidate potential software translation caches
1153 * (e.g. TSB on sparc64, PHT on ppc32).
1154 */
1155 as_invalidate_translation_cache(as, area->base, area->pages);
1156 tlb_shootdown_finalize(ipl);
1157
1158 page_table_unlock(as, false);
1159
1160 used_space_finalize(&area->used_space);
1161 area->attributes |= AS_AREA_ATTR_PARTIAL;
1162 sh_info_remove_reference(area->sh_info);
1163
1164 mutex_unlock(&area->lock);
1165
1166 /*
1167 * Remove the empty area from address space.
1168 */
1169 odict_remove(&area->las_areas);
1170
1171 free(area);
1172
1173 mutex_unlock(&as->lock);
1174 return 0;
1175}
1176
1177/** Share address space area with another or the same address space.
1178 *
1179 * Address space area mapping is shared with a new address space area.
1180 * If the source address space area has not been shared so far,
1181 * a new sh_info is created. The new address space area simply gets the
1182 * sh_info of the source area. The process of duplicating the
1183 * mapping is done through the backend share function.
1184 *
1185 * @param src_as Pointer to source address space.
1186 * @param src_base Base address of the source address space area.
1187 * @param acc_size Expected size of the source area.
1188 * @param dst_as Pointer to destination address space.
1189 * @param dst_flags_mask Destination address space area flags mask.
1190 * @param dst_base Target base address. If set to -1,
1191 * a suitable mappable area is found.
1192 * @param bound Lowest address bound if dst_base is set to -1.
1193 * Otherwise ignored.
1194 *
1195 * @return Zero on success.
1196 * @return ENOENT if there is no such task or such address space.
1197 * @return EPERM if there was a problem in accepting the area.
1198 * @return ENOMEM if there was a problem in allocating destination
1199 * address space area.
1200 * @return ENOTSUP if the address space area backend does not support
1201 * sharing.
1202 *
1203 */
1204errno_t as_area_share(as_t *src_as, uintptr_t src_base, size_t acc_size,
1205 as_t *dst_as, unsigned int dst_flags_mask, uintptr_t *dst_base,
1206 uintptr_t bound)
1207{
1208 mutex_lock(&src_as->lock);
1209 as_area_t *src_area = find_area_and_lock(src_as, src_base);
1210 if (!src_area) {
1211 /*
1212 * Could not find the source address space area.
1213 */
1214 mutex_unlock(&src_as->lock);
1215 return ENOENT;
1216 }
1217
1218 if (!src_area->backend->is_shareable(src_area)) {
1219 /*
1220 * The backend does not permit sharing of this area.
1221 */
1222 mutex_unlock(&src_area->lock);
1223 mutex_unlock(&src_as->lock);
1224 return ENOTSUP;
1225 }
1226
1227 size_t src_size = P2SZ(src_area->pages);
1228 unsigned int src_flags = src_area->flags;
1229 mem_backend_t *src_backend = src_area->backend;
1230 mem_backend_data_t src_backend_data = src_area->backend_data;
1231
1232 /* Share the cacheable flag from the original mapping */
1233 if (src_flags & AS_AREA_CACHEABLE)
1234 dst_flags_mask |= AS_AREA_CACHEABLE;
1235
1236 if ((src_size != acc_size) ||
1237 ((src_flags & dst_flags_mask) != dst_flags_mask)) {
1238 mutex_unlock(&src_area->lock);
1239 mutex_unlock(&src_as->lock);
1240 return EPERM;
1241 }
1242
1243 /*
1244 * Now we are committed to sharing the area.
1245 * First, prepare the area for sharing.
1246 * Then it will be safe to unlock it.
1247 */
1248 share_info_t *sh_info = src_area->sh_info;
1249
1250 mutex_lock(&sh_info->lock);
1251 sh_info->refcount++;
1252 bool shared = sh_info->shared;
1253 sh_info->shared = true;
1254 mutex_unlock(&sh_info->lock);
1255
1256 if (!shared) {
1257 /*
1258 * Call the backend to setup sharing.
1259 * This only happens once for each sh_info.
1260 */
1261 src_area->backend->share(src_area);
1262 }
1263
1264 mutex_unlock(&src_area->lock);
1265 mutex_unlock(&src_as->lock);
1266
1267 /*
1268 * Create copy of the source address space area.
1269 * The destination area is created with AS_AREA_ATTR_PARTIAL
1270 * attribute set which prevents race condition with
1271 * preliminary as_page_fault() calls.
1272 * The flags of the source area are masked against dst_flags_mask
1273 * to support sharing in less privileged mode.
1274 */
1275 as_area_t *dst_area = as_area_create(dst_as, dst_flags_mask,
1276 src_size, AS_AREA_ATTR_PARTIAL, src_backend,
1277 &src_backend_data, dst_base, bound);
1278 if (!dst_area) {
1279 /*
1280 * Destination address space area could not be created.
1281 */
1282 sh_info_remove_reference(sh_info);
1283
1284 return ENOMEM;
1285 }
1286
1287 /*
1288 * Now the destination address space area has been
1289 * fully initialized. Clear the AS_AREA_ATTR_PARTIAL
1290 * attribute and set the sh_info.
1291 */
1292 mutex_lock(&dst_as->lock);
1293 mutex_lock(&dst_area->lock);
1294 dst_area->attributes &= ~AS_AREA_ATTR_PARTIAL;
1295 dst_area->sh_info = sh_info;
1296 mutex_unlock(&dst_area->lock);
1297 mutex_unlock(&dst_as->lock);
1298
1299 return 0;
1300}
1301
1302/** Check access mode for address space area.
1303 *
1304 * @param area Address space area.
1305 * @param access Access mode.
1306 *
1307 * @return False if access violates area's permissions, true
1308 * otherwise.
1309 *
1310 */
1311NO_TRACE bool as_area_check_access(as_area_t *area, pf_access_t access)
1312{
1313 assert(mutex_locked(&area->lock));
1314
1315 int flagmap[] = {
1316 [PF_ACCESS_READ] = AS_AREA_READ,
1317 [PF_ACCESS_WRITE] = AS_AREA_WRITE,
1318 [PF_ACCESS_EXEC] = AS_AREA_EXEC
1319 };
1320
1321 if (!(area->flags & flagmap[access]))
1322 return false;
1323
1324 return true;
1325}
1326
1327/** Convert address space area flags to page flags.
1328 *
1329 * @param aflags Flags of some address space area.
1330 *
1331 * @return Flags to be passed to page_mapping_insert().
1332 *
1333 */
1334NO_TRACE static unsigned int area_flags_to_page_flags(unsigned int aflags)
1335{
1336 unsigned int flags = PAGE_USER | PAGE_PRESENT;
1337
1338 if (aflags & AS_AREA_READ)
1339 flags |= PAGE_READ;
1340
1341 if (aflags & AS_AREA_WRITE)
1342 flags |= PAGE_WRITE;
1343
1344 if (aflags & AS_AREA_EXEC)
1345 flags |= PAGE_EXEC;
1346
1347 if (aflags & AS_AREA_CACHEABLE)
1348 flags |= PAGE_CACHEABLE;
1349
1350 return flags;
1351}
1352
1353/** Change adress space area flags.
1354 *
1355 * The idea is to have the same data, but with a different access mode.
1356 * This is needed e.g. for writing code into memory and then executing it.
1357 * In order for this to work properly, this may copy the data
1358 * into private anonymous memory (unless it's already there).
1359 *
1360 * @param as Address space.
1361 * @param flags Flags of the area memory.
1362 * @param address Address within the area to be changed.
1363 *
1364 * @return Zero on success or a value from @ref errno.h on failure.
1365 *
1366 */
1367errno_t as_area_change_flags(as_t *as, unsigned int flags, uintptr_t address)
1368{
1369 /* Flags for the new memory mapping */
1370 unsigned int page_flags = area_flags_to_page_flags(flags);
1371
1372 mutex_lock(&as->lock);
1373
1374 as_area_t *area = find_area_and_lock(as, address);
1375 if (!area) {
1376 mutex_unlock(&as->lock);
1377 return ENOENT;
1378 }
1379
1380 if (area->backend != &anon_backend) {
1381 /* Copying non-anonymous memory not supported yet */
1382 mutex_unlock(&area->lock);
1383 mutex_unlock(&as->lock);
1384 return ENOTSUP;
1385 }
1386
1387 mutex_lock(&area->sh_info->lock);
1388 if (area->sh_info->shared) {
1389 /* Copying shared areas not supported yet */
1390 mutex_unlock(&area->sh_info->lock);
1391 mutex_unlock(&area->lock);
1392 mutex_unlock(&as->lock);
1393 return ENOTSUP;
1394 }
1395 mutex_unlock(&area->sh_info->lock);
1396
1397 /*
1398 * Compute total number of used pages
1399 */
1400 size_t used_pages = 0;
1401
1402 used_space_ival_t *ival = used_space_first(&area->used_space);
1403 while (ival != NULL) {
1404 used_pages += ival->count;
1405 ival = used_space_next(ival);
1406 }
1407
1408 /* An array for storing frame numbers */
1409 uintptr_t *old_frame = malloc(used_pages * sizeof(uintptr_t));
1410 if (!old_frame) {
1411 mutex_unlock(&area->lock);
1412 mutex_unlock(&as->lock);
1413 return ENOMEM;
1414 }
1415
1416 page_table_lock(as, false);
1417
1418 /*
1419 * Start TLB shootdown sequence.
1420 */
1421 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES, as->asid, area->base,
1422 area->pages);
1423
1424 /*
1425 * Remove used pages from page tables and remember their frame
1426 * numbers.
1427 */
1428 size_t frame_idx = 0;
1429
1430 ival = used_space_first(&area->used_space);
1431 while (ival != NULL) {
1432 uintptr_t ptr = ival->page;
1433 size_t size;
1434
1435 for (size = 0; size < ival->count; size++) {
1436 pte_t pte;
1437 bool found = page_mapping_find(as, ptr + P2SZ(size),
1438 false, &pte);
1439
1440 (void) found;
1441 assert(found);
1442 assert(PTE_VALID(&pte));
1443 assert(PTE_PRESENT(&pte));
1444
1445 old_frame[frame_idx++] = PTE_GET_FRAME(&pte);
1446
1447 /* Remove old mapping */
1448 page_mapping_remove(as, ptr + P2SZ(size));
1449 }
1450
1451 ival = used_space_next(ival);
1452 }
1453
1454 /*
1455 * Finish TLB shootdown sequence.
1456 */
1457
1458 tlb_invalidate_pages(as->asid, area->base, area->pages);
1459
1460 /*
1461 * Invalidate potential software translation caches
1462 * (e.g. TSB on sparc64, PHT on ppc32).
1463 */
1464 as_invalidate_translation_cache(as, area->base, area->pages);
1465 tlb_shootdown_finalize(ipl);
1466
1467 page_table_unlock(as, false);
1468
1469 /*
1470 * Set the new flags.
1471 */
1472 area->flags = flags;
1473
1474 /*
1475 * Map pages back in with new flags. This step is kept separate
1476 * so that the memory area could not be accesed with both the old and
1477 * the new flags at once.
1478 */
1479 frame_idx = 0;
1480
1481 ival = used_space_first(&area->used_space);
1482 while (ival != NULL) {
1483 uintptr_t ptr = ival->page;
1484 size_t size;
1485
1486 for (size = 0; size < ival->count; size++) {
1487 page_table_lock(as, false);
1488
1489 /* Insert the new mapping */
1490 page_mapping_insert(as, ptr + P2SZ(size),
1491 old_frame[frame_idx++], page_flags);
1492
1493 page_table_unlock(as, false);
1494 }
1495
1496 ival = used_space_next(ival);
1497 }
1498
1499 free(old_frame);
1500
1501 mutex_unlock(&area->lock);
1502 mutex_unlock(&as->lock);
1503
1504 return 0;
1505}
1506
1507/** Handle page fault within the current address space.
1508 *
1509 * This is the high-level page fault handler. It decides whether the page fault
1510 * can be resolved by any backend and if so, it invokes the backend to resolve
1511 * the page fault.
1512 *
1513 * Interrupts are assumed disabled.
1514 *
1515 * @param address Faulting address.
1516 * @param access Access mode that caused the page fault (i.e.
1517 * read/write/exec).
1518 * @param istate Pointer to the interrupted state.
1519 *
1520 * @return AS_PF_FAULT on page fault.
1521 * @return AS_PF_OK on success.
1522 * @return AS_PF_DEFER if the fault was caused by copy_to_uspace()
1523 * or copy_from_uspace().
1524 *
1525 */
1526int as_page_fault(uintptr_t address, pf_access_t access, istate_t *istate)
1527{
1528 uintptr_t page = ALIGN_DOWN(address, PAGE_SIZE);
1529 int rc = AS_PF_FAULT;
1530
1531 if (!THREAD)
1532 goto page_fault;
1533
1534 if (!AS)
1535 goto page_fault;
1536
1537 mutex_lock(&AS->lock);
1538 as_area_t *area = find_area_and_lock(AS, page);
1539 if (!area) {
1540 /*
1541 * No area contained mapping for 'page'.
1542 * Signal page fault to low-level handler.
1543 */
1544 mutex_unlock(&AS->lock);
1545 goto page_fault;
1546 }
1547
1548 if (area->attributes & AS_AREA_ATTR_PARTIAL) {
1549 /*
1550 * The address space area is not fully initialized.
1551 * Avoid possible race by returning error.
1552 */
1553 mutex_unlock(&area->lock);
1554 mutex_unlock(&AS->lock);
1555 goto page_fault;
1556 }
1557
1558 if ((!area->backend) || (!area->backend->page_fault)) {
1559 /*
1560 * The address space area is not backed by any backend
1561 * or the backend cannot handle page faults.
1562 */
1563 mutex_unlock(&area->lock);
1564 mutex_unlock(&AS->lock);
1565 goto page_fault;
1566 }
1567
1568 page_table_lock(AS, false);
1569
1570 /*
1571 * To avoid race condition between two page faults on the same address,
1572 * we need to make sure the mapping has not been already inserted.
1573 */
1574 pte_t pte;
1575 bool found = page_mapping_find(AS, page, false, &pte);
1576 if (found && PTE_PRESENT(&pte)) {
1577 if (((access == PF_ACCESS_READ) && PTE_READABLE(&pte)) ||
1578 (access == PF_ACCESS_WRITE && PTE_WRITABLE(&pte)) ||
1579 (access == PF_ACCESS_EXEC && PTE_EXECUTABLE(&pte))) {
1580 page_table_unlock(AS, false);
1581 mutex_unlock(&area->lock);
1582 mutex_unlock(&AS->lock);
1583 return AS_PF_OK;
1584 }
1585 }
1586
1587 /*
1588 * Resort to the backend page fault handler.
1589 */
1590 rc = area->backend->page_fault(area, page, access);
1591 if (rc != AS_PF_OK) {
1592 page_table_unlock(AS, false);
1593 mutex_unlock(&area->lock);
1594 mutex_unlock(&AS->lock);
1595 goto page_fault;
1596 }
1597
1598 page_table_unlock(AS, false);
1599 mutex_unlock(&area->lock);
1600 mutex_unlock(&AS->lock);
1601 return AS_PF_OK;
1602
1603page_fault:
1604 if (THREAD && THREAD->in_copy_from_uspace) {
1605 THREAD->in_copy_from_uspace = false;
1606 istate_set_retaddr(istate,
1607 (uintptr_t) &memcpy_from_uspace_failover_address);
1608 } else if (THREAD && THREAD->in_copy_to_uspace) {
1609 THREAD->in_copy_to_uspace = false;
1610 istate_set_retaddr(istate,
1611 (uintptr_t) &memcpy_to_uspace_failover_address);
1612 } else if (rc == AS_PF_SILENT) {
1613 printf("Killing task %" PRIu64 " due to a "
1614 "failed late reservation request.\n", TASK->taskid);
1615 task_kill_self(true);
1616 } else {
1617 fault_if_from_uspace(istate, "Page fault: %p.", (void *) address);
1618 panic_memtrap(istate, access, address, NULL);
1619 }
1620
1621 return AS_PF_DEFER;
1622}
1623
1624/** Switch address spaces.
1625 *
1626 * Note that this function cannot sleep as it is essentially a part of
1627 * scheduling. Sleeping here would lead to deadlock on wakeup. Another
1628 * thing which is forbidden in this context is locking the address space.
1629 *
1630 * When this function is entered, no spinlocks may be held.
1631 *
1632 * @param old Old address space or NULL.
1633 * @param new New address space.
1634 *
1635 */
1636void as_switch(as_t *old_as, as_t *new_as)
1637{
1638 DEADLOCK_PROBE_INIT(p_asidlock);
1639 preemption_disable();
1640
1641retry:
1642 (void) interrupts_disable();
1643 if (!spinlock_trylock(&asidlock)) {
1644 /*
1645 * Avoid deadlock with TLB shootdown.
1646 * We can enable interrupts here because
1647 * preemption is disabled. We should not be
1648 * holding any other lock.
1649 */
1650 (void) interrupts_enable();
1651 DEADLOCK_PROBE(p_asidlock, DEADLOCK_THRESHOLD);
1652 goto retry;
1653 }
1654 preemption_enable();
1655
1656 /*
1657 * First, take care of the old address space.
1658 */
1659 if (old_as) {
1660 assert(old_as->cpu_refcount);
1661
1662 if ((--old_as->cpu_refcount == 0) && (old_as != AS_KERNEL)) {
1663 /*
1664 * The old address space is no longer active on
1665 * any processor. It can be appended to the
1666 * list of inactive address spaces with assigned
1667 * ASID.
1668 */
1669 assert(old_as->asid != ASID_INVALID);
1670
1671 list_append(&old_as->inactive_as_with_asid_link,
1672 &inactive_as_with_asid_list);
1673 }
1674
1675 /*
1676 * Perform architecture-specific tasks when the address space
1677 * is being removed from the CPU.
1678 */
1679 as_deinstall_arch(old_as);
1680 }
1681
1682 /*
1683 * Second, prepare the new address space.
1684 */
1685 if ((new_as->cpu_refcount++ == 0) && (new_as != AS_KERNEL)) {
1686 if (new_as->asid != ASID_INVALID)
1687 list_remove(&new_as->inactive_as_with_asid_link);
1688 else
1689 new_as->asid = asid_get();
1690 }
1691
1692#ifdef AS_PAGE_TABLE
1693 SET_PTL0_ADDRESS(new_as->genarch.page_table);
1694#endif
1695
1696 /*
1697 * Perform architecture-specific steps.
1698 * (e.g. write ASID to hardware register etc.)
1699 */
1700 as_install_arch(new_as);
1701
1702 spinlock_unlock(&asidlock);
1703
1704 AS = new_as;
1705}
1706
1707/** Compute flags for virtual address translation subsytem.
1708 *
1709 * @param area Address space area.
1710 *
1711 * @return Flags to be used in page_mapping_insert().
1712 *
1713 */
1714NO_TRACE unsigned int as_area_get_flags(as_area_t *area)
1715{
1716 assert(mutex_locked(&area->lock));
1717
1718 return area_flags_to_page_flags(area->flags);
1719}
1720
1721/** Get key function for the @c as_t.as_areas ordered dictionary.
1722 *
1723 * @param odlink Link
1724 * @return Pointer to task ID cast as 'void *'
1725 */
1726static void *as_areas_getkey(odlink_t *odlink)
1727{
1728 as_area_t *area = odict_get_instance(odlink, as_area_t, las_areas);
1729 return (void *) &area->base;
1730}
1731
1732/** Key comparison function for the @c as_t.as_areas ordered dictionary.
1733 *
1734 * @param a Pointer to area A base
1735 * @param b Pointer to area B base
1736 * @return -1, 0, 1 iff base of A is lower than, equal to, higher than B
1737 */
1738static int as_areas_cmp(void *a, void *b)
1739{
1740 uintptr_t base_a = *(uintptr_t *)a;
1741 uintptr_t base_b = *(uintptr_t *)b;
1742
1743 if (base_a < base_b)
1744 return -1;
1745 else if (base_a == base_b)
1746 return 0;
1747 else
1748 return +1;
1749}
1750
1751/** Create page table.
1752 *
1753 * Depending on architecture, create either address space private or global page
1754 * table.
1755 *
1756 * @param flags Flags saying whether the page table is for the kernel
1757 * address space.
1758 *
1759 * @return First entry of the page table.
1760 *
1761 */
1762NO_TRACE pte_t *page_table_create(unsigned int flags)
1763{
1764 assert(as_operations);
1765 assert(as_operations->page_table_create);
1766
1767 return as_operations->page_table_create(flags);
1768}
1769
1770/** Destroy page table.
1771 *
1772 * Destroy page table in architecture specific way.
1773 *
1774 * @param page_table Physical address of PTL0.
1775 *
1776 */
1777NO_TRACE void page_table_destroy(pte_t *page_table)
1778{
1779 assert(as_operations);
1780 assert(as_operations->page_table_destroy);
1781
1782 as_operations->page_table_destroy(page_table);
1783}
1784
1785/** Lock page table.
1786 *
1787 * This function should be called before any page_mapping_insert(),
1788 * page_mapping_remove() and page_mapping_find().
1789 *
1790 * Locking order is such that address space areas must be locked
1791 * prior to this call. Address space can be locked prior to this
1792 * call in which case the lock argument is false.
1793 *
1794 * @param as Address space.
1795 * @param lock If false, do not attempt to lock as->lock.
1796 *
1797 */
1798NO_TRACE void page_table_lock(as_t *as, bool lock)
1799{
1800 assert(as_operations);
1801 assert(as_operations->page_table_lock);
1802
1803 as_operations->page_table_lock(as, lock);
1804}
1805
1806/** Unlock page table.
1807 *
1808 * @param as Address space.
1809 * @param unlock If false, do not attempt to unlock as->lock.
1810 *
1811 */
1812NO_TRACE void page_table_unlock(as_t *as, bool unlock)
1813{
1814 assert(as_operations);
1815 assert(as_operations->page_table_unlock);
1816
1817 as_operations->page_table_unlock(as, unlock);
1818}
1819
1820/** Test whether page tables are locked.
1821 *
1822 * @param as Address space where the page tables belong.
1823 *
1824 * @return True if the page tables belonging to the address soace
1825 * are locked, otherwise false.
1826 */
1827NO_TRACE bool page_table_locked(as_t *as)
1828{
1829 assert(as_operations);
1830 assert(as_operations->page_table_locked);
1831
1832 return as_operations->page_table_locked(as);
1833}
1834
1835/** Return size of the address space area with given base.
1836 *
1837 * @param base Arbitrary address inside the address space area.
1838 *
1839 * @return Size of the address space area in bytes or zero if it
1840 * does not exist.
1841 *
1842 */
1843size_t as_area_get_size(uintptr_t base)
1844{
1845 size_t size;
1846
1847 page_table_lock(AS, true);
1848 as_area_t *src_area = find_area_and_lock(AS, base);
1849
1850 if (src_area) {
1851 size = P2SZ(src_area->pages);
1852 mutex_unlock(&src_area->lock);
1853 } else
1854 size = 0;
1855
1856 page_table_unlock(AS, true);
1857 return size;
1858}
1859
1860/** Initialize used space map.
1861 *
1862 * @param used_space Used space map
1863 */
1864static void used_space_initialize(used_space_t *used_space)
1865{
1866 odict_initialize(&used_space->ivals, used_space_getkey, used_space_cmp);
1867 used_space->pages = 0;
1868}
1869
1870/** Finalize used space map.
1871 *
1872 * @param used_space Used space map
1873 */
1874static void used_space_finalize(used_space_t *used_space)
1875{
1876 assert(odict_empty(&used_space->ivals));
1877 odict_finalize(&used_space->ivals);
1878}
1879
1880/** Get first interval of used space.
1881 *
1882 * @param used_space Used space map
1883 * @return First interval or @c NULL if there are none
1884 */
1885used_space_ival_t *used_space_first(used_space_t *used_space)
1886{
1887 odlink_t *odlink = odict_first(&used_space->ivals);
1888
1889 if (odlink == NULL)
1890 return NULL;
1891
1892 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1893}
1894
1895/** Get next interval of used space.
1896 *
1897 * @param cur Current interval
1898 * @return Next interval or @c NULL if there are none
1899 */
1900used_space_ival_t *used_space_next(used_space_ival_t *cur)
1901{
1902 odlink_t *odlink = odict_next(&cur->lused_space,
1903 &cur->used_space->ivals);
1904
1905 if (odlink == NULL)
1906 return NULL;
1907
1908 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1909}
1910
1911/** Get last interval of used space.
1912 *
1913 * @param used_space Used space map
1914 * @return First interval or @c NULL if there are none
1915 */
1916static used_space_ival_t *used_space_last(used_space_t *used_space)
1917{
1918 odlink_t *odlink = odict_last(&used_space->ivals);
1919
1920 if (odlink == NULL)
1921 return NULL;
1922
1923 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1924}
1925
1926/** Find the first interval that contains addresses greater than or equal to
1927 * @a ptr.
1928 *
1929 * @param used_space Used space map
1930 * @param ptr Virtual address
1931 *
1932 * @return Used space interval or @c NULL if none matches
1933 */
1934used_space_ival_t *used_space_find_gteq(used_space_t *used_space, uintptr_t ptr)
1935{
1936 odlink_t *odlink;
1937 used_space_ival_t *ival;
1938
1939 /* Find last interval to start at address less than @a ptr */
1940 odlink = odict_find_lt(&used_space->ivals, &ptr, NULL);
1941 if (odlink != NULL) {
1942 ival = odict_get_instance(odlink, used_space_ival_t,
1943 lused_space);
1944
1945 /* If the interval extends above @a ptr, return it */
1946 if (ival->page + P2SZ(ival->count) > ptr)
1947 return ival;
1948
1949 /*
1950 * Otherwise, if a next interval exists, it must match
1951 * the criteria.
1952 */
1953 odlink = odict_next(&ival->lused_space, &used_space->ivals);
1954 } else {
1955 /*
1956 * No interval with lower base address, so if there is any
1957 * interval at all, it must match the criteria
1958 */
1959 odlink = odict_first(&used_space->ivals);
1960 }
1961
1962 if (odlink != NULL) {
1963 ival = odict_get_instance(odlink, used_space_ival_t,
1964 lused_space);
1965 return ival;
1966 }
1967
1968 return NULL;
1969}
1970
1971/** Get key function for used space ordered dictionary.
1972 *
1973 * The key is the virtual address of the first page
1974 *
1975 * @param odlink Ordered dictionary link (used_space_ival_t.lused_space)
1976 * @return Pointer to virtual address of first page cast as @c void *.
1977 */
1978static void *used_space_getkey(odlink_t *odlink)
1979{
1980 used_space_ival_t *ival = odict_get_instance(odlink, used_space_ival_t,
1981 lused_space);
1982 return (void *) &ival->page;
1983}
1984
1985/** Compare function for used space ordered dictionary.
1986 *
1987 * @param a Pointer to virtual address of first page cast as @c void *
1988 * @param b Pointer to virtual address of first page cast as @c void *
1989 * @return Less than zero, zero, greater than zero if virtual address @a a
1990 * is less than, equal to, greater than virtual address b, respectively.
1991 */
1992static int used_space_cmp(void *a, void *b)
1993{
1994 uintptr_t va = *(uintptr_t *) a;
1995 uintptr_t vb = *(uintptr_t *) b;
1996
1997 if (va < vb)
1998 return -1;
1999 else if (va == vb)
2000 return 0;
2001 else
2002 return +1;
2003}
2004
2005/** Remove used space interval.
2006 *
2007 * @param ival Used space interval
2008 */
2009static void used_space_remove_ival(used_space_ival_t *ival)
2010{
2011 ival->used_space->pages -= ival->count;
2012 odict_remove(&ival->lused_space);
2013 slab_free(used_space_ival_cache, ival);
2014}
2015
2016/** Shorten used space interval.
2017 *
2018 * @param ival Used space interval
2019 * @param count New number of pages in the interval
2020 */
2021static void used_space_shorten_ival(used_space_ival_t *ival, size_t count)
2022{
2023 assert(count > 0);
2024 assert(count < ival->count);
2025
2026 ival->used_space->pages -= ival->count - count;
2027 ival->count = count;
2028}
2029
2030/** Mark portion of address space area as used.
2031 *
2032 * The address space area must be already locked.
2033 *
2034 * @param used_space Used space map
2035 * @param page First page to be marked.
2036 * @param count Number of page to be marked.
2037 *
2038 * @return False on failure or true on success.
2039 *
2040 */
2041bool used_space_insert(used_space_t *used_space, uintptr_t page, size_t count)
2042{
2043 used_space_ival_t *a;
2044 used_space_ival_t *b;
2045 bool adj_a;
2046 bool adj_b;
2047 odlink_t *odlink;
2048 used_space_ival_t *ival;
2049
2050 assert(IS_ALIGNED(page, PAGE_SIZE));
2051 assert(count);
2052
2053 /* Interval to the left */
2054 odlink = odict_find_lt(&used_space->ivals, &page, NULL);
2055 a = (odlink != NULL) ?
2056 odict_get_instance(odlink, used_space_ival_t, lused_space) :
2057 NULL;
2058
2059 /* Interval to the right */
2060 b = (a != NULL) ? used_space_next(a) :
2061 used_space_first(used_space);
2062
2063 /* Check for conflict with left interval */
2064 if (a != NULL && overlaps(a->page, P2SZ(a->count), page, P2SZ(count)))
2065 return false;
2066
2067 /* Check for conflict with right interval */
2068 if (b != NULL && overlaps(page, P2SZ(count), b->page, P2SZ(b->count)))
2069 return false;
2070
2071 /* Check if A is adjacent to the new interval */
2072 adj_a = (a != NULL) && (a->page + P2SZ(a->count) == page);
2073 /* Check if the new interval is adjacent to B*/
2074 adj_b = (b != NULL) && page + P2SZ(count) == b->page;
2075
2076 if (adj_a && adj_b) {
2077 /* Fuse into a single interval */
2078 a->count += count + b->count;
2079 used_space_remove_ival(b);
2080 } else if (adj_a) {
2081 /* Append to A */
2082 a->count += count;
2083 } else if (adj_b) {
2084 /* Prepend to B */
2085 b->page = page;
2086 b->count += count;
2087 } else {
2088 /* Create new interval */
2089 ival = slab_alloc(used_space_ival_cache, 0);
2090 ival->used_space = used_space;
2091 odlink_initialize(&ival->lused_space);
2092 ival->page = page;
2093 ival->count = count;
2094
2095 odict_insert(&ival->lused_space, &used_space->ivals,
2096 NULL);
2097 }
2098
2099 used_space->pages += count;
2100 return true;
2101}
2102
2103/*
2104 * Address space related syscalls.
2105 */
2106
2107sysarg_t sys_as_area_create(uintptr_t base, size_t size, unsigned int flags,
2108 uintptr_t bound, as_area_pager_info_t *pager_info)
2109{
2110 uintptr_t virt = base;
2111 mem_backend_t *backend;
2112 mem_backend_data_t backend_data;
2113
2114 if (pager_info == AS_AREA_UNPAGED)
2115 backend = &anon_backend;
2116 else {
2117 backend = &user_backend;
2118 if (copy_from_uspace(&backend_data.pager_info, pager_info,
2119 sizeof(as_area_pager_info_t)) != EOK) {
2120 return (sysarg_t) AS_MAP_FAILED;
2121 }
2122 }
2123 as_area_t *area = as_area_create(AS, flags, size,
2124 AS_AREA_ATTR_NONE, backend, &backend_data, &virt, bound);
2125 if (area == NULL)
2126 return (sysarg_t) AS_MAP_FAILED;
2127
2128 return (sysarg_t) virt;
2129}
2130
2131sys_errno_t sys_as_area_resize(uintptr_t address, size_t size, unsigned int flags)
2132{
2133 return (sys_errno_t) as_area_resize(AS, address, size, 0);
2134}
2135
2136sys_errno_t sys_as_area_change_flags(uintptr_t address, unsigned int flags)
2137{
2138 return (sys_errno_t) as_area_change_flags(AS, flags, address);
2139}
2140
2141sys_errno_t sys_as_area_get_info(uintptr_t address, as_area_info_t *dest)
2142{
2143 as_area_t *area;
2144
2145 mutex_lock(&AS->lock);
2146 area = find_area_and_lock(AS, address);
2147 if (area == NULL) {
2148 mutex_unlock(&AS->lock);
2149 return ENOENT;
2150 }
2151
2152 dest->start_addr = area->base;
2153 dest->size = P2SZ(area->pages);
2154 dest->flags = area->flags;
2155
2156 mutex_unlock(&area->lock);
2157 mutex_unlock(&AS->lock);
2158 return EOK;
2159}
2160
2161sys_errno_t sys_as_area_destroy(uintptr_t address)
2162{
2163 return (sys_errno_t) as_area_destroy(AS, address);
2164}
2165
2166/** Get list of adress space areas.
2167 *
2168 * @param as Address space.
2169 * @param obuf Place to save pointer to returned buffer.
2170 * @param osize Place to save size of returned buffer.
2171 *
2172 */
2173as_area_info_t *as_get_area_info(as_t *as, size_t *osize)
2174{
2175 mutex_lock(&as->lock);
2176
2177 /* Count number of areas. */
2178 size_t area_cnt = odict_count(&as->as_areas);
2179
2180 size_t isize = area_cnt * sizeof(as_area_info_t);
2181 as_area_info_t *info = malloc(isize);
2182 if (!info) {
2183 mutex_unlock(&as->lock);
2184 return NULL;
2185 }
2186
2187 /* Record area data. */
2188
2189 size_t area_idx = 0;
2190
2191 as_area_t *area = as_area_first(as);
2192 while (area != NULL) {
2193 assert(area_idx < area_cnt);
2194 mutex_lock(&area->lock);
2195
2196 info[area_idx].start_addr = area->base;
2197 info[area_idx].size = P2SZ(area->pages);
2198 info[area_idx].flags = area->flags;
2199 ++area_idx;
2200
2201 mutex_unlock(&area->lock);
2202 area = as_area_next(area);
2203 }
2204
2205 mutex_unlock(&as->lock);
2206
2207 *osize = isize;
2208 return info;
2209}
2210
2211/** Print out information about address space.
2212 *
2213 * @param as Address space.
2214 *
2215 */
2216void as_print(as_t *as)
2217{
2218 mutex_lock(&as->lock);
2219
2220 /* Print out info about address space areas */
2221 as_area_t *area = as_area_first(as);
2222 while (area != NULL) {
2223 mutex_lock(&area->lock);
2224 printf("as_area: %p, base=%p, pages=%zu"
2225 " (%p - %p)\n", area, (void *) area->base,
2226 area->pages, (void *) area->base,
2227 (void *) (area->base + P2SZ(area->pages)));
2228 mutex_unlock(&area->lock);
2229
2230 area = as_area_next(area);
2231 }
2232
2233 mutex_unlock(&as->lock);
2234}
2235
2236/** @}
2237 */
Note: See TracBrowser for help on using the repository browser.