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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 5071f8a was 5071f8a, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

Handle correctly THREAD being NULL

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