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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since d91488d was 0705fc5, checked in by Jakub Jermar <jakub@…>, 7 years ago

Fix warnings in non-debug build

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