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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since ef4218f was b294126, checked in by GitHub <noreply@…>, 7 years ago

Merge pull request #52 from jermar/asrefcnt

Fix as_t reference counting

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