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

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

No need to compute number of used pages again

In as_area_change_flags we can just use used_space.pages which already
contains the number of used pages.

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