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

Last change on this file since 7be8d4d was 7be8d4d, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Replace B+tree with ordered dict. for used space

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

  • Property mode set to 100644
File size: 54.2 KB
Line 
1/*
2 * Copyright (c) 2010 Jakub Jermar
3 * Copyright (c) 2018 Jiri Svoboda
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup kernel_generic_mm
31 * @{
32 */
33
34/**
35 * @file
36 * @brief Address space related functions.
37 *
38 * This file contains address space manipulation functions.
39 * Roughly speaking, this is a higher-level client of
40 * Virtual Address Translation (VAT) subsystem.
41 *
42 * Functionality provided by this file allows one to
43 * create address spaces and create, resize and share
44 * address space areas.
45 *
46 * @see page.c
47 *
48 */
49
50#include <mm/as.h>
51#include <arch/mm/as.h>
52#include <mm/page.h>
53#include <mm/frame.h>
54#include <mm/slab.h>
55#include <mm/tlb.h>
56#include <arch/mm/page.h>
57#include <genarch/mm/page_pt.h>
58#include <genarch/mm/page_ht.h>
59#include <mm/asid.h>
60#include <arch/mm/asid.h>
61#include <preemption.h>
62#include <synch/spinlock.h>
63#include <synch/mutex.h>
64#include <adt/list.h>
65#include <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 return va - vb;
571}
572
573/** Initialize pagemap.
574 *
575 * @param pagemap Pagemap
576 */
577NO_TRACE void as_pagemap_initialize(as_pagemap_t *pagemap)
578{
579 odict_initialize(&pagemap->map, as_pagemap_getkey, as_pagemap_cmp);
580}
581
582/** Finalize pagemap.
583 *
584 * Destroy any entries in the pagemap.
585 *
586 * @param pagemap Pagemap
587 */
588NO_TRACE void as_pagemap_finalize(as_pagemap_t *pagemap)
589{
590 as_page_mapping_t *mapping = as_pagemap_first(pagemap);
591 while (mapping != NULL) {
592 as_pagemap_remove(mapping);
593 mapping = as_pagemap_first(pagemap);
594 }
595 odict_finalize(&pagemap->map);
596}
597
598/** Get first page mapping.
599 *
600 * @param pagemap Pagemap
601 * @return First mapping or @c NULL if there is none
602 */
603NO_TRACE as_page_mapping_t *as_pagemap_first(as_pagemap_t *pagemap)
604{
605 odlink_t *odlink;
606
607 odlink = odict_first(&pagemap->map);
608 if (odlink == NULL)
609 return NULL;
610
611 return odict_get_instance(odlink, as_page_mapping_t, lpagemap);
612}
613
614/** Get next page mapping.
615 *
616 * @param cur Current mapping
617 * @return Next mapping or @c NULL if @a cur is the last one
618 */
619NO_TRACE as_page_mapping_t *as_pagemap_next(as_page_mapping_t *cur)
620{
621 odlink_t *odlink;
622
623 odlink = odict_next(&cur->lpagemap, &cur->pagemap->map);
624 if (odlink == NULL)
625 return NULL;
626
627 return odict_get_instance(odlink, as_page_mapping_t, lpagemap);
628}
629
630/** Find frame by virtual address.
631 *
632 * @param pagemap Pagemap
633 * @param vaddr Virtual address of page
634 * @param rframe Place to store physical frame address
635 * @return EOK on succcess or ENOENT if no mapping found
636 */
637NO_TRACE errno_t as_pagemap_find(as_pagemap_t *pagemap, uintptr_t vaddr,
638 uintptr_t *rframe)
639{
640 odlink_t *odlink;
641 as_page_mapping_t *mapping;
642
643 odlink = odict_find_eq(&pagemap->map, &vaddr, NULL);
644 if (odlink == NULL)
645 return ENOENT;
646
647 mapping = odict_get_instance(odlink, as_page_mapping_t, lpagemap);
648 *rframe = mapping->frame;
649 return EOK;
650}
651
652/** Insert new page mapping.
653 *
654 * This function can block to allocate kernel memory.
655 *
656 * @param pagemap Pagemap
657 * @param vaddr Virtual page address
658 * @param frame Physical frame address
659 */
660NO_TRACE void as_pagemap_insert(as_pagemap_t *pagemap, uintptr_t vaddr,
661 uintptr_t frame)
662{
663 as_page_mapping_t *mapping;
664
665 mapping = slab_alloc(as_page_mapping_cache, 0);
666 mapping->pagemap = pagemap;
667 odlink_initialize(&mapping->lpagemap);
668 mapping->vaddr = vaddr;
669 mapping->frame = frame;
670 odict_insert(&mapping->lpagemap, &pagemap->map, NULL);
671}
672
673/** Remove page mapping.
674 *
675 * @param mapping Mapping
676 */
677NO_TRACE void as_pagemap_remove(as_page_mapping_t *mapping)
678{
679 odict_remove(&mapping->lpagemap);
680 slab_free(as_page_mapping_cache, mapping);
681}
682
683/** Remove reference to address space area share info.
684 *
685 * If the reference count drops to 0, the sh_info is deallocated.
686 *
687 * @param sh_info Pointer to address space area share info.
688 *
689 */
690NO_TRACE static void sh_info_remove_reference(share_info_t *sh_info)
691{
692 bool dealloc = false;
693
694 mutex_lock(&sh_info->lock);
695 assert(sh_info->refcount);
696
697 if (--sh_info->refcount == 0) {
698 dealloc = true;
699
700 /*
701 * Now walk carefully the pagemap B+tree and free/remove
702 * reference from all frames found there.
703 */
704 as_page_mapping_t *mapping = as_pagemap_first(&sh_info->pagemap);
705 while (mapping != NULL) {
706 frame_free(mapping->frame, 1);
707 mapping = as_pagemap_next(mapping);
708 }
709
710 }
711 mutex_unlock(&sh_info->lock);
712
713 if (dealloc) {
714 if (sh_info->backend && sh_info->backend->destroy_shared_data) {
715 sh_info->backend->destroy_shared_data(
716 sh_info->backend_shared_data);
717 }
718 as_pagemap_finalize(&sh_info->pagemap);
719 free(sh_info);
720 }
721}
722
723/** Create address space area of common attributes.
724 *
725 * The created address space area is added to the target address space.
726 *
727 * @param as Target address space.
728 * @param flags Flags of the area memory.
729 * @param size Size of area.
730 * @param attrs Attributes of the area.
731 * @param backend Address space area backend. NULL if no backend is used.
732 * @param backend_data NULL or a pointer to custom backend data.
733 * @param base Starting virtual address of the area.
734 * If set to AS_AREA_ANY, a suitable mappable area is
735 * found.
736 * @param bound Lowest address bound if base is set to AS_AREA_ANY.
737 * Otherwise ignored.
738 *
739 * @return Address space area on success or NULL on failure.
740 *
741 */
742as_area_t *as_area_create(as_t *as, unsigned int flags, size_t size,
743 unsigned int attrs, mem_backend_t *backend,
744 mem_backend_data_t *backend_data, uintptr_t *base, uintptr_t bound)
745{
746 if ((*base != (uintptr_t) AS_AREA_ANY) && !IS_ALIGNED(*base, PAGE_SIZE))
747 return NULL;
748
749 if (size == 0)
750 return NULL;
751
752 size_t pages = SIZE2FRAMES(size);
753
754 /* Writeable executable areas are not supported. */
755 if ((flags & AS_AREA_EXEC) && (flags & AS_AREA_WRITE))
756 return NULL;
757
758 bool const guarded = flags & AS_AREA_GUARD;
759
760 mutex_lock(&as->lock);
761
762 if (*base == (uintptr_t) AS_AREA_ANY) {
763 *base = as_get_unmapped_area(as, bound, size, guarded);
764 if (*base == (uintptr_t) -1) {
765 mutex_unlock(&as->lock);
766 return NULL;
767 }
768 }
769
770 if (overflows_into_positive(*base, size)) {
771 mutex_unlock(&as->lock);
772 return NULL;
773 }
774
775 if (!check_area_conflicts(as, *base, pages, guarded, NULL)) {
776 mutex_unlock(&as->lock);
777 return NULL;
778 }
779
780 as_area_t *area = (as_area_t *) malloc(sizeof(as_area_t));
781 if (!area) {
782 mutex_unlock(&as->lock);
783 return NULL;
784 }
785
786 mutex_initialize(&area->lock, MUTEX_PASSIVE);
787
788 area->as = as;
789 odlink_initialize(&area->las_areas);
790 area->flags = flags;
791 area->attributes = attrs;
792 area->pages = pages;
793 area->base = *base;
794 area->backend = backend;
795 area->sh_info = NULL;
796
797 if (backend_data)
798 area->backend_data = *backend_data;
799 else
800 memsetb(&area->backend_data, sizeof(area->backend_data), 0);
801
802 share_info_t *si = NULL;
803
804 /*
805 * Create the sharing info structure.
806 * We do this in advance for every new area, even if it is not going
807 * to be shared.
808 */
809 if (!(attrs & AS_AREA_ATTR_PARTIAL)) {
810 si = (share_info_t *) malloc(sizeof(share_info_t));
811 if (!si) {
812 free(area);
813 mutex_unlock(&as->lock);
814 return NULL;
815 }
816 mutex_initialize(&si->lock, MUTEX_PASSIVE);
817 si->refcount = 1;
818 si->shared = false;
819 si->backend_shared_data = NULL;
820 si->backend = backend;
821 as_pagemap_initialize(&si->pagemap);
822
823 area->sh_info = si;
824
825 if (area->backend && area->backend->create_shared_data) {
826 if (!area->backend->create_shared_data(area)) {
827 free(area);
828 mutex_unlock(&as->lock);
829 sh_info_remove_reference(si);
830 return NULL;
831 }
832 }
833 }
834
835 if (area->backend && area->backend->create) {
836 if (!area->backend->create(area)) {
837 free(area);
838 mutex_unlock(&as->lock);
839 if (!(attrs & AS_AREA_ATTR_PARTIAL))
840 sh_info_remove_reference(si);
841 return NULL;
842 }
843 }
844
845 used_space_initialize(&area->used_space);
846 odict_insert(&area->las_areas, &as->as_areas, NULL);
847
848 mutex_unlock(&as->lock);
849
850 return area;
851}
852
853/** Find address space area and lock it.
854 *
855 * @param as Address space.
856 * @param va Virtual address.
857 *
858 * @return Locked address space area containing va on success or
859 * NULL on failure.
860 *
861 */
862NO_TRACE static as_area_t *find_area_and_lock(as_t *as, uintptr_t va)
863{
864 assert(mutex_locked(&as->lock));
865
866 odlink_t *odlink = odict_find_leq(&as->as_areas, &va, NULL);
867 if (odlink == NULL)
868 return NULL;
869
870 as_area_t *area = odict_get_instance(odlink, as_area_t, las_areas);
871 mutex_lock(&area->lock);
872
873 assert(area->base <= va);
874
875 if (va <= area->base + (P2SZ(area->pages) - 1))
876 return area;
877
878 mutex_unlock(&area->lock);
879 return NULL;
880}
881
882/** Find address space area and change it.
883 *
884 * @param as Address space.
885 * @param address Virtual address belonging to the area to be changed.
886 * Must be page-aligned.
887 * @param size New size of the virtual memory block starting at
888 * address.
889 * @param flags Flags influencing the remap operation. Currently unused.
890 *
891 * @return Zero on success or a value from @ref errno.h otherwise.
892 *
893 */
894errno_t as_area_resize(as_t *as, uintptr_t address, size_t size, unsigned int flags)
895{
896 if (!IS_ALIGNED(address, PAGE_SIZE))
897 return EINVAL;
898
899 mutex_lock(&as->lock);
900
901 /*
902 * Locate the area.
903 */
904 as_area_t *area = find_area_and_lock(as, address);
905 if (!area) {
906 mutex_unlock(&as->lock);
907 return ENOENT;
908 }
909
910 if (!area->backend->is_resizable(area)) {
911 /*
912 * The backend does not support resizing for this area.
913 */
914 mutex_unlock(&area->lock);
915 mutex_unlock(&as->lock);
916 return ENOTSUP;
917 }
918
919 mutex_lock(&area->sh_info->lock);
920 if (area->sh_info->shared) {
921 /*
922 * Remapping of shared address space areas
923 * is not supported.
924 */
925 mutex_unlock(&area->sh_info->lock);
926 mutex_unlock(&area->lock);
927 mutex_unlock(&as->lock);
928 return ENOTSUP;
929 }
930 mutex_unlock(&area->sh_info->lock);
931
932 size_t pages = SIZE2FRAMES((address - area->base) + size);
933 if (!pages) {
934 /*
935 * Zero size address space areas are not allowed.
936 */
937 mutex_unlock(&area->lock);
938 mutex_unlock(&as->lock);
939 return EPERM;
940 }
941
942 if (pages < area->pages) {
943 uintptr_t start_free = area->base + P2SZ(pages);
944
945 /*
946 * Shrinking the area.
947 * No need to check for overlaps.
948 */
949
950 page_table_lock(as, false);
951
952 /*
953 * Start TLB shootdown sequence.
954 */
955
956 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES,
957 as->asid, area->base + P2SZ(pages),
958 area->pages - pages);
959
960 /*
961 * Remove frames belonging to used space starting from
962 * the highest addresses downwards until an overlap with
963 * the resized address space area is found.
964 */
965 bool cond = true;
966 while (cond) {
967 used_space_ival_t *ival =
968 used_space_last(&area->used_space);
969 assert(ival != NULL);
970
971 uintptr_t ptr = ival->page;
972 size_t pcount = ival->count;
973 size_t i = 0;
974
975 if (overlaps(ptr, P2SZ(pcount), area->base,
976 P2SZ(pages))) {
977
978 if (ptr + P2SZ(pcount) <= start_free) {
979 /*
980 * The whole interval fits completely
981 * in the resized address space area.
982 */
983 break;
984 }
985
986 /*
987 * Part of the interval corresponding to b and
988 * c overlaps with the resized address space
989 * area.
990 */
991
992 /* We are almost done */
993 cond = false;
994 i = (start_free - ptr) >> PAGE_WIDTH;
995
996 /* Shorten the interval to @c i pages */
997 used_space_shorten_ival(ival, i);
998 } else {
999 /*
1000 * The interval of used space can be completely
1001 * removed.
1002 */
1003 used_space_remove_ival(ival);
1004 }
1005
1006 for (; i < pcount; i++) {
1007 pte_t pte;
1008 bool found = page_mapping_find(as,
1009 ptr + P2SZ(i), false, &pte);
1010
1011 (void) found;
1012 assert(found);
1013 assert(PTE_VALID(&pte));
1014 assert(PTE_PRESENT(&pte));
1015
1016 if ((area->backend) &&
1017 (area->backend->frame_free)) {
1018 area->backend->frame_free(area,
1019 ptr + P2SZ(i),
1020 PTE_GET_FRAME(&pte));
1021 }
1022
1023 page_mapping_remove(as, ptr + P2SZ(i));
1024 }
1025
1026 }
1027
1028 /*
1029 * Finish TLB shootdown sequence.
1030 */
1031
1032 tlb_invalidate_pages(as->asid,
1033 area->base + P2SZ(pages),
1034 area->pages - pages);
1035
1036 /*
1037 * Invalidate software translation caches
1038 * (e.g. TSB on sparc64, PHT on ppc32).
1039 */
1040 as_invalidate_translation_cache(as,
1041 area->base + P2SZ(pages),
1042 area->pages - pages);
1043 tlb_shootdown_finalize(ipl);
1044
1045 page_table_unlock(as, false);
1046 } else {
1047 /*
1048 * Growing the area.
1049 */
1050
1051 if (overflows_into_positive(address, P2SZ(pages)))
1052 return EINVAL;
1053
1054 /*
1055 * Check for overlaps with other address space areas.
1056 */
1057 bool const guarded = area->flags & AS_AREA_GUARD;
1058 if (!check_area_conflicts(as, address, pages, guarded, area)) {
1059 mutex_unlock(&area->lock);
1060 mutex_unlock(&as->lock);
1061 return EADDRNOTAVAIL;
1062 }
1063 }
1064
1065 if (area->backend && area->backend->resize) {
1066 if (!area->backend->resize(area, pages)) {
1067 mutex_unlock(&area->lock);
1068 mutex_unlock(&as->lock);
1069 return ENOMEM;
1070 }
1071 }
1072
1073 area->pages = pages;
1074
1075 mutex_unlock(&area->lock);
1076 mutex_unlock(&as->lock);
1077
1078 return 0;
1079}
1080
1081/** Destroy address space area.
1082 *
1083 * @param as Address space.
1084 * @param address Address within the area to be deleted.
1085 *
1086 * @return Zero on success or a value from @ref errno.h on failure.
1087 *
1088 */
1089errno_t as_area_destroy(as_t *as, uintptr_t address)
1090{
1091 mutex_lock(&as->lock);
1092
1093 as_area_t *area = find_area_and_lock(as, address);
1094 if (!area) {
1095 mutex_unlock(&as->lock);
1096 return ENOENT;
1097 }
1098
1099 if (area->backend && area->backend->destroy)
1100 area->backend->destroy(area);
1101
1102 page_table_lock(as, false);
1103 /*
1104 * Start TLB shootdown sequence.
1105 */
1106 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES, as->asid, area->base,
1107 area->pages);
1108
1109 /*
1110 * Visit only the pages mapped by used_space.
1111 */
1112 used_space_ival_t *ival = used_space_first(&area->used_space);
1113 while (ival != NULL) {
1114 uintptr_t ptr = ival->page;
1115
1116 for (size_t size = 0; size < ival->count; size++) {
1117 pte_t pte;
1118 bool found = page_mapping_find(as,
1119 ptr + P2SZ(size), false, &pte);
1120
1121 (void) found;
1122 assert(found);
1123 assert(PTE_VALID(&pte));
1124 assert(PTE_PRESENT(&pte));
1125
1126 if ((area->backend) &&
1127 (area->backend->frame_free)) {
1128 area->backend->frame_free(area,
1129 ptr + P2SZ(size),
1130 PTE_GET_FRAME(&pte));
1131 }
1132
1133 page_mapping_remove(as, ptr + P2SZ(size));
1134 }
1135
1136 used_space_remove_ival(ival);
1137 ival = used_space_first(&area->used_space);
1138 }
1139
1140 /*
1141 * Finish TLB shootdown sequence.
1142 */
1143
1144 tlb_invalidate_pages(as->asid, area->base, area->pages);
1145
1146 /*
1147 * Invalidate potential software translation caches
1148 * (e.g. TSB on sparc64, PHT on ppc32).
1149 */
1150 as_invalidate_translation_cache(as, area->base, area->pages);
1151 tlb_shootdown_finalize(ipl);
1152
1153 page_table_unlock(as, false);
1154
1155 used_space_finalize(&area->used_space);
1156 area->attributes |= AS_AREA_ATTR_PARTIAL;
1157 sh_info_remove_reference(area->sh_info);
1158
1159 mutex_unlock(&area->lock);
1160
1161 /*
1162 * Remove the empty area from address space.
1163 */
1164 odict_remove(&area->las_areas);
1165
1166 free(area);
1167
1168 mutex_unlock(&as->lock);
1169 return 0;
1170}
1171
1172/** Share address space area with another or the same address space.
1173 *
1174 * Address space area mapping is shared with a new address space area.
1175 * If the source address space area has not been shared so far,
1176 * a new sh_info is created. The new address space area simply gets the
1177 * sh_info of the source area. The process of duplicating the
1178 * mapping is done through the backend share function.
1179 *
1180 * @param src_as Pointer to source address space.
1181 * @param src_base Base address of the source address space area.
1182 * @param acc_size Expected size of the source area.
1183 * @param dst_as Pointer to destination address space.
1184 * @param dst_flags_mask Destination address space area flags mask.
1185 * @param dst_base Target base address. If set to -1,
1186 * a suitable mappable area is found.
1187 * @param bound Lowest address bound if dst_base is set to -1.
1188 * Otherwise ignored.
1189 *
1190 * @return Zero on success.
1191 * @return ENOENT if there is no such task or such address space.
1192 * @return EPERM if there was a problem in accepting the area.
1193 * @return ENOMEM if there was a problem in allocating destination
1194 * address space area.
1195 * @return ENOTSUP if the address space area backend does not support
1196 * sharing.
1197 *
1198 */
1199errno_t as_area_share(as_t *src_as, uintptr_t src_base, size_t acc_size,
1200 as_t *dst_as, unsigned int dst_flags_mask, uintptr_t *dst_base,
1201 uintptr_t bound)
1202{
1203 mutex_lock(&src_as->lock);
1204 as_area_t *src_area = find_area_and_lock(src_as, src_base);
1205 if (!src_area) {
1206 /*
1207 * Could not find the source address space area.
1208 */
1209 mutex_unlock(&src_as->lock);
1210 return ENOENT;
1211 }
1212
1213 if (!src_area->backend->is_shareable(src_area)) {
1214 /*
1215 * The backend does not permit sharing of this area.
1216 */
1217 mutex_unlock(&src_area->lock);
1218 mutex_unlock(&src_as->lock);
1219 return ENOTSUP;
1220 }
1221
1222 size_t src_size = P2SZ(src_area->pages);
1223 unsigned int src_flags = src_area->flags;
1224 mem_backend_t *src_backend = src_area->backend;
1225 mem_backend_data_t src_backend_data = src_area->backend_data;
1226
1227 /* Share the cacheable flag from the original mapping */
1228 if (src_flags & AS_AREA_CACHEABLE)
1229 dst_flags_mask |= AS_AREA_CACHEABLE;
1230
1231 if ((src_size != acc_size) ||
1232 ((src_flags & dst_flags_mask) != dst_flags_mask)) {
1233 mutex_unlock(&src_area->lock);
1234 mutex_unlock(&src_as->lock);
1235 return EPERM;
1236 }
1237
1238 /*
1239 * Now we are committed to sharing the area.
1240 * First, prepare the area for sharing.
1241 * Then it will be safe to unlock it.
1242 */
1243 share_info_t *sh_info = src_area->sh_info;
1244
1245 mutex_lock(&sh_info->lock);
1246 sh_info->refcount++;
1247 bool shared = sh_info->shared;
1248 sh_info->shared = true;
1249 mutex_unlock(&sh_info->lock);
1250
1251 if (!shared) {
1252 /*
1253 * Call the backend to setup sharing.
1254 * This only happens once for each sh_info.
1255 */
1256 src_area->backend->share(src_area);
1257 }
1258
1259 mutex_unlock(&src_area->lock);
1260 mutex_unlock(&src_as->lock);
1261
1262 /*
1263 * Create copy of the source address space area.
1264 * The destination area is created with AS_AREA_ATTR_PARTIAL
1265 * attribute set which prevents race condition with
1266 * preliminary as_page_fault() calls.
1267 * The flags of the source area are masked against dst_flags_mask
1268 * to support sharing in less privileged mode.
1269 */
1270 as_area_t *dst_area = as_area_create(dst_as, dst_flags_mask,
1271 src_size, AS_AREA_ATTR_PARTIAL, src_backend,
1272 &src_backend_data, dst_base, bound);
1273 if (!dst_area) {
1274 /*
1275 * Destination address space area could not be created.
1276 */
1277 sh_info_remove_reference(sh_info);
1278
1279 return ENOMEM;
1280 }
1281
1282 /*
1283 * Now the destination address space area has been
1284 * fully initialized. Clear the AS_AREA_ATTR_PARTIAL
1285 * attribute and set the sh_info.
1286 */
1287 mutex_lock(&dst_as->lock);
1288 mutex_lock(&dst_area->lock);
1289 dst_area->attributes &= ~AS_AREA_ATTR_PARTIAL;
1290 dst_area->sh_info = sh_info;
1291 mutex_unlock(&dst_area->lock);
1292 mutex_unlock(&dst_as->lock);
1293
1294 return 0;
1295}
1296
1297/** Check access mode for address space area.
1298 *
1299 * @param area Address space area.
1300 * @param access Access mode.
1301 *
1302 * @return False if access violates area's permissions, true
1303 * otherwise.
1304 *
1305 */
1306NO_TRACE bool as_area_check_access(as_area_t *area, pf_access_t access)
1307{
1308 assert(mutex_locked(&area->lock));
1309
1310 int flagmap[] = {
1311 [PF_ACCESS_READ] = AS_AREA_READ,
1312 [PF_ACCESS_WRITE] = AS_AREA_WRITE,
1313 [PF_ACCESS_EXEC] = AS_AREA_EXEC
1314 };
1315
1316 if (!(area->flags & flagmap[access]))
1317 return false;
1318
1319 return true;
1320}
1321
1322/** Convert address space area flags to page flags.
1323 *
1324 * @param aflags Flags of some address space area.
1325 *
1326 * @return Flags to be passed to page_mapping_insert().
1327 *
1328 */
1329NO_TRACE static unsigned int area_flags_to_page_flags(unsigned int aflags)
1330{
1331 unsigned int flags = PAGE_USER | PAGE_PRESENT;
1332
1333 if (aflags & AS_AREA_READ)
1334 flags |= PAGE_READ;
1335
1336 if (aflags & AS_AREA_WRITE)
1337 flags |= PAGE_WRITE;
1338
1339 if (aflags & AS_AREA_EXEC)
1340 flags |= PAGE_EXEC;
1341
1342 if (aflags & AS_AREA_CACHEABLE)
1343 flags |= PAGE_CACHEABLE;
1344
1345 return flags;
1346}
1347
1348/** Change adress space area flags.
1349 *
1350 * The idea is to have the same data, but with a different access mode.
1351 * This is needed e.g. for writing code into memory and then executing it.
1352 * In order for this to work properly, this may copy the data
1353 * into private anonymous memory (unless it's already there).
1354 *
1355 * @param as Address space.
1356 * @param flags Flags of the area memory.
1357 * @param address Address within the area to be changed.
1358 *
1359 * @return Zero on success or a value from @ref errno.h on failure.
1360 *
1361 */
1362errno_t as_area_change_flags(as_t *as, unsigned int flags, uintptr_t address)
1363{
1364 /* Flags for the new memory mapping */
1365 unsigned int page_flags = area_flags_to_page_flags(flags);
1366
1367 mutex_lock(&as->lock);
1368
1369 as_area_t *area = find_area_and_lock(as, address);
1370 if (!area) {
1371 mutex_unlock(&as->lock);
1372 return ENOENT;
1373 }
1374
1375 if (area->backend != &anon_backend) {
1376 /* Copying non-anonymous memory not supported yet */
1377 mutex_unlock(&area->lock);
1378 mutex_unlock(&as->lock);
1379 return ENOTSUP;
1380 }
1381
1382 mutex_lock(&area->sh_info->lock);
1383 if (area->sh_info->shared) {
1384 /* Copying shared areas not supported yet */
1385 mutex_unlock(&area->sh_info->lock);
1386 mutex_unlock(&area->lock);
1387 mutex_unlock(&as->lock);
1388 return ENOTSUP;
1389 }
1390 mutex_unlock(&area->sh_info->lock);
1391
1392 /*
1393 * Compute total number of used pages
1394 */
1395 size_t used_pages = 0;
1396
1397 used_space_ival_t *ival = used_space_first(&area->used_space);
1398 while (ival != NULL) {
1399 used_pages += ival->count;
1400 ival = used_space_next(ival);
1401 }
1402
1403 /* An array for storing frame numbers */
1404 uintptr_t *old_frame = malloc(used_pages * sizeof(uintptr_t));
1405 if (!old_frame) {
1406 mutex_unlock(&area->lock);
1407 mutex_unlock(&as->lock);
1408 return ENOMEM;
1409 }
1410
1411 page_table_lock(as, false);
1412
1413 /*
1414 * Start TLB shootdown sequence.
1415 */
1416 ipl_t ipl = tlb_shootdown_start(TLB_INVL_PAGES, as->asid, area->base,
1417 area->pages);
1418
1419 /*
1420 * Remove used pages from page tables and remember their frame
1421 * numbers.
1422 */
1423 size_t frame_idx = 0;
1424
1425 ival = used_space_first(&area->used_space);
1426 while (ival != NULL) {
1427 uintptr_t ptr = ival->page;
1428 size_t size;
1429
1430 for (size = 0; size < ival->count; size++) {
1431 pte_t pte;
1432 bool found = page_mapping_find(as, ptr + P2SZ(size),
1433 false, &pte);
1434
1435 (void) found;
1436 assert(found);
1437 assert(PTE_VALID(&pte));
1438 assert(PTE_PRESENT(&pte));
1439
1440 old_frame[frame_idx++] = PTE_GET_FRAME(&pte);
1441
1442 /* Remove old mapping */
1443 page_mapping_remove(as, ptr + P2SZ(size));
1444 }
1445
1446 ival = used_space_next(ival);
1447 }
1448
1449 /*
1450 * Finish TLB shootdown sequence.
1451 */
1452
1453 tlb_invalidate_pages(as->asid, area->base, area->pages);
1454
1455 /*
1456 * Invalidate potential software translation caches
1457 * (e.g. TSB on sparc64, PHT on ppc32).
1458 */
1459 as_invalidate_translation_cache(as, area->base, area->pages);
1460 tlb_shootdown_finalize(ipl);
1461
1462 page_table_unlock(as, false);
1463
1464 /*
1465 * Set the new flags.
1466 */
1467 area->flags = flags;
1468
1469 /*
1470 * Map pages back in with new flags. This step is kept separate
1471 * so that the memory area could not be accesed with both the old and
1472 * the new flags at once.
1473 */
1474 frame_idx = 0;
1475
1476 ival = used_space_first(&area->used_space);
1477 while (ival != NULL) {
1478 uintptr_t ptr = ival->page;
1479 size_t size;
1480
1481 for (size = 0; size < ival->count; size++) {
1482 page_table_lock(as, false);
1483
1484 /* Insert the new mapping */
1485 page_mapping_insert(as, ptr + P2SZ(size),
1486 old_frame[frame_idx++], page_flags);
1487
1488 page_table_unlock(as, false);
1489 }
1490
1491 ival = used_space_next(ival);
1492 }
1493
1494 free(old_frame);
1495
1496 mutex_unlock(&area->lock);
1497 mutex_unlock(&as->lock);
1498
1499 return 0;
1500}
1501
1502/** Handle page fault within the current address space.
1503 *
1504 * This is the high-level page fault handler. It decides whether the page fault
1505 * can be resolved by any backend and if so, it invokes the backend to resolve
1506 * the page fault.
1507 *
1508 * Interrupts are assumed disabled.
1509 *
1510 * @param address Faulting address.
1511 * @param access Access mode that caused the page fault (i.e.
1512 * read/write/exec).
1513 * @param istate Pointer to the interrupted state.
1514 *
1515 * @return AS_PF_FAULT on page fault.
1516 * @return AS_PF_OK on success.
1517 * @return AS_PF_DEFER if the fault was caused by copy_to_uspace()
1518 * or copy_from_uspace().
1519 *
1520 */
1521int as_page_fault(uintptr_t address, pf_access_t access, istate_t *istate)
1522{
1523 uintptr_t page = ALIGN_DOWN(address, PAGE_SIZE);
1524 int rc = AS_PF_FAULT;
1525
1526 if (!THREAD)
1527 goto page_fault;
1528
1529 if (!AS)
1530 goto page_fault;
1531
1532 mutex_lock(&AS->lock);
1533 as_area_t *area = find_area_and_lock(AS, page);
1534 if (!area) {
1535 /*
1536 * No area contained mapping for 'page'.
1537 * Signal page fault to low-level handler.
1538 */
1539 mutex_unlock(&AS->lock);
1540 goto page_fault;
1541 }
1542
1543 if (area->attributes & AS_AREA_ATTR_PARTIAL) {
1544 /*
1545 * The address space area is not fully initialized.
1546 * Avoid possible race by returning error.
1547 */
1548 mutex_unlock(&area->lock);
1549 mutex_unlock(&AS->lock);
1550 goto page_fault;
1551 }
1552
1553 if ((!area->backend) || (!area->backend->page_fault)) {
1554 /*
1555 * The address space area is not backed by any backend
1556 * or the backend cannot handle page faults.
1557 */
1558 mutex_unlock(&area->lock);
1559 mutex_unlock(&AS->lock);
1560 goto page_fault;
1561 }
1562
1563 page_table_lock(AS, false);
1564
1565 /*
1566 * To avoid race condition between two page faults on the same address,
1567 * we need to make sure the mapping has not been already inserted.
1568 */
1569 pte_t pte;
1570 bool found = page_mapping_find(AS, page, false, &pte);
1571 if (found && PTE_PRESENT(&pte)) {
1572 if (((access == PF_ACCESS_READ) && PTE_READABLE(&pte)) ||
1573 (access == PF_ACCESS_WRITE && PTE_WRITABLE(&pte)) ||
1574 (access == PF_ACCESS_EXEC && PTE_EXECUTABLE(&pte))) {
1575 page_table_unlock(AS, false);
1576 mutex_unlock(&area->lock);
1577 mutex_unlock(&AS->lock);
1578 return AS_PF_OK;
1579 }
1580 }
1581
1582 /*
1583 * Resort to the backend page fault handler.
1584 */
1585 rc = area->backend->page_fault(area, page, access);
1586 if (rc != AS_PF_OK) {
1587 page_table_unlock(AS, false);
1588 mutex_unlock(&area->lock);
1589 mutex_unlock(&AS->lock);
1590 goto page_fault;
1591 }
1592
1593 page_table_unlock(AS, false);
1594 mutex_unlock(&area->lock);
1595 mutex_unlock(&AS->lock);
1596 return AS_PF_OK;
1597
1598page_fault:
1599 if (THREAD && THREAD->in_copy_from_uspace) {
1600 THREAD->in_copy_from_uspace = false;
1601 istate_set_retaddr(istate,
1602 (uintptr_t) &memcpy_from_uspace_failover_address);
1603 } else if (THREAD && THREAD->in_copy_to_uspace) {
1604 THREAD->in_copy_to_uspace = false;
1605 istate_set_retaddr(istate,
1606 (uintptr_t) &memcpy_to_uspace_failover_address);
1607 } else if (rc == AS_PF_SILENT) {
1608 printf("Killing task %" PRIu64 " due to a "
1609 "failed late reservation request.\n", TASK->taskid);
1610 task_kill_self(true);
1611 } else {
1612 fault_if_from_uspace(istate, "Page fault: %p.", (void *) address);
1613 panic_memtrap(istate, access, address, NULL);
1614 }
1615
1616 return AS_PF_DEFER;
1617}
1618
1619/** Switch address spaces.
1620 *
1621 * Note that this function cannot sleep as it is essentially a part of
1622 * scheduling. Sleeping here would lead to deadlock on wakeup. Another
1623 * thing which is forbidden in this context is locking the address space.
1624 *
1625 * When this function is entered, no spinlocks may be held.
1626 *
1627 * @param old Old address space or NULL.
1628 * @param new New address space.
1629 *
1630 */
1631void as_switch(as_t *old_as, as_t *new_as)
1632{
1633 DEADLOCK_PROBE_INIT(p_asidlock);
1634 preemption_disable();
1635
1636retry:
1637 (void) interrupts_disable();
1638 if (!spinlock_trylock(&asidlock)) {
1639 /*
1640 * Avoid deadlock with TLB shootdown.
1641 * We can enable interrupts here because
1642 * preemption is disabled. We should not be
1643 * holding any other lock.
1644 */
1645 (void) interrupts_enable();
1646 DEADLOCK_PROBE(p_asidlock, DEADLOCK_THRESHOLD);
1647 goto retry;
1648 }
1649 preemption_enable();
1650
1651 /*
1652 * First, take care of the old address space.
1653 */
1654 if (old_as) {
1655 assert(old_as->cpu_refcount);
1656
1657 if ((--old_as->cpu_refcount == 0) && (old_as != AS_KERNEL)) {
1658 /*
1659 * The old address space is no longer active on
1660 * any processor. It can be appended to the
1661 * list of inactive address spaces with assigned
1662 * ASID.
1663 */
1664 assert(old_as->asid != ASID_INVALID);
1665
1666 list_append(&old_as->inactive_as_with_asid_link,
1667 &inactive_as_with_asid_list);
1668 }
1669
1670 /*
1671 * Perform architecture-specific tasks when the address space
1672 * is being removed from the CPU.
1673 */
1674 as_deinstall_arch(old_as);
1675 }
1676
1677 /*
1678 * Second, prepare the new address space.
1679 */
1680 if ((new_as->cpu_refcount++ == 0) && (new_as != AS_KERNEL)) {
1681 if (new_as->asid != ASID_INVALID)
1682 list_remove(&new_as->inactive_as_with_asid_link);
1683 else
1684 new_as->asid = asid_get();
1685 }
1686
1687#ifdef AS_PAGE_TABLE
1688 SET_PTL0_ADDRESS(new_as->genarch.page_table);
1689#endif
1690
1691 /*
1692 * Perform architecture-specific steps.
1693 * (e.g. write ASID to hardware register etc.)
1694 */
1695 as_install_arch(new_as);
1696
1697 spinlock_unlock(&asidlock);
1698
1699 AS = new_as;
1700}
1701
1702/** Compute flags for virtual address translation subsytem.
1703 *
1704 * @param area Address space area.
1705 *
1706 * @return Flags to be used in page_mapping_insert().
1707 *
1708 */
1709NO_TRACE unsigned int as_area_get_flags(as_area_t *area)
1710{
1711 assert(mutex_locked(&area->lock));
1712
1713 return area_flags_to_page_flags(area->flags);
1714}
1715
1716/** Get key function for the @c as_t.as_areas ordered dictionary.
1717 *
1718 * @param odlink Link
1719 * @return Pointer to task ID cast as 'void *'
1720 */
1721static void *as_areas_getkey(odlink_t *odlink)
1722{
1723 as_area_t *area = odict_get_instance(odlink, as_area_t, las_areas);
1724 return (void *) &area->base;
1725}
1726
1727/** Key comparison function for the @c as_t.as_areas ordered dictionary.
1728 *
1729 * @param a Pointer to area A base
1730 * @param b Pointer to area B base
1731 * @return -1, 0, 1 iff base of A is lower than, equal to, higher than B
1732 */
1733static int as_areas_cmp(void *a, void *b)
1734{
1735 uintptr_t base_a = *(uintptr_t *)a;
1736 uintptr_t base_b = *(uintptr_t *)b;
1737
1738 if (base_a < base_b)
1739 return -1;
1740 else if (base_a == base_b)
1741 return 0;
1742 else
1743 return +1;
1744}
1745
1746/** Create page table.
1747 *
1748 * Depending on architecture, create either address space private or global page
1749 * table.
1750 *
1751 * @param flags Flags saying whether the page table is for the kernel
1752 * address space.
1753 *
1754 * @return First entry of the page table.
1755 *
1756 */
1757NO_TRACE pte_t *page_table_create(unsigned int flags)
1758{
1759 assert(as_operations);
1760 assert(as_operations->page_table_create);
1761
1762 return as_operations->page_table_create(flags);
1763}
1764
1765/** Destroy page table.
1766 *
1767 * Destroy page table in architecture specific way.
1768 *
1769 * @param page_table Physical address of PTL0.
1770 *
1771 */
1772NO_TRACE void page_table_destroy(pte_t *page_table)
1773{
1774 assert(as_operations);
1775 assert(as_operations->page_table_destroy);
1776
1777 as_operations->page_table_destroy(page_table);
1778}
1779
1780/** Lock page table.
1781 *
1782 * This function should be called before any page_mapping_insert(),
1783 * page_mapping_remove() and page_mapping_find().
1784 *
1785 * Locking order is such that address space areas must be locked
1786 * prior to this call. Address space can be locked prior to this
1787 * call in which case the lock argument is false.
1788 *
1789 * @param as Address space.
1790 * @param lock If false, do not attempt to lock as->lock.
1791 *
1792 */
1793NO_TRACE void page_table_lock(as_t *as, bool lock)
1794{
1795 assert(as_operations);
1796 assert(as_operations->page_table_lock);
1797
1798 as_operations->page_table_lock(as, lock);
1799}
1800
1801/** Unlock page table.
1802 *
1803 * @param as Address space.
1804 * @param unlock If false, do not attempt to unlock as->lock.
1805 *
1806 */
1807NO_TRACE void page_table_unlock(as_t *as, bool unlock)
1808{
1809 assert(as_operations);
1810 assert(as_operations->page_table_unlock);
1811
1812 as_operations->page_table_unlock(as, unlock);
1813}
1814
1815/** Test whether page tables are locked.
1816 *
1817 * @param as Address space where the page tables belong.
1818 *
1819 * @return True if the page tables belonging to the address soace
1820 * are locked, otherwise false.
1821 */
1822NO_TRACE bool page_table_locked(as_t *as)
1823{
1824 assert(as_operations);
1825 assert(as_operations->page_table_locked);
1826
1827 return as_operations->page_table_locked(as);
1828}
1829
1830/** Return size of the address space area with given base.
1831 *
1832 * @param base Arbitrary address inside the address space area.
1833 *
1834 * @return Size of the address space area in bytes or zero if it
1835 * does not exist.
1836 *
1837 */
1838size_t as_area_get_size(uintptr_t base)
1839{
1840 size_t size;
1841
1842 page_table_lock(AS, true);
1843 as_area_t *src_area = find_area_and_lock(AS, base);
1844
1845 if (src_area) {
1846 size = P2SZ(src_area->pages);
1847 mutex_unlock(&src_area->lock);
1848 } else
1849 size = 0;
1850
1851 page_table_unlock(AS, true);
1852 return size;
1853}
1854
1855/** Initialize used space map.
1856 *
1857 * @param used_space Used space map
1858 */
1859static void used_space_initialize(used_space_t *used_space)
1860{
1861 odict_initialize(&used_space->ivals, used_space_getkey, used_space_cmp);
1862 used_space->pages = 0;
1863}
1864
1865/** Finalize used space map.
1866 *
1867 * @param used_space Used space map
1868 */
1869static void used_space_finalize(used_space_t *used_space)
1870{
1871 assert(odict_empty(&used_space->ivals));
1872 odict_finalize(&used_space->ivals);
1873}
1874
1875/** Get first interval of used space.
1876 *
1877 * @param used_space Used space map
1878 * @return First interval or @c NULL if there are none
1879 */
1880used_space_ival_t *used_space_first(used_space_t *used_space)
1881{
1882 odlink_t *odlink = odict_first(&used_space->ivals);
1883
1884 if (odlink == NULL)
1885 return NULL;
1886
1887 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1888}
1889
1890/** Get next interval of used space.
1891 *
1892 * @param cur Current interval
1893 * @return Next interval or @c NULL if there are none
1894 */
1895used_space_ival_t *used_space_next(used_space_ival_t *cur)
1896{
1897 odlink_t *odlink = odict_next(&cur->lused_space,
1898 &cur->used_space->ivals);
1899
1900 if (odlink == NULL)
1901 return NULL;
1902
1903 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1904}
1905
1906/** Get last interval of used space.
1907 *
1908 * @param used_space Used space map
1909 * @return First interval or @c NULL if there are none
1910 */
1911static used_space_ival_t *used_space_last(used_space_t *used_space)
1912{
1913 odlink_t *odlink = odict_last(&used_space->ivals);
1914
1915 if (odlink == NULL)
1916 return NULL;
1917
1918 return odict_get_instance(odlink, used_space_ival_t, lused_space);
1919}
1920
1921/** Find the first interval that contains addresses greater than or equal to
1922 * @a ptr.
1923 *
1924 * @param used_space Used space map
1925 * @param ptr Virtual address
1926 *
1927 * @return Used space interval or @c NULL if none matches
1928 */
1929used_space_ival_t *used_space_find_gteq(used_space_t *used_space, uintptr_t ptr)
1930{
1931 odlink_t *odlink;
1932 used_space_ival_t *ival;
1933
1934 /* Find last interval to start at address less than @a ptr */
1935 odlink = odict_find_lt(&used_space->ivals, &ptr, NULL);
1936 if (odlink != NULL) {
1937 ival = odict_get_instance(odlink, used_space_ival_t,
1938 lused_space);
1939
1940 /* If the interval extends above @a ptr, return it */
1941 if (ival->page + P2SZ(ival->count) > ptr)
1942 return ival;
1943
1944 /*
1945 * Otherwise, if a next interval exists, it must match
1946 * the criteria.
1947 */
1948 odlink = odict_next(&ival->lused_space, &used_space->ivals);
1949 } else {
1950 /*
1951 * No interval with lower base address, so if there is any
1952 * interval at all, it must match the criteria
1953 */
1954 odlink = odict_first(&used_space->ivals);
1955 }
1956
1957 if (odlink != NULL) {
1958 ival = odict_get_instance(odlink, used_space_ival_t,
1959 lused_space);
1960 return ival;
1961 }
1962
1963 return NULL;
1964}
1965
1966/** Get key function for used space ordered dictionary.
1967 *
1968 * The key is the virtual address of the first page
1969 *
1970 * @param odlink Ordered dictionary link (used_space_ival_t.lused_space)
1971 * @return Pointer to virtual address of first page cast as @c void *.
1972 */
1973static void *used_space_getkey(odlink_t *odlink)
1974{
1975 used_space_ival_t *ival = odict_get_instance(odlink, used_space_ival_t,
1976 lused_space);
1977 return (void *) &ival->page;
1978}
1979
1980/** Compare function for used space ordered dictionary.
1981 *
1982 * @param a Pointer to virtual address of first page cast as @c void *
1983 * @param b Pointer to virtual address of first page cast as @c void *
1984 * @return Less than zero, zero, greater than zero if virtual address @a a
1985 * is less than, equal to, greater than virtual address b, respectively.
1986 */
1987static int used_space_cmp(void *a, void *b)
1988{
1989 uintptr_t va = *(uintptr_t *) a;
1990 uintptr_t vb = *(uintptr_t *) b;
1991
1992 if (va < vb)
1993 return -1;
1994 else if (va == vb)
1995 return 0;
1996 else
1997 return +1;
1998}
1999
2000/** Remove used space interval.
2001 *
2002 * @param ival Used space interval
2003 */
2004static void used_space_remove_ival(used_space_ival_t *ival)
2005{
2006 ival->used_space->pages -= ival->count;
2007 odict_remove(&ival->lused_space);
2008 slab_free(used_space_ival_cache, ival);
2009}
2010
2011/** Shorten used space interval.
2012 *
2013 * @param ival Used space interval
2014 * @param count New number of pages in the interval
2015 */
2016static void used_space_shorten_ival(used_space_ival_t *ival, size_t count)
2017{
2018 assert(count > 0);
2019 assert(count < ival->count);
2020
2021 ival->used_space->pages -= ival->count - count;
2022 ival->count = count;
2023}
2024
2025/** Mark portion of address space area as used.
2026 *
2027 * The address space area must be already locked.
2028 *
2029 * @param used_space Used space map
2030 * @param page First page to be marked.
2031 * @param count Number of page to be marked.
2032 *
2033 * @return False on failure or true on success.
2034 *
2035 */
2036bool used_space_insert(used_space_t *used_space, uintptr_t page, size_t count)
2037{
2038 used_space_ival_t *a;
2039 used_space_ival_t *b;
2040 bool adj_a;
2041 bool adj_b;
2042 odlink_t *odlink;
2043 used_space_ival_t *ival;
2044
2045 assert(IS_ALIGNED(page, PAGE_SIZE));
2046 assert(count);
2047
2048 /* Interval to the left */
2049 odlink = odict_find_lt(&used_space->ivals, &page, NULL);
2050 a = (odlink != NULL) ?
2051 odict_get_instance(odlink, used_space_ival_t, lused_space) :
2052 NULL;
2053
2054 /* Interval to the right */
2055 b = (a != NULL) ? used_space_next(a) :
2056 used_space_first(used_space);
2057
2058 /* Check for conflict with left interval */
2059 if (a != NULL && overlaps(a->page, P2SZ(a->count), page, P2SZ(count)))
2060 return false;
2061
2062 /* Check for conflict with right interval */
2063 if (b != NULL && overlaps(page, P2SZ(count), b->page, P2SZ(b->count)))
2064 return false;
2065
2066 /* Check if A is adjacent to the new interval */
2067 adj_a = (a != NULL) && (a->page + P2SZ(a->count) == page);
2068 /* Check if the new interval is adjacent to B*/
2069 adj_b = (b != NULL) && page + P2SZ(count) == b->page;
2070
2071 if (adj_a && adj_b) {
2072 /* Fuse into a single interval */
2073 a->count += count + b->count;
2074 used_space_remove_ival(b);
2075 } else if (adj_a) {
2076 /* Append to A */
2077 a->count += count;
2078 } else if (adj_b) {
2079 /* Prepend to B */
2080 b->page = page;
2081 b->count += count;
2082 } else {
2083 /* Create new interval */
2084 ival = slab_alloc(used_space_ival_cache, 0);
2085 ival->used_space = used_space;
2086 odlink_initialize(&ival->lused_space);
2087 ival->page = page;
2088 ival->count = count;
2089
2090 odict_insert(&ival->lused_space, &used_space->ivals,
2091 NULL);
2092 }
2093
2094 used_space->pages += count;
2095 return true;
2096}
2097
2098/*
2099 * Address space related syscalls.
2100 */
2101
2102sysarg_t sys_as_area_create(uintptr_t base, size_t size, unsigned int flags,
2103 uintptr_t bound, as_area_pager_info_t *pager_info)
2104{
2105 uintptr_t virt = base;
2106 mem_backend_t *backend;
2107 mem_backend_data_t backend_data;
2108
2109 if (pager_info == AS_AREA_UNPAGED)
2110 backend = &anon_backend;
2111 else {
2112 backend = &user_backend;
2113 if (copy_from_uspace(&backend_data.pager_info, pager_info,
2114 sizeof(as_area_pager_info_t)) != EOK) {
2115 return (sysarg_t) AS_MAP_FAILED;
2116 }
2117 }
2118 as_area_t *area = as_area_create(AS, flags, size,
2119 AS_AREA_ATTR_NONE, backend, &backend_data, &virt, bound);
2120 if (area == NULL)
2121 return (sysarg_t) AS_MAP_FAILED;
2122
2123 return (sysarg_t) virt;
2124}
2125
2126sys_errno_t sys_as_area_resize(uintptr_t address, size_t size, unsigned int flags)
2127{
2128 return (sys_errno_t) as_area_resize(AS, address, size, 0);
2129}
2130
2131sys_errno_t sys_as_area_change_flags(uintptr_t address, unsigned int flags)
2132{
2133 return (sys_errno_t) as_area_change_flags(AS, flags, address);
2134}
2135
2136sys_errno_t sys_as_area_get_info(uintptr_t address, as_area_info_t *dest)
2137{
2138 as_area_t *area;
2139
2140 mutex_lock(&AS->lock);
2141 area = find_area_and_lock(AS, address);
2142 if (area == NULL) {
2143 mutex_unlock(&AS->lock);
2144 return ENOENT;
2145 }
2146
2147 dest->start_addr = area->base;
2148 dest->size = P2SZ(area->pages);
2149 dest->flags = area->flags;
2150
2151 mutex_unlock(&area->lock);
2152 mutex_unlock(&AS->lock);
2153 return EOK;
2154}
2155
2156sys_errno_t sys_as_area_destroy(uintptr_t address)
2157{
2158 return (sys_errno_t) as_area_destroy(AS, address);
2159}
2160
2161/** Get list of adress space areas.
2162 *
2163 * @param as Address space.
2164 * @param obuf Place to save pointer to returned buffer.
2165 * @param osize Place to save size of returned buffer.
2166 *
2167 */
2168as_area_info_t *as_get_area_info(as_t *as, size_t *osize)
2169{
2170 mutex_lock(&as->lock);
2171
2172 /* Count number of areas. */
2173 size_t area_cnt = odict_count(&as->as_areas);
2174
2175 size_t isize = area_cnt * sizeof(as_area_info_t);
2176 as_area_info_t *info = malloc(isize);
2177 if (!info) {
2178 mutex_unlock(&as->lock);
2179 return NULL;
2180 }
2181
2182 /* Record area data. */
2183
2184 size_t area_idx = 0;
2185
2186 as_area_t *area = as_area_first(as);
2187 while (area != NULL) {
2188 assert(area_idx < area_cnt);
2189 mutex_lock(&area->lock);
2190
2191 info[area_idx].start_addr = area->base;
2192 info[area_idx].size = P2SZ(area->pages);
2193 info[area_idx].flags = area->flags;
2194 ++area_idx;
2195
2196 mutex_unlock(&area->lock);
2197 area = as_area_next(area);
2198 }
2199
2200 mutex_unlock(&as->lock);
2201
2202 *osize = isize;
2203 return info;
2204}
2205
2206/** Print out information about address space.
2207 *
2208 * @param as Address space.
2209 *
2210 */
2211void as_print(as_t *as)
2212{
2213 mutex_lock(&as->lock);
2214
2215 /* Print out info about address space areas */
2216 as_area_t *area = as_area_first(as);
2217 while (area != NULL) {
2218 mutex_lock(&area->lock);
2219 printf("as_area: %p, base=%p, pages=%zu"
2220 " (%p - %p)\n", area, (void *) area->base,
2221 area->pages, (void *) area->base,
2222 (void *) (area->base + P2SZ(area->pages)));
2223 mutex_unlock(&area->lock);
2224
2225 area = as_area_next(area);
2226 }
2227
2228 mutex_unlock(&as->lock);
2229}
2230
2231/** @}
2232 */
Note: See TracBrowser for help on using the repository browser.