/* Copyright (c) 2016, 2017, 2018, 2019, 2020, 2021, 2023 Dennis Wölfing
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* kernel/include/dennix/kernel/addressspace.h
 * Address space class.
 */

#ifndef KERNEL_ADDRESSSPACE_H
#define KERNEL_ADDRESSSPACE_H

#include <dennix/mman.h>
#include <dennix/kernel/kthread.h>
#include <dennix/kernel/memorysegment.h>

#define PROT_WRITE_COMBINING (1 << 17)

class AddressSpace : public ConstructorMayFail {
public:
    AddressSpace();
    ~AddressSpace();
    NOT_COPYABLE(AddressSpace);
    NOT_MOVABLE(AddressSpace);

    void activate();
    AddressSpace* fork();
    paddr_t getPhysicalAddress(vaddr_t virtualAddress);
    vaddr_t mapAt(vaddr_t virtualAddress, paddr_t physicalAddress,
            int protection);
    vaddr_t mapFromOtherAddressSpace(AddressSpace* sourceSpace,
            vaddr_t sourceVirtualAddress, size_t size, int protection);
    vaddr_t mapMemory(size_t size, int protection);
    vaddr_t mapMemory(vaddr_t virtualAddress, size_t size, int protection);
    vaddr_t mapPhysical(paddr_t physicalAddress, size_t size, int protection);
    vaddr_t mapUnaligned(paddr_t physicalAddress, size_t size, int protection,
            vaddr_t& mapping, size_t& mapSize);
    void unmapMemory(vaddr_t virtualAddress, size_t size);
    void unmapPhysical(vaddr_t firstVirtualAddress, size_t size);
private:
    bool isActive();
    vaddr_t mapMemoryInternal(vaddr_t virtualAddress, size_t size,
            int protection);
    void unmap(vaddr_t virtualAddress);
public:
    MemorySegment::List segments;
private:
    AddressSpace* prev;
    AddressSpace* next;
    kthread_mutex_t mutex;
    vaddr_t mappingArea;
#ifdef __i386__
    paddr_t pageDir;
#elif defined(__x86_64__)
    paddr_t pml4;
#endif
public:
    static void initialize();
    static bool patSupported;
private:
    static AddressSpace* activeAddressSpace;
};

// Global variable for the kernel's address space
extern AddressSpace* const kernelSpace;

#endif
