--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -3,6 +3,9 @@
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.ImmutableList;
+import co.aikar.timings.Timings;
+import com.destroystokyo.paper.event.server.PaperServerListPingEvent;
+import com.google.common.base.Stopwatch;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
@@ -15,37 +18,40 @@
 import it.unimi.dsi.fastutil.objects.ObjectArrayList;
 import it.unimi.dsi.fastutil.objects.ObjectArraySet;
 import java.awt.image.BufferedImage;
+import java.io.BufferedWriter;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.Writer;
 import java.lang.management.ManagementFactory;
 import java.lang.management.ThreadInfo;
 import java.lang.management.ThreadMXBean;
 import java.net.Proxy;
 import java.nio.file.FileStore;
 import java.nio.file.Files;
+import java.nio.file.LinkOption;
 import java.nio.file.Path;
 import java.security.KeyPair;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
-import java.util.Map.Entry;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.Executor;
-import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.BooleanSupplier;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import javax.annotation.Nullable;
 import javax.imageio.ImageIO;
 import net.minecraft.CrashReport;
@@ -76,17 +82,6 @@
 import net.minecraft.obfuscate.DontObfuscate;
 import net.minecraft.resources.ResourceKey;
 import net.minecraft.resources.ResourceLocation;
-import net.minecraft.server.bossevents.CustomBossEvents;
-import net.minecraft.server.level.DemoMode;
-import net.minecraft.server.level.PlayerRespawnLogic;
-import net.minecraft.server.level.ServerChunkCache;
-import net.minecraft.server.level.ServerLevel;
-import net.minecraft.server.level.ServerPlayer;
-import net.minecraft.server.level.ServerPlayerGameMode;
-import net.minecraft.server.level.progress.ChunkProgressListener;
-import net.minecraft.server.level.progress.ChunkProgressListenerFactory;
-import net.minecraft.server.network.ServerConnectionListener;
-import net.minecraft.server.network.TextFilter;
 import net.minecraft.server.packs.PackType;
 import net.minecraft.server.packs.repository.Pack;
 import net.minecraft.server.packs.repository.PackRepository;
@@ -103,9 +98,11 @@
 import net.minecraft.util.ModCheck;
 import net.minecraft.util.Mth;
 import net.minecraft.util.NativeModuleLister;
+import net.minecraft.util.ProgressListener;
 import net.minecraft.util.RandomSource;
 import net.minecraft.util.SignatureValidator;
 import net.minecraft.util.TimeUtil;
+import net.minecraft.util.datafix.DataFixers;
 import net.minecraft.util.debugchart.RemoteDebugSampleType;
 import net.minecraft.util.debugchart.SampleLogger;
 import net.minecraft.util.debugchart.TpsDebugDimensions;
@@ -124,6 +121,7 @@
 import net.minecraft.util.thread.ReentrantBlockableEventLoop;
 import net.minecraft.world.Difficulty;
 import net.minecraft.world.RandomSequences;
+import net.minecraft.world.entity.Entity;
 import net.minecraft.world.entity.ai.village.VillageSiege;
 import net.minecraft.world.entity.npc.CatSpawner;
 import net.minecraft.world.entity.npc.WanderingTraderSpawner;
@@ -143,35 +141,72 @@
 import net.minecraft.world.level.WorldDataConfiguration;
 import net.minecraft.world.level.biome.BiomeManager;
 import net.minecraft.world.level.block.Block;
-import net.minecraft.world.level.border.BorderChangeListener;
 import net.minecraft.world.level.border.WorldBorder;
 import net.minecraft.world.level.chunk.storage.ChunkIOErrorReporter;
 import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
 import net.minecraft.world.level.dimension.LevelStem;
+import net.minecraft.world.level.levelgen.WorldOptions;
+import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
+import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
+import net.minecraft.world.level.storage.WorldData;
+import org.slf4j.Logger;
+
+// CraftBukkit start
+import com.mojang.serialization.Dynamic;
+import com.mojang.serialization.Lifecycle;
+import java.io.File;
+import java.util.Random;
+// import jline.console.ConsoleReader; // Paper
+import joptsimple.OptionSet;
+import net.minecraft.nbt.NbtException;
+import net.minecraft.nbt.ReportedNbtException;
+import net.minecraft.server.bossevents.CustomBossEvents;
+import net.minecraft.server.dedicated.DedicatedServer;
+import net.minecraft.server.dedicated.DedicatedServerProperties;
+import net.minecraft.server.level.DemoMode;
+import net.minecraft.server.level.PlayerRespawnLogic;
+import net.minecraft.server.level.ServerChunkCache;
+import net.minecraft.server.level.ServerLevel;
+import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.server.level.ServerPlayerGameMode;
+import net.minecraft.server.level.progress.ChunkProgressListener;
+import net.minecraft.server.level.progress.ChunkProgressListenerFactory;
+import net.minecraft.server.network.ServerConnectionListener;
+import net.minecraft.server.network.TextFilter;
 import net.minecraft.world.level.levelgen.Heightmap;
 import net.minecraft.world.level.levelgen.PatrolSpawner;
 import net.minecraft.world.level.levelgen.PhantomSpawner;
-import net.minecraft.world.level.levelgen.WorldOptions;
-import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
+import net.minecraft.world.level.levelgen.WorldDimensions;
+import net.minecraft.world.level.levelgen.presets.WorldPresets;
 import net.minecraft.world.level.storage.CommandStorage;
-import net.minecraft.world.level.storage.DerivedLevelData;
 import net.minecraft.world.level.storage.DimensionDataStorage;
 import net.minecraft.world.level.storage.LevelData;
+import net.minecraft.world.level.storage.LevelDataAndDimensions;
 import net.minecraft.world.level.storage.LevelResource;
 import net.minecraft.world.level.storage.LevelStorageSource;
+import net.minecraft.world.level.storage.LevelSummary;
 import net.minecraft.world.level.storage.PlayerDataStorage;
+import net.minecraft.world.level.storage.PrimaryLevelData;
 import net.minecraft.world.level.storage.ServerLevelData;
-import net.minecraft.world.level.storage.WorldData;
+import net.minecraft.world.level.validation.ContentValidationException;
 import net.minecraft.world.phys.Vec2;
 import net.minecraft.world.phys.Vec3;
-import org.slf4j.Logger;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.CraftRegistry;
+import org.bukkit.event.server.ServerLoadEvent;
+// CraftBukkit end
 
-public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTask> implements ServerInfo, ChunkIOErrorReporter, CommandSource, AutoCloseable {
+import co.aikar.timings.MinecraftTimings; // Paper
+
+public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTask> implements ServerInfo, ChunkIOErrorReporter, CommandSource, AutoCloseable, ca.spottedleaf.moonrise.patches.chunk_system.server.ChunkSystemMinecraftServer { // Paper - rewrite chunk system
+
+    private static MinecraftServer SERVER; // Paper
     public static final Logger LOGGER = LogUtils.getLogger();
+    public static final net.kyori.adventure.text.logger.slf4j.ComponentLogger COMPONENT_LOGGER = net.kyori.adventure.text.logger.slf4j.ComponentLogger.logger(LOGGER.getName()); // Paper
     public static final String VANILLA_BRAND = "vanilla";
     private static final float AVERAGE_TICK_TIME_SMOOTHING = 0.8F;
     private static final int TICK_STATS_SPAN = 100;
-    private static final long OVERLOADED_THRESHOLD_NANOS = 20L * TimeUtil.NANOSECONDS_PER_SECOND / 20L;
+    private static final long OVERLOADED_THRESHOLD_NANOS = 30L * TimeUtil.NANOSECONDS_PER_SECOND / 20L; // CraftBukkit
     private static final int OVERLOADED_TICKS_THRESHOLD = 20;
     private static final long OVERLOADED_WARNING_INTERVAL_NANOS = 10L * TimeUtil.NANOSECONDS_PER_SECOND;
     private static final int OVERLOADED_TICKS_WARNING_INTERVAL = 100;
@@ -183,18 +218,15 @@
     private static final int MIMINUM_AUTOSAVE_TICKS = 100;
     private static final int MAX_TICK_LATENCY = 3;
     public static final int ABSOLUTE_MAX_WORLD_SIZE = 29999984;
-    public static final LevelSettings DEMO_SETTINGS = new LevelSettings(
-        "Demo World", GameType.SURVIVAL, false, Difficulty.NORMAL, false, new GameRules(), WorldDataConfiguration.DEFAULT
-    );
+    public static final LevelSettings DEMO_SETTINGS = new LevelSettings("Demo World", GameType.SURVIVAL, false, Difficulty.NORMAL, false, new GameRules(), WorldDataConfiguration.DEFAULT);
     public static final GameProfile ANONYMOUS_PLAYER_PROFILE = new GameProfile(Util.NIL_UUID, "Anonymous Player");
     public LevelStorageSource.LevelStorageAccess storageSource;
     public final PlayerDataStorage playerDataStorage;
     private final List<Runnable> tickables = Lists.newArrayList();
-    private MetricsRecorder metricsRecorder = InactiveMetricsRecorder.INSTANCE;
-    private ProfilerFiller profiler = this.metricsRecorder.getProfiler();
-    private Consumer<ProfileResults> onMetricsRecordingStopped = profileResult -> this.stopRecordingMetrics();
-    private Consumer<Path> onMetricsRecordingFinished = path -> {
-    };
+    private MetricsRecorder metricsRecorder;
+    private ProfilerFiller profiler;
+    private Consumer<ProfileResults> onMetricsRecordingStopped;
+    private Consumer<Path> onMetricsRecordingFinished;
     private boolean willStartRecordingMetrics;
     @Nullable
     private MinecraftServer.TimeProfiler debugCommandProfiler;
@@ -205,27 +237,32 @@
     private ServerStatus status;
     @Nullable
     private ServerStatus.Favicon statusIcon;
-    private final RandomSource random = RandomSource.create();
+    private final RandomSource random;
     public final DataFixer fixerUpper;
     private String localIp;
-    private int port = -1;
+    private int port;
     private final LayeredRegistryAccess<RegistryLayer> registries;
-    private Map<ResourceKey<Level>, ServerLevel> levels = Maps.newLinkedHashMap();
+    private Map<ResourceKey<Level>, ServerLevel> levels;
     private PlayerList playerList;
-    private volatile boolean running = true;
+    private volatile boolean running;
+    private volatile boolean isRestarting = false; // Paper - flag to signify we're attempting to restart
     private boolean stopped;
     private int tickCount;
-    private int ticksUntilAutosave = 6000;
+    private int ticksUntilAutosave;
     protected final Proxy proxy;
     private boolean onlineMode;
     private boolean preventProxyConnections;
     private boolean pvp;
     private boolean allowFlight;
-    @Nullable
-    private String motd;
+    private net.kyori.adventure.text.Component motd; // Paper - Adventure
     private int playerIdleTimeout;
-    private final long[] tickTimesNanos = new long[100];
-    private long aggregatedTickTimesNanos = 0L;
+    private final long[] tickTimesNanos;
+    private long aggregatedTickTimesNanos;
+    // Paper start - Add tick times API and /mspt command
+    public final TickTimes tickTimes5s = new TickTimes(100);
+    public final TickTimes tickTimes10s = new TickTimes(200);
+    public final TickTimes tickTimes60s = new TickTimes(1200);
+    // Paper end - Add tick times API and /mspt command
     @Nullable
     private KeyPair keyPair;
     @Nullable
@@ -236,17 +273,17 @@
     protected final Services services;
     private long lastServerStatus;
     public final Thread serverThread;
-    private long lastTickNanos = Util.getNanos();
-    private long taskExecutionStartNanos = Util.getNanos();
+    private long lastTickNanos;
+    private long taskExecutionStartNanos;
     private long idleTimeNanos;
-    private long nextTickTimeNanos = Util.getNanos();
+    private long nextTickTimeNanos;
     private long delayedTasksMaxNextTickTimeNanos;
     private boolean mayHaveDelayedTasks;
     private final PackRepository packRepository;
-    private final ServerScoreboard scoreboard = new ServerScoreboard(this);
+    private final ServerScoreboard scoreboard;
     @Nullable
     private CommandStorage commandStorage;
-    private final CustomBossEvents customBossEvents = new CustomBossEvents();
+    private final CustomBossEvents customBossEvents;
     private final ServerFunctionManager functionManager;
     private boolean enforceWhitelist;
     private float smoothedTickTimeMillis;
@@ -259,63 +296,207 @@
     protected WorldData worldData;
     public PotionBrewing potionBrewing;
     private volatile boolean isSaving;
-    private static final AtomicReference<RuntimeException> fatalException = new AtomicReference<>();
+    private static final AtomicReference<RuntimeException> fatalException = new AtomicReference();
+
+    // CraftBukkit start
+    public final WorldLoader.DataLoadContext worldLoader;
+    public org.bukkit.craftbukkit.CraftServer server;
+    public OptionSet options;
+    public org.bukkit.command.ConsoleCommandSender console;
+    public static int currentTick; // Paper - improve tick loop
+    public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
+    public int autosavePeriod;
+    // Paper - don't store the vanilla dispatcher
+    public boolean forceTicks; // Paper - Improved watchdog support
+    // CraftBukkit end
+    // Spigot start
+    public static final int TPS = 20;
+    public static final int TICK_TIME = 1000000000 / MinecraftServer.TPS;
+    private static final int SAMPLE_INTERVAL = 20; // Paper - improve server tick loop
+    @Deprecated(forRemoval = true) // Paper
+    public final double[] recentTps = new double[ 3 ];
+    // Spigot end
+    public final io.papermc.paper.configuration.PaperConfigurations paperConfigurations; // Paper - add paper configuration files
+    public static long currentTickLong = 0L; // Paper - track current tick as a long
+    public boolean isIteratingOverLevels = false; // Paper - Throw exception on world create while being ticked
+
+    public volatile Thread shutdownThread; // Paper
+    public volatile boolean abnormalExit = false; // Paper
+    public static final long SERVER_INIT = System.nanoTime(); // Paper - Lag compensation
 
     public static <S extends MinecraftServer> S spin(Function<Thread, S> serverFactory) {
-        AtomicReference<S> atomicReference = new AtomicReference<>();
-        Thread thread = new Thread(() -> atomicReference.get().runServer(), "Server thread");
-        thread.setUncaughtExceptionHandler((threadx, throwable) -> LOGGER.error("Uncaught exception in server thread", throwable));
+        AtomicReference<S> atomicreference = new AtomicReference();
+        Thread thread = new ca.spottedleaf.moonrise.common.util.TickThread(() -> { // Paper - rewrite chunk system
+            ((MinecraftServer) atomicreference.get()).runServer();
+        }, "Server thread");
+
+        thread.setUncaughtExceptionHandler((thread1, throwable) -> {
+            MinecraftServer.LOGGER.error("Uncaught exception in server thread", throwable);
+        });
+        thread.setPriority(Thread.NORM_PRIORITY+2); // Paper - Perf: Boost priority
         if (Runtime.getRuntime().availableProcessors() > 4) {
             thread.setPriority(8);
         }
 
-        S minecraftServer = (S)serverFactory.apply(thread);
-        atomicReference.set(minecraftServer);
+        S s0 = serverFactory.apply(thread); // CraftBukkit - decompile error
+
+        atomicreference.set(s0);
         thread.start();
-        return minecraftServer;
+        return s0;
     }
 
-    public MinecraftServer(
-        Thread serverThread,
-        LevelStorageSource.LevelStorageAccess session,
-        PackRepository dataPackManager,
-        WorldStem saveLoader,
-        Proxy proxy,
-        DataFixer dataFixer,
-        Services apiServices,
-        ChunkProgressListenerFactory worldGenerationProgressListenerFactory
-    ) {
+    // Paper start - rewrite chunk system
+    private volatile Throwable chunkSystemCrash;
+
+    @Override
+    public final void moonrise$setChunkSystemCrash(final Throwable throwable) {
+        this.chunkSystemCrash = throwable;
+    }
+
+    private static final long CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME = 25L * 1000L; // 25us
+    private static final long MAX_CHUNK_EXEC_TIME = 1000L; // 1us
+    private static final long TASK_EXECUTION_FAILURE_BACKOFF = 5L * 1000L; // 5us
+
+    private long lastMidTickExecute;
+    private long lastMidTickExecuteFailure;
+
+    private boolean tickMidTickTasks() {
+        // give all worlds a fair chance at by targeting them all.
+        // if we execute too many tasks, that's fine - we have logic to correctly handle overuse of allocated time.
+        boolean executed = false;
+        for (final ServerLevel world : this.getAllLevels()) {
+            long currTime = System.nanoTime();
+            if (currTime - ((ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemServerLevel)world).moonrise$getLastMidTickFailure() <= TASK_EXECUTION_FAILURE_BACKOFF) {
+                continue;
+            }
+            if (!world.getChunkSource().pollTask()) {
+                // we need to back off if this fails
+                ((ca.spottedleaf.moonrise.patches.chunk_system.level.ChunkSystemServerLevel)world).moonrise$setLastMidTickFailure(currTime);
+            } else {
+                executed = true;
+            }
+        }
+
+        return executed;
+    }
+
+    @Override
+    public final void moonrise$executeMidTickTasks() {
+        final long startTime = System.nanoTime();
+        if ((startTime - this.lastMidTickExecute) <= CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME || (startTime - this.lastMidTickExecuteFailure) <= TASK_EXECUTION_FAILURE_BACKOFF) {
+            // it's shown to be bad to constantly hit the queue (chunk loads slow to a crawl), even if no tasks are executed.
+            // so, backoff to prevent this
+            return;
+        }
+
+        for (;;) {
+            final boolean moreTasks = this.tickMidTickTasks();
+            final long currTime = System.nanoTime();
+            final long diff = currTime - startTime;
+
+            if (!moreTasks || diff >= MAX_CHUNK_EXEC_TIME) {
+                if (!moreTasks) {
+                    this.lastMidTickExecuteFailure = currTime;
+                }
+
+                // note: negative values reduce the time
+                long overuse = diff - MAX_CHUNK_EXEC_TIME;
+                if (overuse >= (10L * 1000L * 1000L)) { // 10ms
+                    // make sure something like a GC or dumb plugin doesn't screw us over...
+                    overuse = 10L * 1000L * 1000L; // 10ms
+                }
+
+                final double overuseCount = (double)overuse/(double)MAX_CHUNK_EXEC_TIME;
+                final long extraSleep = (long)Math.round(overuseCount*CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME);
+
+                this.lastMidTickExecute = currTime + extraSleep;
+                return;
+            }
+        }
+    }
+    // Paper end - rewrite chunk system
+
+    public MinecraftServer(OptionSet options, WorldLoader.DataLoadContext worldLoader, Thread thread, LevelStorageSource.LevelStorageAccess convertable_conversionsession, PackRepository resourcepackrepository, WorldStem worldstem, Proxy proxy, DataFixer datafixer, Services services, ChunkProgressListenerFactory worldloadlistenerfactory) {
         super("Server");
-        this.registries = saveLoader.registries();
-        this.worldData = saveLoader.worldData();
-        if (!this.registries.compositeAccess().registryOrThrow(Registries.LEVEL_STEM).containsKey(LevelStem.OVERWORLD)) {
+        SERVER = this; // Paper - better singleton
+        this.metricsRecorder = InactiveMetricsRecorder.INSTANCE;
+        this.profiler = this.metricsRecorder.getProfiler();
+        this.onMetricsRecordingStopped = (methodprofilerresults) -> {
+            this.stopRecordingMetrics();
+        };
+        this.onMetricsRecordingFinished = (path) -> {
+        };
+        this.random = RandomSource.create();
+        this.port = -1;
+        this.levels = Maps.newLinkedHashMap();
+        this.running = true;
+        this.ticksUntilAutosave = 6000;
+        this.tickTimesNanos = new long[100];
+        this.aggregatedTickTimesNanos = 0L;
+        this.lastTickNanos = Util.getNanos();
+        this.taskExecutionStartNanos = Util.getNanos();
+        this.nextTickTimeNanos = Util.getNanos();
+        this.scoreboard = new ServerScoreboard(this);
+        this.customBossEvents = new CustomBossEvents();
+        this.registries = worldstem.registries();
+        this.worldData = worldstem.worldData();
+        if (false && !this.registries.compositeAccess().registryOrThrow(Registries.LEVEL_STEM).containsKey(LevelStem.OVERWORLD)) { // CraftBukkit - initialised later
             throw new IllegalStateException("Missing Overworld dimension data");
         } else {
             this.proxy = proxy;
-            this.packRepository = dataPackManager;
-            this.resources = new MinecraftServer.ReloadableResources(saveLoader.resourceManager(), saveLoader.dataPackResources());
-            this.services = apiServices;
-            if (apiServices.profileCache() != null) {
-                apiServices.profileCache().setExecutor(this);
+            this.packRepository = resourcepackrepository;
+            this.resources = new MinecraftServer.ReloadableResources(worldstem.resourceManager(), worldstem.dataPackResources());
+            this.services = services;
+            if (services.profileCache() != null) {
+                services.profileCache().setExecutor(this);
             }
 
-            this.connection = new ServerConnectionListener(this);
+            // this.connection = new ServerConnection(this); // Spigot
             this.tickRateManager = new ServerTickRateManager(this);
-            this.progressListenerFactory = worldGenerationProgressListenerFactory;
-            this.storageSource = session;
-            this.playerDataStorage = session.createPlayerStorage();
-            this.fixerUpper = dataFixer;
+            this.progressListenerFactory = worldloadlistenerfactory;
+            this.storageSource = convertable_conversionsession;
+            this.playerDataStorage = convertable_conversionsession.createPlayerStorage();
+            this.fixerUpper = datafixer;
             this.functionManager = new ServerFunctionManager(this, this.resources.managers.getFunctionLibrary());
-            HolderGetter<Block> holderGetter = this.registries
-                .compositeAccess()
-                .registryOrThrow(Registries.BLOCK)
-                .asLookup()
-                .filterFeatures(this.worldData.enabledFeatures());
-            this.structureTemplateManager = new StructureTemplateManager(saveLoader.resourceManager(), session, dataFixer, holderGetter);
-            this.serverThread = serverThread;
+            HolderGetter<Block> holdergetter = this.registries.compositeAccess().registryOrThrow(Registries.BLOCK).asLookup().filterFeatures(this.worldData.enabledFeatures());
+
+            this.structureTemplateManager = new StructureTemplateManager(worldstem.resourceManager(), convertable_conversionsession, datafixer, holdergetter);
+            this.serverThread = thread;
             this.executor = Util.backgroundExecutor();
             this.potionBrewing = PotionBrewing.bootstrap(this.worldData.enabledFeatures());
         }
+        // CraftBukkit start
+        this.options = options;
+        this.worldLoader = worldLoader;
+        // Paper start - Handled by TerminalConsoleAppender
+        // Try to see if we're actually running in a terminal, disable jline if not
+        /*
+        if (System.console() == null && System.getProperty("jline.terminal") == null) {
+            System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+            Main.useJline = false;
+        }
+
+        try {
+            this.reader = new ConsoleReader(System.in, System.out);
+            this.reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
+        } catch (Throwable e) {
+            try {
+                // Try again with jline disabled for Windows users without C++ 2008 Redistributable
+                System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
+                System.setProperty("user.language", "en");
+                Main.useJline = false;
+                this.reader = new ConsoleReader(System.in, System.out);
+                this.reader.setExpandEvents(false);
+            } catch (IOException ex) {
+                MinecraftServer.LOGGER.warn((String) null, ex);
+            }
+        }
+        */
+        // Paper end
+        io.papermc.paper.util.LogManagerShutdownThread.unhook(); // Paper
+        Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
+        // CraftBukkit end
+        this.paperConfigurations = services.paperConfigurations(); // Paper - add paper configuration files
     }
 
     private void readScoreboard(DimensionDataStorage persistentStateManager) {
@@ -324,201 +505,432 @@
 
     protected abstract boolean initServer() throws IOException;
 
-    protected void loadLevel() {
+    protected void loadLevel(String s) { // CraftBukkit
         if (!JvmProfiler.INSTANCE.isRunning()) {
+            ;
         }
 
-        boolean bl = false;
-        ProfiledDuration profiledDuration = JvmProfiler.INSTANCE.onWorldLoadedStarted();
-        this.worldData.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
-        ChunkProgressListener chunkProgressListener = this.progressListenerFactory
-            .create(this.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
-        this.createLevels(chunkProgressListener);
-        this.forceDifficulty();
-        this.prepareLevels(chunkProgressListener);
-        if (profiledDuration != null) {
-            profiledDuration.finish();
+        boolean flag = false;
+        ProfiledDuration profiledduration = JvmProfiler.INSTANCE.onWorldLoadedStarted();
+
+        this.loadWorld0(s); // CraftBukkit
+
+        if (profiledduration != null) {
+            profiledduration.finish();
         }
 
-        if (bl) {
+        if (flag) {
             try {
                 JvmProfiler.INSTANCE.stop();
-            } catch (Throwable var5) {
-                LOGGER.warn("Failed to stop JFR profiling", var5);
+            } catch (Throwable throwable) {
+                MinecraftServer.LOGGER.warn("Failed to stop JFR profiling", throwable);
             }
         }
-    }
 
-    protected void forceDifficulty() {
     }
 
-    protected void createLevels(ChunkProgressListener worldGenerationProgressListener) {
-        ServerLevelData serverLevelData = this.worldData.overworldData();
-        boolean bl = this.worldData.isDebugWorld();
-        Registry<LevelStem> registry = this.registries.compositeAccess().registryOrThrow(Registries.LEVEL_STEM);
-        WorldOptions worldOptions = this.worldData.worldGenOptions();
-        long l = worldOptions.seed();
-        long m = BiomeManager.obfuscateSeed(l);
-        List<CustomSpawner> list = ImmutableList.of(
-            new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(serverLevelData)
-        );
-        LevelStem levelStem = registry.get(LevelStem.OVERWORLD);
-        ServerLevel serverLevel = new ServerLevel(
-            this, this.executor, this.storageSource, serverLevelData, Level.OVERWORLD, levelStem, worldGenerationProgressListener, bl, m, list, true, null
-        );
-        this.levels.put(Level.OVERWORLD, serverLevel);
-        DimensionDataStorage dimensionDataStorage = serverLevel.getDataStorage();
-        this.readScoreboard(dimensionDataStorage);
-        this.commandStorage = new CommandStorage(dimensionDataStorage);
-        WorldBorder worldBorder = serverLevel.getWorldBorder();
-        if (!serverLevelData.isInitialized()) {
-            try {
-                setInitialSpawn(serverLevel, serverLevelData, worldOptions.generateBonusChest(), bl);
-                serverLevelData.setInitialized(true);
-                if (bl) {
-                    this.setupDebugLevel(this.worldData);
+    protected void forceDifficulty() {}
+
+    // CraftBukkit start
+    private void loadWorld0(String s) {
+        LevelStorageSource.LevelStorageAccess worldSession = this.storageSource;
+
+        RegistryAccess.Frozen iregistrycustom_dimension = this.registries.compositeAccess();
+        Registry<LevelStem> dimensions = iregistrycustom_dimension.registryOrThrow(Registries.LEVEL_STEM);
+        for (LevelStem worldDimension : dimensions) {
+            ResourceKey<LevelStem> dimensionKey = dimensions.getResourceKey(worldDimension).get();
+
+            ServerLevel world;
+            int dimension = 0;
+
+            if (dimensionKey == LevelStem.NETHER) {
+                if (this.server.getAllowNether()) {
+                    dimension = -1;
+                } else {
+                    continue;
+                }
+            } else if (dimensionKey == LevelStem.END) {
+                if (this.server.getAllowEnd()) {
+                    dimension = 1;
+                } else {
+                    continue;
+                }
+            } else if (dimensionKey != LevelStem.OVERWORLD) {
+                dimension = -999;
+            }
+
+            String worldType = (dimension == -999) ? dimensionKey.location().getNamespace() + "_" + dimensionKey.location().getPath() : org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase(Locale.ROOT);
+            String name = (dimensionKey == LevelStem.OVERWORLD) ? s : s + "_" + worldType;
+            if (dimension != 0) {
+                File newWorld = LevelStorageSource.getStorageFolder(new File(name).toPath(), dimensionKey).toFile();
+                File oldWorld = LevelStorageSource.getStorageFolder(new File(s).toPath(), dimensionKey).toFile();
+                File oldLevelDat = new File(new File(s), "level.dat"); // The data folders exist on first run as they are created in the PersistentCollection constructor above, but the level.dat won't
+
+                if (!newWorld.isDirectory() && oldWorld.isDirectory() && oldLevelDat.isFile()) {
+                    MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----");
+                    MinecraftServer.LOGGER.info("Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + worldType + " folder to a new location in order to operate correctly.");
+                    MinecraftServer.LOGGER.info("We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
+                    MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
+
+                    if (newWorld.exists()) {
+                        MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    } else if (newWorld.getParentFile().mkdirs()) {
+                        if (oldWorld.renameTo(newWorld)) {
+                            MinecraftServer.LOGGER.info("Success! To restore " + worldType + " in the future, simply move " + newWorld + " to " + oldWorld);
+                            // Migrate world data too.
+                            try {
+                                com.google.common.io.Files.copy(oldLevelDat, new File(new File(name), "level.dat"));
+                                org.apache.commons.io.FileUtils.copyDirectory(new File(new File(s), "data"), new File(new File(name), "data"));
+                            } catch (IOException exception) {
+                                MinecraftServer.LOGGER.warn("Unable to migrate world data.");
+                            }
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----");
+                        } else {
+                            MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
+                            MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                        }
+                    } else {
+                        MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!");
+                        MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
+                    }
                 }
-            } catch (Throwable var23) {
-                CrashReport crashReport = CrashReport.forThrowable(var23, "Exception initializing level");
 
                 try {
-                    serverLevel.fillReportDetails(crashReport);
-                } catch (Throwable var22) {
+                    worldSession = LevelStorageSource.createDefault(this.server.getWorldContainer().toPath()).validateAndCreateAccess(name, dimensionKey);
+                } catch (IOException | ContentValidationException ex) {
+                    throw new RuntimeException(ex);
                 }
+            }
 
-                throw new ReportedException(crashReport);
+            Dynamic<?> dynamic;
+            if (worldSession.hasWorldData()) {
+                LevelSummary worldinfo;
+
+                try {
+                    dynamic = worldSession.getDataTag();
+                    worldinfo = worldSession.getSummary(dynamic);
+                } catch (NbtException | ReportedNbtException | IOException ioexception) {
+                    LevelStorageSource.LevelDirectory convertable_b = worldSession.getLevelDirectory();
+
+                    MinecraftServer.LOGGER.warn("Failed to load world data from {}", convertable_b.dataFile(), ioexception);
+                    MinecraftServer.LOGGER.info("Attempting to use fallback");
+
+                    try {
+                        dynamic = worldSession.getDataTagFallback();
+                        worldinfo = worldSession.getSummary(dynamic);
+                    } catch (NbtException | ReportedNbtException | IOException ioexception1) {
+                        MinecraftServer.LOGGER.error("Failed to load world data from {}", convertable_b.oldDataFile(), ioexception1);
+                        MinecraftServer.LOGGER.error("Failed to load world data from {} and {}. World files may be corrupted. Shutting down.", convertable_b.dataFile(), convertable_b.oldDataFile());
+                        return;
+                    }
+
+                    worldSession.restoreLevelDataFromOld();
+                }
+
+                if (worldinfo.requiresManualConversion()) {
+                    MinecraftServer.LOGGER.info("This world must be opened in an older version (like 1.6.4) to be safely converted");
+                    return;
+                }
+
+                if (!worldinfo.isCompatible()) {
+                    MinecraftServer.LOGGER.info("This world was created by an incompatible version.");
+                    return;
+                }
+            } else {
+                dynamic = null;
             }
 
-            serverLevelData.setInitialized(true);
+            org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
+            org.bukkit.generator.BiomeProvider biomeProvider = this.server.getBiomeProvider(name);
+
+            PrimaryLevelData worlddata;
+            WorldLoader.DataLoadContext worldloader_a = this.worldLoader;
+            Registry<LevelStem> iregistry = worldloader_a.datapackDimensions().registryOrThrow(Registries.LEVEL_STEM);
+            if (dynamic != null) {
+                LevelDataAndDimensions leveldataanddimensions = LevelStorageSource.getLevelDataAndDimensions(dynamic, worldloader_a.dataConfiguration(), iregistry, worldloader_a.datapackWorldgen());
+
+                worlddata = (PrimaryLevelData) leveldataanddimensions.worldData();
+            } else {
+                LevelSettings worldsettings;
+                WorldOptions worldoptions;
+                WorldDimensions worlddimensions;
+
+                if (this.isDemo()) {
+                    worldsettings = MinecraftServer.DEMO_SETTINGS;
+                    worldoptions = WorldOptions.DEMO_OPTIONS;
+                    worlddimensions = WorldPresets.createNormalWorldDimensions(worldloader_a.datapackWorldgen());
+                } else {
+                    DedicatedServerProperties dedicatedserverproperties = ((DedicatedServer) this).getProperties();
+
+                    worldsettings = new LevelSettings(dedicatedserverproperties.levelName, dedicatedserverproperties.gamemode, dedicatedserverproperties.hardcore, dedicatedserverproperties.difficulty, false, new GameRules(), worldloader_a.dataConfiguration());
+                    worldoptions = this.options.has("bonusChest") ? dedicatedserverproperties.worldOptions.withBonusChest(true) : dedicatedserverproperties.worldOptions;
+                    worlddimensions = dedicatedserverproperties.createDimensions(worldloader_a.datapackWorldgen());
+                }
+
+                WorldDimensions.Complete worlddimensions_b = worlddimensions.bake(iregistry);
+                Lifecycle lifecycle = worlddimensions_b.lifecycle().add(worldloader_a.datapackWorldgen().allRegistriesLifecycle());
+
+                worlddata = new PrimaryLevelData(worldsettings, worldoptions, worlddimensions_b.specialWorldProperty(), lifecycle);
+            }
+            worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
+            if (this.options.has("forceUpgrade")) {
+                net.minecraft.server.Main.forceUpgrade(worldSession, DataFixers.getDataFixer(), this.options.has("eraseCache"), () -> {
+                    return true;
+                }, iregistrycustom_dimension, this.options.has("recreateRegionFiles"));
+            }
+
+            PrimaryLevelData iworlddataserver = worlddata;
+            boolean flag = worlddata.isDebugWorld();
+            WorldOptions worldoptions = worlddata.worldGenOptions();
+            long i = worldoptions.seed();
+            long j = BiomeManager.obfuscateSeed(i);
+            List<CustomSpawner> list = ImmutableList.of(new PhantomSpawner(), new PatrolSpawner(), new CatSpawner(), new VillageSiege(), new WanderingTraderSpawner(iworlddataserver));
+            LevelStem worlddimension = (LevelStem) dimensions.get(dimensionKey);
+
+            org.bukkit.generator.WorldInfo worldInfo = new org.bukkit.craftbukkit.generator.CraftWorldInfo(iworlddataserver, worldSession, org.bukkit.World.Environment.getEnvironment(dimension), worlddimension.type().value(), worlddimension.generator(), this.registryAccess()); // Paper - Expose vanilla BiomeProvider from WorldInfo
+            if (biomeProvider == null && gen != null) {
+                biomeProvider = gen.getDefaultBiomeProvider(worldInfo);
+            }
+
+            ResourceKey<Level> worldKey = ResourceKey.create(Registries.DIMENSION, dimensionKey.location());
+
+            if (dimensionKey == LevelStem.OVERWORLD) {
+                this.worldData = worlddata;
+                this.worldData.setGameType(((DedicatedServer) this).getProperties().gamemode); // From DedicatedServer.init
+
+                ChunkProgressListener worldloadlistener = this.progressListenerFactory.create(this.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
+
+                world = new ServerLevel(this, this.executor, worldSession, iworlddataserver, worldKey, worlddimension, worldloadlistener, flag, j, list, true, (RandomSequences) null, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+                DimensionDataStorage worldpersistentdata = world.getDataStorage();
+                this.readScoreboard(worldpersistentdata);
+                this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
+                this.commandStorage = new CommandStorage(worldpersistentdata);
+            } else {
+                ChunkProgressListener worldloadlistener = this.progressListenerFactory.create(this.worldData.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS));
+                // Paper start - option to use the dimension_type to check if spawners should be added. I imagine mojang will add some datapack-y way of managing this in the future.
+                final List<CustomSpawner> spawners;
+                if (io.papermc.paper.configuration.GlobalConfiguration.get().misc.useDimensionTypeForCustomSpawners && this.registryAccess().registryOrThrow(Registries.DIMENSION_TYPE).getResourceKey(worlddimension.type().value()).orElseThrow() == net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD) {
+                    spawners = list;
+                } else {
+                    spawners = Collections.emptyList();
+                }
+                world = new ServerLevel(this, this.executor, worldSession, iworlddataserver, worldKey, worlddimension, worldloadlistener, flag, j, spawners, true, this.overworld().getRandomSequences(), org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+                // Paper end - option to use the dimension_type to check if spawners should be added
+            }
+
+            worlddata.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
+            this.addLevel(world); // Paper - Put world into worldlist before initing the world; move up
+            this.initWorld(world, worlddata, this.worldData, worldoptions);
+
+            // Paper - Put world into worldlist before initing the world; move up
+            this.getPlayerList().addWorldborderListener(world);
+
+            if (worlddata.getCustomBossEvents() != null) {
+                this.getCustomBossEvents().load(worlddata.getCustomBossEvents(), this.registryAccess());
+            }
+        }
+        this.forceDifficulty();
+        for (ServerLevel worldserver : this.getAllLevels()) {
+            this.prepareLevels(worldserver.getChunkSource().chunkMap.progressListener, worldserver);
+            // Paper - rewrite chunk system
+            this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(worldserver.getWorld()));
         }
 
-        this.getPlayerList().addWorldborderListener(serverLevel);
-        if (this.worldData.getCustomBossEvents() != null) {
-            this.getCustomBossEvents().load(this.worldData.getCustomBossEvents(), this.registryAccess());
+        // Paper start - Configurable player collision; Handle collideRule team for player collision toggle
+        final ServerScoreboard scoreboard = this.getScoreboard();
+        final java.util.Collection<String> toRemove = scoreboard.getPlayerTeams().stream().filter(team -> team.getName().startsWith("collideRule_")).map(net.minecraft.world.scores.PlayerTeam::getName).collect(java.util.stream.Collectors.toList());
+        for (String teamName : toRemove) {
+            scoreboard.removePlayerTeam(scoreboard.getPlayerTeam(teamName)); // Clean up after ourselves
         }
 
-        RandomSequences randomSequences = serverLevel.getRandomSequences();
+        if (!io.papermc.paper.configuration.GlobalConfiguration.get().collisions.enablePlayerCollisions) {
+            this.getPlayerList().collideRuleTeamName = org.apache.commons.lang3.StringUtils.left("collideRule_" + java.util.concurrent.ThreadLocalRandom.current().nextInt(), 16);
+            net.minecraft.world.scores.PlayerTeam collideTeam = scoreboard.addPlayerTeam(this.getPlayerList().collideRuleTeamName);
+            collideTeam.setSeeFriendlyInvisibles(false); // Because we want to mimic them not being on a team at all
+        }
+        // Paper end - Configurable player collision
 
-        for (Entry<ResourceKey<LevelStem>, LevelStem> entry : registry.entrySet()) {
-            ResourceKey<LevelStem> resourceKey = entry.getKey();
-            if (resourceKey != LevelStem.OVERWORLD) {
-                ResourceKey<Level> resourceKey2 = ResourceKey.create(Registries.DIMENSION, resourceKey.location());
-                DerivedLevelData derivedLevelData = new DerivedLevelData(this.worldData, serverLevelData);
-                ServerLevel serverLevel2 = new ServerLevel(
-                    this,
-                    this.executor,
-                    this.storageSource,
-                    derivedLevelData,
-                    resourceKey2,
-                    entry.getValue(),
-                    worldGenerationProgressListener,
-                    bl,
-                    m,
-                    ImmutableList.of(),
-                    false,
-                    randomSequences
-                );
-                worldBorder.addListener(new BorderChangeListener.DelegateBorderChangeListener(serverLevel2.getWorldBorder()));
-                this.levels.put(resourceKey2, serverLevel2);
+        this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
+        this.server.spark.registerCommandBeforePlugins(this.server); // Paper - spark
+        this.server.spark.enableAfterPlugins(this.server); // Paper - spark
+        if (io.papermc.paper.plugin.PluginInitializerManager.instance().pluginRemapper != null) io.papermc.paper.plugin.PluginInitializerManager.instance().pluginRemapper.pluginsEnabled(); // Paper - Remap plugins
+        io.papermc.paper.command.brigadier.PaperCommands.INSTANCE.setValid(); // Paper - reset invalid state for event fire below
+        io.papermc.paper.plugin.lifecycle.event.LifecycleEventRunner.INSTANCE.callReloadableRegistrarEvent(io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents.COMMANDS, io.papermc.paper.command.brigadier.PaperCommands.INSTANCE, org.bukkit.plugin.Plugin.class, io.papermc.paper.plugin.lifecycle.event.registrar.ReloadableRegistrarEvent.Cause.INITIAL); // Paper - call commands event for regular plugins
+        ((org.bukkit.craftbukkit.help.SimpleHelpMap) this.server.getHelpMap()).initializeCommands();
+        this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP));
+        this.connection.acceptConnections();
+    }
+
+    public void initWorld(ServerLevel worldserver, ServerLevelData iworlddataserver, WorldData saveData, WorldOptions worldoptions) {
+        boolean flag = saveData.isDebugWorld();
+        // CraftBukkit start
+        if (worldserver.generator != null) {
+            worldserver.getWorld().getPopulators().addAll(worldserver.generator.getDefaultPopulators(worldserver.getWorld()));
+        }
+        WorldBorder worldborder = worldserver.getWorldBorder();
+        worldborder.applySettings(iworlddataserver.getWorldBorder()); // CraftBukkit - move up so that WorldBorder is set during WorldInitEvent
+        this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(worldserver.getWorld())); // CraftBukkit - SPIGOT-5569: Call WorldInitEvent before any chunks are generated
+
+        if (!iworlddataserver.isInitialized()) {
+            try {
+                MinecraftServer.setInitialSpawn(worldserver, iworlddataserver, worldoptions.generateBonusChest(), flag);
+                iworlddataserver.setInitialized(true);
+                if (flag) {
+                    this.setupDebugLevel(this.worldData);
+                }
+            } catch (Throwable throwable) {
+                CrashReport crashreport = CrashReport.forThrowable(throwable, "Exception initializing level");
+
+                try {
+                    worldserver.fillReportDetails(crashreport);
+                } catch (Throwable throwable1) {
+                    ;
+                }
+
+                throw new ReportedException(crashreport);
             }
+
+            iworlddataserver.setInitialized(true);
         }
 
-        worldBorder.applySettings(serverLevelData.getWorldBorder());
     }
+    // CraftBukkit end
 
     private static void setInitialSpawn(ServerLevel world, ServerLevelData worldProperties, boolean bonusChest, boolean debugWorld) {
         if (debugWorld) {
             worldProperties.setSpawn(BlockPos.ZERO.above(80), 0.0F);
         } else {
-            ServerChunkCache serverChunkCache = world.getChunkSource();
-            ChunkPos chunkPos = new ChunkPos(serverChunkCache.randomState().sampler().findSpawnPosition());
-            int i = serverChunkCache.getGenerator().getSpawnHeight(world);
+            ServerChunkCache chunkproviderserver = world.getChunkSource();
+            ChunkPos chunkcoordintpair = new ChunkPos(chunkproviderserver.randomState().sampler().findSpawnPosition());
+            // CraftBukkit start
+            if (world.generator != null) {
+                Random rand = new Random(world.getSeed());
+                org.bukkit.Location spawn = world.generator.getFixedSpawnLocation(world.getWorld(), rand);
+
+                if (spawn != null) {
+                    if (spawn.getWorld() != world.getWorld()) {
+                        throw new IllegalStateException("Cannot set spawn point for " + worldProperties.getLevelName() + " to be in another world (" + spawn.getWorld().getName() + ")");
+                    } else {
+                        worldProperties.setSpawn(new BlockPos(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ()), spawn.getYaw());
+                        return;
+                    }
+                }
+            }
+            // CraftBukkit end
+            int i = chunkproviderserver.getGenerator().getSpawnHeight(world);
+
             if (i < world.getMinBuildHeight()) {
-                BlockPos blockPos = chunkPos.getWorldPosition();
-                i = world.getHeight(Heightmap.Types.WORLD_SURFACE, blockPos.getX() + 8, blockPos.getZ() + 8);
+                BlockPos blockposition = chunkcoordintpair.getWorldPosition();
+
+                i = world.getHeight(Heightmap.Types.WORLD_SURFACE, blockposition.getX() + 8, blockposition.getZ() + 8);
             }
 
-            worldProperties.setSpawn(chunkPos.getWorldPosition().offset(8, i, 8), 0.0F);
+            worldProperties.setSpawn(chunkcoordintpair.getWorldPosition().offset(8, i, 8), 0.0F);
             int j = 0;
             int k = 0;
             int l = 0;
-            int m = -1;
+            int i1 = -1;
 
-            for (int n = 0; n < Mth.square(11); n++) {
+            for (int j1 = 0; j1 < Mth.square(11); ++j1) {
                 if (j >= -5 && j <= 5 && k >= -5 && k <= 5) {
-                    BlockPos blockPos2 = PlayerRespawnLogic.getSpawnPosInChunk(world, new ChunkPos(chunkPos.x + j, chunkPos.z + k));
-                    if (blockPos2 != null) {
-                        worldProperties.setSpawn(blockPos2, 0.0F);
+                    BlockPos blockposition1 = PlayerRespawnLogic.getSpawnPosInChunk(world, new ChunkPos(chunkcoordintpair.x + j, chunkcoordintpair.z + k));
+
+                    if (blockposition1 != null) {
+                        worldProperties.setSpawn(blockposition1, 0.0F);
                         break;
                     }
                 }
 
                 if (j == k || j < 0 && j == -k || j > 0 && j == 1 - k) {
-                    int o = l;
-                    l = -m;
-                    m = o;
+                    int k1 = l;
+
+                    l = -i1;
+                    i1 = k1;
                 }
 
                 j += l;
-                k += m;
+                k += i1;
             }
 
             if (bonusChest) {
-                world.registryAccess()
-                    .registry(Registries.CONFIGURED_FEATURE)
-                    .flatMap(featureRegistry -> featureRegistry.getHolder(MiscOverworldFeatures.BONUS_CHEST))
-                    .ifPresent(feature -> feature.value().place(world, serverChunkCache.getGenerator(), world.random, worldProperties.getSpawnPos()));
+                world.registryAccess().registry(Registries.CONFIGURED_FEATURE).flatMap((iregistry) -> {
+                    return iregistry.getHolder(MiscOverworldFeatures.BONUS_CHEST);
+                }).ifPresent((holder_c) -> {
+                    ((ConfiguredFeature) holder_c.value()).place(world, chunkproviderserver.getGenerator(), world.random, worldProperties.getSpawnPos());
+                });
             }
+
         }
     }
 
     private void setupDebugLevel(WorldData properties) {
         properties.setDifficulty(Difficulty.PEACEFUL);
         properties.setDifficultyLocked(true);
-        ServerLevelData serverLevelData = properties.overworldData();
-        serverLevelData.setRaining(false);
-        serverLevelData.setThundering(false);
-        serverLevelData.setClearWeatherTime(1000000000);
-        serverLevelData.setDayTime(6000L);
-        serverLevelData.setGameType(GameType.SPECTATOR);
+        ServerLevelData iworlddataserver = properties.overworldData();
+
+        iworlddataserver.setRaining(false);
+        iworlddataserver.setThundering(false);
+        iworlddataserver.setClearWeatherTime(1000000000);
+        iworlddataserver.setDayTime(6000L);
+        iworlddataserver.setGameType(GameType.SPECTATOR);
     }
 
-    public void prepareLevels(ChunkProgressListener worldGenerationProgressListener) {
-        ServerLevel serverLevel = this.overworld();
-        LOGGER.info("Preparing start region for dimension {}", serverLevel.dimension().location());
-        BlockPos blockPos = serverLevel.getSharedSpawnPos();
-        worldGenerationProgressListener.updateSpawnPos(new ChunkPos(blockPos));
-        ServerChunkCache serverChunkCache = serverLevel.getChunkSource();
+    // CraftBukkit start
+    public void prepareLevels(ChunkProgressListener worldloadlistener, ServerLevel worldserver) {
+        // WorldServer worldserver = this.overworld();
+        this.forceTicks = true;
+        // CraftBukkit end
+
+        MinecraftServer.LOGGER.info("Preparing start region for dimension {}", worldserver.dimension().location());
+        BlockPos blockposition = worldserver.getSharedSpawnPos();
+
+        worldloadlistener.updateSpawnPos(new ChunkPos(blockposition));
+        ServerChunkCache chunkproviderserver = worldserver.getChunkSource();
+
         this.nextTickTimeNanos = Util.getNanos();
-        serverLevel.setDefaultSpawnPos(blockPos, serverLevel.getSharedSpawnAngle());
-        int i = this.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS);
+        worldserver.setDefaultSpawnPos(blockposition, worldserver.getSharedSpawnAngle());
+        int i = worldserver.getGameRules().getInt(GameRules.RULE_SPAWN_CHUNK_RADIUS); // CraftBukkit - per-world
         int j = i > 0 ? Mth.square(ChunkProgressListener.calculateDiameter(i)) : 0;
 
-        while (serverChunkCache.getTickingGenerated() < j) {
-            this.nextTickTimeNanos = Util.getNanos() + PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-            this.waitUntilNextTick();
+        while (chunkproviderserver.getTickingGenerated() < j) {
+            // CraftBukkit start
+            // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+            this.executeModerately();
         }
 
-        this.nextTickTimeNanos = Util.getNanos() + PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-        this.waitUntilNextTick();
+        // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+        this.executeModerately();
+        // Iterator iterator = this.levels.values().iterator();
 
-        for (ServerLevel serverLevel2 : this.levels.values()) {
-            ForcedChunksSavedData forcedChunksSavedData = serverLevel2.getDataStorage().get(ForcedChunksSavedData.factory(), "chunks");
-            if (forcedChunksSavedData != null) {
-                LongIterator longIterator = forcedChunksSavedData.getChunks().iterator();
+        if (true) {
+            ServerLevel worldserver1 = worldserver;
+            // CraftBukkit end
+            ForcedChunksSavedData forcedchunk = (ForcedChunksSavedData) worldserver1.getDataStorage().get(ForcedChunksSavedData.factory(), "chunks");
 
-                while (longIterator.hasNext()) {
-                    long l = longIterator.nextLong();
-                    ChunkPos chunkPos = new ChunkPos(l);
-                    serverLevel2.getChunkSource().updateChunkForced(chunkPos, true);
+            if (forcedchunk != null) {
+                LongIterator longiterator = forcedchunk.getChunks().iterator();
+
+                while (longiterator.hasNext()) {
+                    long k = longiterator.nextLong();
+                    ChunkPos chunkcoordintpair = new ChunkPos(k);
+
+                    worldserver1.getChunkSource().updateChunkForced(chunkcoordintpair, true);
                 }
             }
         }
 
-        this.nextTickTimeNanos = Util.getNanos() + PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
-        this.waitUntilNextTick();
-        worldGenerationProgressListener.stop();
-        this.updateMobSpawningFlags();
+        // CraftBukkit start
+        // this.nextTickTimeNanos = SystemUtils.getNanos() + MinecraftServer.PREPARE_LEVELS_DEFAULT_DELAY_NANOS;
+        this.executeModerately();
+        // CraftBukkit end
+        worldloadlistener.stop();
+        // CraftBukkit start
+        // this.updateMobSpawningFlags();
+        worldserver.setSpawnSettings(worldserver.serverLevelData.getDifficulty() != Difficulty.PEACEFUL && ((DedicatedServer) this).settings.getProperties().spawnMonsters, this.isSpawningAnimals()); // Paper - per level difficulty (from setDifficulty(ServerLevel, Difficulty, boolean))
+
+        this.forceTicks = false;
+        // CraftBukkit end
     }
 
     public GameType getDefaultGameType() {
@@ -536,44 +948,60 @@
     public abstract boolean shouldRconBroadcast();
 
     public boolean saveAllChunks(boolean suppressLogs, boolean flush, boolean force) {
-        boolean bl = false;
+        // Paper start - add close param
+        return this.saveAllChunks(suppressLogs, flush, force, false);
+    }
+    public boolean saveAllChunks(boolean suppressLogs, boolean flush, boolean force, boolean close) {
+        // Paper end - add close param
+        boolean flag3 = false;
+
+        for (Iterator iterator = this.getAllLevels().iterator(); iterator.hasNext(); flag3 = true) {
+            ServerLevel worldserver = (ServerLevel) iterator.next();
 
-        for (ServerLevel serverLevel : this.getAllLevels()) {
             if (!suppressLogs) {
-                LOGGER.info("Saving chunks for level '{}'/{}", serverLevel, serverLevel.dimension().location());
+                MinecraftServer.LOGGER.info("Saving chunks for level '{}'/{}", worldserver, worldserver.dimension().location());
             }
 
-            serverLevel.save(null, flush, serverLevel.noSave && !force);
-            bl = true;
+            worldserver.save((ProgressListener) null, flush, worldserver.noSave && !force, close); // Paper - add close param
         }
 
-        ServerLevel serverLevel2 = this.overworld();
-        ServerLevelData serverLevelData = this.worldData.overworldData();
-        serverLevelData.setWorldBorder(serverLevel2.getWorldBorder().createSettings());
+        // CraftBukkit start - moved to WorldServer.save
+        /*
+        WorldServer worldserver1 = this.overworld();
+        IWorldDataServer iworlddataserver = this.worldData.overworldData();
+
+        iworlddataserver.setWorldBorder(worldserver1.getWorldBorder().createSettings());
         this.worldData.setCustomBossEvents(this.getCustomBossEvents().save(this.registryAccess()));
         this.storageSource.saveDataTag(this.registryAccess(), this.worldData, this.getPlayerList().getSingleplayerData());
+        */
+        // CraftBukkit end
         if (flush) {
-            for (ServerLevel serverLevel3 : this.getAllLevels()) {
-                LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", serverLevel3.getChunkSource().chunkMap.getStorageName());
+            Iterator iterator1 = this.getAllLevels().iterator();
+
+            while (iterator1.hasNext()) {
+                ServerLevel worldserver2 = (ServerLevel) iterator1.next();
+
+                MinecraftServer.LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", worldserver2.getChunkSource().chunkMap.getStorageName());
             }
 
-            LOGGER.info("ThreadedAnvilChunkStorage: All dimensions are saved");
+            MinecraftServer.LOGGER.info("ThreadedAnvilChunkStorage: All dimensions are saved");
         }
 
-        return bl;
+        return flag3;
     }
 
     public boolean saveEverything(boolean suppressLogs, boolean flush, boolean force) {
-        boolean var4;
+        boolean flag3;
+
         try {
             this.isSaving = true;
-            this.getPlayerList().saveAll();
-            var4 = this.saveAllChunks(suppressLogs, flush, force);
+            this.getPlayerList().saveAll(); // Paper - Incremental chunk and player saving; diff on change
+            flag3 = this.saveAllChunks(suppressLogs, flush, force);
         } finally {
             this.isSaving = false;
         }
 
-        return var4;
+        return flag3;
     }
 
     @Override
@@ -581,59 +1009,114 @@
         this.stopServer();
     }
 
+    // CraftBukkit start
+    private boolean hasStopped = false;
+    private boolean hasLoggedStop = false; // Paper - Debugging
+    public volatile boolean hasFullyShutdown = false; // Paper
+    private final Object stopLock = new Object();
+    public final boolean hasStopped() {
+        synchronized (this.stopLock) {
+            return this.hasStopped;
+        }
+    }
+    // CraftBukkit end
+
     public void stopServer() {
+        // CraftBukkit start - prevent double stopping on multiple threads
+        synchronized(this.stopLock) {
+            if (this.hasStopped) return;
+            this.hasStopped = true;
+        }
+        if (!hasLoggedStop && isDebugging()) io.papermc.paper.util.TraceUtil.dumpTraceForThread("Server stopped"); // Paper - Debugging
+        // Paper start - kill main thread, and kill it hard
+        shutdownThread = Thread.currentThread();
+        org.spigotmc.WatchdogThread.doStop(); // Paper
+        // Paper end
+        // CraftBukkit end
         if (this.metricsRecorder.isRecording()) {
             this.cancelRecordingMetrics();
         }
 
-        LOGGER.info("Stopping server");
+        MinecraftServer.LOGGER.info("Stopping server");
+        Commands.COMMAND_SENDING_POOL.shutdownNow(); // Paper - Perf: Async command map building; Shutdown and don't bother finishing
+        MinecraftTimings.stopServer(); // Paper
+        this.server.spark.disable(); // Paper - spark
+        // CraftBukkit start
+        if (this.server != null) {
+            this.server.disablePlugins();
+            this.server.waitForAsyncTasksShutdown(); // Paper - Wait for Async Tasks during shutdown
+        }
+        // CraftBukkit end
+        if (io.papermc.paper.plugin.PluginInitializerManager.instance().pluginRemapper != null) io.papermc.paper.plugin.PluginInitializerManager.instance().pluginRemapper.shutdown(); // Paper - Plugin remapping
         this.getConnection().stop();
         this.isSaving = true;
         if (this.playerList != null) {
-            LOGGER.info("Saving players");
+            MinecraftServer.LOGGER.info("Saving players");
             this.playerList.saveAll();
-            this.playerList.removeAll();
+            this.playerList.removeAll(this.isRestarting); // Paper
+            try { Thread.sleep(100); } catch (InterruptedException ex) {} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets
         }
 
-        LOGGER.info("Saving worlds");
+        MinecraftServer.LOGGER.info("Saving worlds");
+        Iterator iterator = this.getAllLevels().iterator();
 
-        for (ServerLevel serverLevel : this.getAllLevels()) {
-            if (serverLevel != null) {
-                serverLevel.noSave = false;
+        ServerLevel worldserver;
+
+        while (iterator.hasNext()) {
+            worldserver = (ServerLevel) iterator.next();
+            if (worldserver != null) {
+                worldserver.noSave = false;
             }
         }
 
-        while (this.levels.values().stream().anyMatch(world -> world.getChunkSource().chunkMap.hasWork())) {
+        while (false && this.levels.values().stream().anyMatch((worldserver1) -> { // Paper - rewrite chunk system
+            return worldserver1.getChunkSource().chunkMap.hasWork();
+        })) {
             this.nextTickTimeNanos = Util.getNanos() + TimeUtil.NANOSECONDS_PER_MILLISECOND;
+            iterator = this.getAllLevels().iterator();
 
-            for (ServerLevel serverLevel2 : this.getAllLevels()) {
-                serverLevel2.getChunkSource().removeTicketsOnClosing();
-                serverLevel2.getChunkSource().tick(() -> true, false);
+            while (iterator.hasNext()) {
+                worldserver = (ServerLevel) iterator.next();
+                worldserver.getChunkSource().removeTicketsOnClosing();
+                worldserver.getChunkSource().tick(() -> {
+                    return true;
+                }, false);
             }
 
             this.waitUntilNextTick();
         }
 
-        this.saveAllChunks(false, true, false);
-
-        for (ServerLevel serverLevel3 : this.getAllLevels()) {
-            if (serverLevel3 != null) {
-                try {
-                    serverLevel3.close();
-                } catch (IOException var5) {
-                    LOGGER.error("Exception closing the level", (Throwable)var5);
-                }
-            }
-        }
+        this.saveAllChunks(false, true, true, true); // Paper - rewrite chunk system
 
         this.isSaving = false;
         this.resources.close();
 
         try {
             this.storageSource.close();
-        } catch (IOException var4) {
-            LOGGER.error("Failed to unlock level {}", this.storageSource.getLevelId(), var4);
+        } catch (IOException ioexception1) {
+            MinecraftServer.LOGGER.error("Failed to unlock level {}", this.storageSource.getLevelId(), ioexception1);
         }
+        // Spigot start
+        io.papermc.paper.util.MCUtil.asyncExecutor.shutdown(); // Paper
+        try { io.papermc.paper.util.MCUtil.asyncExecutor.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS); // Paper
+        } catch (java.lang.InterruptedException ignored) {} // Paper
+        if (org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) {
+            MinecraftServer.LOGGER.info("Saving usercache.json");
+            this.getProfileCache().save(false); // Paper - Perf: Async GameProfileCache saving
+        }
+        // Spigot end
+
+        // Paper end - Improved watchdog support; move final shutdown items here
+        ca.spottedleaf.moonrise.patches.chunk_system.io.RegionFileIOThread.deinit(); // Paper - rewrite chunk system
+        // Paper start - move final shutdown items here
+        Util.shutdownExecutors();
+        try {
+            net.minecrell.terminalconsole.TerminalConsoleAppender.close(); // Paper - Use TerminalConsoleAppender
+        } catch (final Exception ignored) {
+        }
+        io.papermc.paper.log.CustomLogManager.forceReset(); // Paper - Reset loggers after shutdown
+        this.onServerExit();
+        // Paper end - Improved watchdog support
     }
 
     public String getLocalIp() {
@@ -649,61 +1132,192 @@
     }
 
     public void halt(boolean waitForShutdown) {
+        // Paper start - allow passing of the intent to restart
+        this.safeShutdown(waitForShutdown, false);
+    }
+    public void safeShutdown(boolean waitForShutdown, boolean isRestarting) {
+        this.isRestarting = isRestarting;
+        this.hasLoggedStop = true; // Paper - Debugging
+        if (isDebugging()) io.papermc.paper.util.TraceUtil.dumpTraceForThread("Server stopped"); // Paper - Debugging
+        // Paper end
         this.running = false;
         if (waitForShutdown) {
             try {
                 this.serverThread.join();
-            } catch (InterruptedException var3) {
-                LOGGER.error("Error while shutting down", (Throwable)var3);
+            } catch (InterruptedException interruptedexception) {
+                MinecraftServer.LOGGER.error("Error while shutting down", interruptedexception);
             }
         }
+
     }
 
+    // Spigot Start
+    private static double calcTps(double avg, double exp, double tps)
+    {
+        return ( avg * exp ) + ( tps * ( 1 - exp ) );
+    }
+
+    // Paper start - Further improve server tick loop
+    private static final long SEC_IN_NANO = 1000000000;
+    private static final long MAX_CATCHUP_BUFFER = TICK_TIME * TPS * 60L;
+    private long lastTick = 0;
+    private long catchupTime = 0;
+    public final RollingAverage tps1 = new RollingAverage(60);
+    public final RollingAverage tps5 = new RollingAverage(60 * 5);
+    public final RollingAverage tps15 = new RollingAverage(60 * 15);
+
+    public static class RollingAverage {
+        private final int size;
+        private long time;
+        private java.math.BigDecimal total;
+        private int index = 0;
+        private final java.math.BigDecimal[] samples;
+        private final long[] times;
+
+        RollingAverage(int size) {
+            this.size = size;
+            this.time = size * SEC_IN_NANO;
+            this.total = dec(TPS).multiply(dec(SEC_IN_NANO)).multiply(dec(size));
+            this.samples = new java.math.BigDecimal[size];
+            this.times = new long[size];
+            for (int i = 0; i < size; i++) {
+                this.samples[i] = dec(TPS);
+                this.times[i] = SEC_IN_NANO;
+            }
+        }
+
+        private static java.math.BigDecimal dec(long t) {
+            return new java.math.BigDecimal(t);
+        }
+        public void add(java.math.BigDecimal x, long t) {
+            time -= times[index];
+            total = total.subtract(samples[index].multiply(dec(times[index])));
+            samples[index] = x;
+            times[index] = t;
+            time += t;
+            total = total.add(x.multiply(dec(t)));
+            if (++index == size) {
+                index = 0;
+            }
+        }
+
+        public double getAverage() {
+            return total.divide(dec(time), 30, java.math.RoundingMode.HALF_UP).doubleValue();
+        }
+    }
+    private static final java.math.BigDecimal TPS_BASE = new java.math.BigDecimal(1E9).multiply(new java.math.BigDecimal(SAMPLE_INTERVAL));
+    // Paper end
+    // Spigot End
+
     protected void runServer() {
         try {
+            long serverStartTime = Util.getNanos(); // Paper
             if (!this.initServer()) {
                 throw new IllegalStateException("Failed to initialize server");
             }
 
             this.nextTickTimeNanos = Util.getNanos();
-            this.statusIcon = this.loadStatusIcon().orElse(null);
+            this.statusIcon = (ServerStatus.Favicon) this.loadStatusIcon().orElse(null); // CraftBukkit - decompile error
             this.status = this.buildServerStatus();
 
+            // Spigot start
+            // Paper start - Improved Watchdog Support
+            LOGGER.info("Running delayed init tasks");
+            this.server.getScheduler().mainThreadHeartbeat(this.tickCount); // run all 1 tick delay tasks during init,
+            // this is going to be the first thing the tick process does anyways, so move done and run it after
+            // everything is init before watchdog tick.
+            // anything at 3+ won't be caught here but also will trip watchdog....
+            // tasks are default scheduled at -1 + delay, and first tick will tick at 1
+            final long actualDoneTimeMs = System.currentTimeMillis() - org.bukkit.craftbukkit.Main.BOOT_TIME.toEpochMilli(); // Paper - Add total time
+            LOGGER.info("Done ({})! For help, type \"help\"", String.format(java.util.Locale.ROOT, "%.3fs", actualDoneTimeMs / 1000.00D)); // Paper - Add total time
+            this.server.spark.enableBeforePlugins(); // Paper - spark
+            org.spigotmc.WatchdogThread.tick();
+            // Paper end - Improved Watchdog Support
+            org.spigotmc.WatchdogThread.hasStarted = true; // Paper
+            Arrays.fill( this.recentTps, 20 );
+            // Paper start - further improve server tick loop
+            long tickSection = Util.getNanos();
+            long currentTime;
+            // Paper end - further improve server tick loop
+            // Paper start - Add onboarding message for initial server start
+            if (io.papermc.paper.configuration.GlobalConfiguration.isFirstStart) {
+                LOGGER.info("*************************************************************************************");
+                LOGGER.info("This is the first time you're starting this server.");
+                LOGGER.info("It's recommended you read our 'Getting Started' documentation for guidance.");
+                LOGGER.info("View this and more helpful information here: https://docs.papermc.io/paper/next-steps");
+                LOGGER.info("*************************************************************************************");
+            }
+            // Paper end - Add onboarding message for initial server start
+
             while (this.running) {
-                long l;
+                long i;
+
                 if (!this.isPaused() && this.tickRateManager.isSprinting() && this.tickRateManager.checkShouldSprintThisTick()) {
-                    l = 0L;
+                    i = 0L;
                     this.nextTickTimeNanos = Util.getNanos();
                     this.lastOverloadWarningNanos = this.nextTickTimeNanos;
                 } else {
-                    l = this.tickRateManager.nanosecondsPerTick();
-                    long n = Util.getNanos() - this.nextTickTimeNanos;
-                    if (n > OVERLOADED_THRESHOLD_NANOS + 20L * l
-                        && this.nextTickTimeNanos - this.lastOverloadWarningNanos >= OVERLOADED_WARNING_INTERVAL_NANOS + 100L * l) {
-                        long o = n / l;
-                        LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", n / TimeUtil.NANOSECONDS_PER_MILLISECOND, o);
-                        this.nextTickTimeNanos += o * l;
+                    i = this.tickRateManager.nanosecondsPerTick();
+                    long j = Util.getNanos() - this.nextTickTimeNanos;
+
+                    if (j > MinecraftServer.OVERLOADED_THRESHOLD_NANOS + 20L * i && this.nextTickTimeNanos - this.lastOverloadWarningNanos >= MinecraftServer.OVERLOADED_WARNING_INTERVAL_NANOS + 100L * i) {
+                        long k = j / i;
+
+                        if (this.server.getWarnOnOverload()) // CraftBukkit
+                        MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", j / TimeUtil.NANOSECONDS_PER_MILLISECOND, k);
+                        this.nextTickTimeNanos += k * i;
                         this.lastOverloadWarningNanos = this.nextTickTimeNanos;
                     }
                 }
+                // Spigot start
+                ++MinecraftServer.currentTickLong; // Paper - track current tick as a long
+                // Paper start - further improve server tick loop
+                currentTime = Util.getNanos();
+                if (++MinecraftServer.currentTick % MinecraftServer.SAMPLE_INTERVAL == 0) {
+                    final long diff = currentTime - tickSection;
+                    final java.math.BigDecimal currentTps = TPS_BASE.divide(new java.math.BigDecimal(diff), 30, java.math.RoundingMode.HALF_UP);
+                    tps1.add(currentTps, diff);
+                    tps5.add(currentTps, diff);
+                    tps15.add(currentTps, diff);
+
+                    // Backwards compat with bad plugins
+                    this.recentTps[0] = tps1.getAverage();
+                    this.recentTps[1] = tps5.getAverage();
+                    this.recentTps[2] = tps15.getAverage();
+                    tickSection = currentTime;
+                }
+                // Paper end - further improve server tick loop
+                // Spigot end
+
+                boolean flag = i == 0L;
 
-                boolean bl = l == 0L;
                 if (this.debugCommandProfilerDelayStart) {
                     this.debugCommandProfilerDelayStart = false;
                     this.debugCommandProfiler = new MinecraftServer.TimeProfiler(Util.getNanos(), this.tickCount);
                 }
 
-                this.nextTickTimeNanos += l;
+                //MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit // Paper - don't overwrite current tick time
+                lastTick = currentTime;
+                this.nextTickTimeNanos += i;
                 this.startMetricsRecordingTick();
                 this.profiler.push("tick");
-                this.tickServer(bl ? () -> false : this::haveTime);
+                this.tickServer(flag ? () -> {
+                    return false;
+                } : this::haveTime);
+                // Paper start - rewrite chunk system
+                final Throwable crash = this.chunkSystemCrash;
+                if (crash != null) {
+                    this.chunkSystemCrash = null;
+                    throw new RuntimeException("Chunk system crash propagated to tick()", crash);
+                }
+                // Paper end - rewrite chunk system
                 this.profiler.popPush("nextTickWait");
                 this.mayHaveDelayedTasks = true;
-                this.delayedTasksMaxNextTickTimeNanos = Math.max(Util.getNanos() + l, this.nextTickTimeNanos);
+                this.delayedTasksMaxNextTickTimeNanos = Math.max(Util.getNanos() + i, this.nextTickTimeNanos);
                 this.startMeasuringTaskExecutionTime();
                 this.waitUntilNextTick();
                 this.finishMeasuringTaskExecutionTime();
-                if (bl) {
+                if (flag) {
                     this.tickRateManager.endTickWork();
                 }
 
@@ -713,41 +1327,60 @@
                 this.isReady = true;
                 JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis);
             }
-        } catch (Throwable var46) {
-            LOGGER.error("Encountered an unexpected exception", var46);
-            CrashReport crashReport = constructOrExtractCrashReport(var46);
-            this.fillSystemReport(crashReport.getSystemReport());
+        } catch (Throwable throwable) {
+            // Paper start
+            if (throwable instanceof ThreadDeath) {
+                MinecraftServer.LOGGER.error("Main thread terminated by WatchDog due to hard crash", throwable);
+                return;
+            }
+            // Paper end
+            MinecraftServer.LOGGER.error("Encountered an unexpected exception", throwable);
+            CrashReport crashreport = MinecraftServer.constructOrExtractCrashReport(throwable);
+
+            this.fillSystemReport(crashreport.getSystemReport());
             Path path = this.getServerDirectory().resolve("crash-reports").resolve("crash-" + Util.getFilenameFormattedDateTime() + "-server.txt");
-            if (crashReport.saveToFile(path, ReportType.CRASH)) {
-                LOGGER.error("This crash report has been saved to: {}", path.toAbsolutePath());
+
+            if (crashreport.saveToFile(path, ReportType.CRASH)) {
+                MinecraftServer.LOGGER.error("This crash report has been saved to: {}", path.toAbsolutePath());
             } else {
-                LOGGER.error("We were unable to save this crash report to disk.");
+                MinecraftServer.LOGGER.error("We were unable to save this crash report to disk.");
             }
 
-            this.onServerCrash(crashReport);
+            this.onServerCrash(crashreport);
         } finally {
             try {
                 this.stopped = true;
                 this.stopServer();
-            } catch (Throwable var44) {
-                LOGGER.error("Exception stopping the server", var44);
+            } catch (Throwable throwable1) {
+                MinecraftServer.LOGGER.error("Exception stopping the server", throwable1);
             } finally {
                 if (this.services.profileCache() != null) {
                     this.services.profileCache().clearExecutor();
                 }
 
-                this.onServerExit();
+                //org.spigotmc.WatchdogThread.doStop(); // Spigot // Paper - move into stop
+                // CraftBukkit start - Restore terminal to original settings
+                try {
+                    //net.minecrell.terminalconsole.TerminalConsoleAppender.close(); // Paper - Move into stop
+                } catch (Exception ignored) {
+                }
+                // CraftBukkit end
+                //io.papermc.paper.log.CustomLogManager.forceReset(); // Paper - Reset loggers after shutdown
+                //this.onServerExit(); // Paper - moved into stop
             }
+
         }
+
     }
 
     private void logFullTickTime() {
-        long l = Util.getNanos();
+        long i = Util.getNanos();
+
         if (this.isTickTimeLoggingEnabled()) {
-            this.getTickTimeLogger().logSample(l - this.lastTickNanos);
+            this.getTickTimeLogger().logSample(i - this.lastTickNanos);
         }
 
-        this.lastTickNanos = l;
+        this.lastTickNanos = i;
     }
 
     private void startMeasuringTaskExecutionTime() {
@@ -755,128 +1388,176 @@
             this.taskExecutionStartNanos = Util.getNanos();
             this.idleTimeNanos = 0L;
         }
+
     }
 
     private void finishMeasuringTaskExecutionTime() {
         if (this.isTickTimeLoggingEnabled()) {
-            SampleLogger sampleLogger = this.getTickTimeLogger();
-            sampleLogger.logPartialSample(Util.getNanos() - this.taskExecutionStartNanos - this.idleTimeNanos, TpsDebugDimensions.SCHEDULED_TASKS.ordinal());
-            sampleLogger.logPartialSample(this.idleTimeNanos, TpsDebugDimensions.IDLE.ordinal());
+            SampleLogger samplelogger = this.getTickTimeLogger();
+
+            samplelogger.logPartialSample(Util.getNanos() - this.taskExecutionStartNanos - this.idleTimeNanos, TpsDebugDimensions.SCHEDULED_TASKS.ordinal());
+            samplelogger.logPartialSample(this.idleTimeNanos, TpsDebugDimensions.IDLE.ordinal());
         }
+
     }
 
     private static CrashReport constructOrExtractCrashReport(Throwable throwable) {
-        ReportedException reportedException = null;
+        ReportedException reportedexception = null;
 
-        for (Throwable throwable2 = throwable; throwable2 != null; throwable2 = throwable2.getCause()) {
-            if (throwable2 instanceof ReportedException reportedException2) {
-                reportedException = reportedException2;
+        for (Throwable throwable1 = throwable; throwable1 != null; throwable1 = throwable1.getCause()) {
+            if (throwable1 instanceof ReportedException reportedexception1) {
+                reportedexception = reportedexception1;
             }
         }
 
-        CrashReport crashReport;
-        if (reportedException != null) {
-            crashReport = reportedException.getReport();
-            if (reportedException != throwable) {
-                crashReport.addCategory("Wrapped in").setDetailError("Wrapping exception", throwable);
+        CrashReport crashreport;
+
+        if (reportedexception != null) {
+            crashreport = reportedexception.getReport();
+            if (reportedexception != throwable) {
+                crashreport.addCategory("Wrapped in").setDetailError("Wrapping exception", throwable);
             }
         } else {
-            crashReport = new CrashReport("Exception in server tick loop", throwable);
+            crashreport = new CrashReport("Exception in server tick loop", throwable);
         }
 
-        return crashReport;
+        return crashreport;
     }
 
     private boolean haveTime() {
-        return this.runningTask() || Util.getNanos() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTimeNanos : this.nextTickTimeNanos);
+        // CraftBukkit start
+        if (isOversleep) return canOversleep(); // Paper - because of our changes, this logic is broken
+        return this.forceTicks || this.runningTask() || Util.getNanos() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTimeNanos : this.nextTickTimeNanos);
+    }
+
+    // Paper start
+    boolean isOversleep = false;
+    private boolean canOversleep() {
+        return this.mayHaveDelayedTasks && Util.getNanos() < this.delayedTasksMaxNextTickTimeNanos;
+    }
+
+    private boolean canSleepForTickNoOversleep() {
+        return this.forceTicks || this.runningTask() || Util.getNanos() < this.nextTickTimeNanos;
+    }
+    // Paper end
+
+    private void executeModerately() {
+        this.runAllTasks();
+        java.util.concurrent.locks.LockSupport.parkNanos("executing tasks", 1000L);
+        // CraftBukkit end
     }
 
     public static boolean throwIfFatalException() {
-        RuntimeException runtimeException = fatalException.get();
-        if (runtimeException != null) {
-            throw runtimeException;
+        RuntimeException runtimeexception = (RuntimeException) MinecraftServer.fatalException.get();
+
+        if (runtimeexception != null) {
+            throw runtimeexception;
         } else {
             return true;
         }
     }
 
     public static void setFatalException(RuntimeException exception) {
-        fatalException.compareAndSet(null, exception);
+        MinecraftServer.fatalException.compareAndSet(null, exception); // CraftBukkit - decompile error
     }
 
     @Override
     public void managedBlock(BooleanSupplier stopCondition) {
-        super.managedBlock(() -> throwIfFatalException() && stopCondition.getAsBoolean());
+        super.managedBlock(() -> {
+            return MinecraftServer.throwIfFatalException() && stopCondition.getAsBoolean();
+        });
     }
 
     protected void waitUntilNextTick() {
-        this.runAllTasks();
-        this.managedBlock(() -> !this.haveTime());
+        //this.executeAll(); // Paper - move this into the tick method for timings
+        this.managedBlock(() -> {
+            return !this.canSleepForTickNoOversleep(); // Paper - move oversleep into full server tick
+        });
     }
 
     @Override
     public void waitForTasks() {
-        boolean bl = this.isTickTimeLoggingEnabled();
-        long l = bl ? Util.getNanos() : 0L;
+        boolean flag = this.isTickTimeLoggingEnabled();
+        long i = flag ? Util.getNanos() : 0L;
+
         super.waitForTasks();
-        if (bl) {
-            this.idleTimeNanos = this.idleTimeNanos + (Util.getNanos() - l);
+        if (flag) {
+            this.idleTimeNanos += Util.getNanos() - i;
         }
+
     }
 
     @Override
     public TickTask wrapRunnable(Runnable runnable) {
+        // Paper start - anything that does try to post to main during watchdog crash, run on watchdog
+        if (this.hasStopped && Thread.currentThread().equals(shutdownThread)) {
+            runnable.run();
+            runnable = () -> {};
+        }
+        // Paper end
         return new TickTask(this.tickCount, runnable);
     }
 
-    @Override
-    protected boolean shouldRun(TickTask tickTask) {
-        return tickTask.getTick() + 3 < this.tickCount || this.haveTime();
+    protected boolean shouldRun(TickTask ticktask) {
+        return ticktask.getTick() + 3 < this.tickCount || this.haveTime();
     }
 
     @Override
     public boolean pollTask() {
-        boolean bl = this.pollTaskInternal();
-        this.mayHaveDelayedTasks = bl;
-        return bl;
+        boolean flag = this.pollTaskInternal();
+
+        this.mayHaveDelayedTasks = flag;
+        return flag;
     }
 
     private boolean pollTaskInternal() {
         if (super.pollTask()) {
+            this.moonrise$executeMidTickTasks(); // Paper - rewrite chunk system
             return true;
         } else {
+            boolean ret = false; // Paper - force execution of all worlds, do not just bias the first
             if (this.tickRateManager.isSprinting() || this.haveTime()) {
-                for (ServerLevel serverLevel : this.getAllLevels()) {
-                    if (serverLevel.getChunkSource().pollTask()) {
-                        return true;
+                Iterator iterator = this.getAllLevels().iterator();
+
+                while (iterator.hasNext()) {
+                    ServerLevel worldserver = (ServerLevel) iterator.next();
+
+                    if (worldserver.getChunkSource().pollTask()) {
+                        ret = true; // Paper - force execution of all worlds, do not just bias the first
                     }
                 }
             }
 
-            return false;
+            return ret; // Paper - force execution of all worlds, do not just bias the first
         }
     }
 
-    @Override
-    public void doRunTask(TickTask tickTask) {
+    public void doRunTask(TickTask ticktask) { // CraftBukkit - decompile error
         this.getProfiler().incrementCounter("runTask");
-        super.doRunTask(tickTask);
+        super.doRunTask(ticktask);
     }
 
     private Optional<ServerStatus.Favicon> loadStatusIcon() {
-        Optional<Path> optional = Optional.of(this.getFile("server-icon.png"))
-            .filter(path -> Files.isRegularFile(path))
-            .or(() -> this.storageSource.getIconFile().filter(path -> Files.isRegularFile(path)));
-        return optional.flatMap(path -> {
+        Optional<Path> optional = Optional.of(this.getFile("server-icon.png")).filter((path) -> {
+            return Files.isRegularFile(path, new LinkOption[0]);
+        }).or(() -> {
+            return this.storageSource.getIconFile().filter((path) -> {
+                return Files.isRegularFile(path, new LinkOption[0]);
+            });
+        });
+
+        return optional.flatMap((path) -> {
             try {
-                BufferedImage bufferedImage = ImageIO.read(path.toFile());
-                Preconditions.checkState(bufferedImage.getWidth() == 64, "Must be 64 pixels wide");
-                Preconditions.checkState(bufferedImage.getHeight() == 64, "Must be 64 pixels high");
-                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-                ImageIO.write(bufferedImage, "PNG", byteArrayOutputStream);
-                return Optional.of(new ServerStatus.Favicon(byteArrayOutputStream.toByteArray()));
-            } catch (Exception var3) {
-                LOGGER.error("Couldn't load server icon", (Throwable)var3);
+                BufferedImage bufferedimage = ImageIO.read(path.toFile());
+
+                Preconditions.checkState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide");
+                Preconditions.checkState(bufferedimage.getHeight() == 64, "Must be 64 pixels high");
+                ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
+
+                ImageIO.write(bufferedimage, "PNG", bytearrayoutputstream);
+                return Optional.of(new ServerStatus.Favicon(bytearrayoutputstream.toByteArray()));
+            } catch (Exception exception) {
+                MinecraftServer.LOGGER.error("Couldn't load server icon", exception);
                 return Optional.empty();
             }
         });
@@ -890,71 +1571,119 @@
         return Path.of("");
     }
 
-    public void onServerCrash(CrashReport report) {
-    }
+    public void onServerCrash(CrashReport report) {}
 
-    public void onServerExit() {
-    }
+    public void onServerExit() {}
 
     public boolean isPaused() {
         return false;
     }
 
     public void tickServer(BooleanSupplier shouldKeepTicking) {
-        long l = Util.getNanos();
-        this.tickCount++;
+        co.aikar.timings.TimingsManager.FULL_SERVER_TICK.startTiming(); // Paper
+        long i = Util.getNanos();
+
+        // Paper start - move oversleep into full server tick
+        isOversleep = true;MinecraftTimings.serverOversleep.startTiming();
+        this.managedBlock(() -> {
+            return !this.canOversleep();
+        });
+        isOversleep = false;MinecraftTimings.serverOversleep.stopTiming();
+        // Paper end
+        this.server.spark.tickStart(); // Paper - spark
+        new com.destroystokyo.paper.event.server.ServerTickStartEvent(this.tickCount+1).callEvent(); // Paper - Server Tick Events
+
+        ++this.tickCount;
         this.tickRateManager.tick();
         this.tickChildren(shouldKeepTicking);
-        if (l - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) {
-            this.lastServerStatus = l;
+        if (i - this.lastServerStatus >= MinecraftServer.STATUS_EXPIRE_TIME_NANOS) {
+            this.lastServerStatus = i;
             this.status = this.buildServerStatus();
         }
 
-        this.ticksUntilAutosave--;
-        if (this.ticksUntilAutosave <= 0) {
-            this.ticksUntilAutosave = this.computeNextAutosaveInterval();
-            LOGGER.debug("Autosave started");
-            this.profiler.push("save");
-            this.saveEverything(true, false, false);
-            this.profiler.pop();
-            LOGGER.debug("Autosave finished");
+        --this.ticksUntilAutosave;
+        // Paper start - Incremental chunk and player saving
+        int playerSaveInterval = io.papermc.paper.configuration.GlobalConfiguration.get().playerAutoSave.rate;
+        if (playerSaveInterval < 0) {
+            playerSaveInterval = autosavePeriod;
         }
-
+        this.profiler.push("save");
+        final boolean fullSave = autosavePeriod > 0 && this.tickCount % autosavePeriod == 0;
+        try {
+            this.isSaving = true;
+            if (playerSaveInterval > 0) {
+                this.playerList.saveAll(playerSaveInterval);
+            }
+            for (ServerLevel level : this.getAllLevels()) {
+                if (level.paperConfig().chunks.autoSaveInterval.value() > 0) {
+                    level.saveIncrementally(fullSave);
+                }
+            }
+        } finally {
+            this.isSaving = false;
+        }
+        this.profiler.pop();
+        // Paper end - Incremental chunk and player saving
+        // Paper start - move executeAll() into full server tick timing
+        try (co.aikar.timings.Timing ignored = MinecraftTimings.processTasksTimer.startTiming()) {
+            this.runAllTasks();
+        }
+        // Paper end
+        // Paper start - Server Tick Events
+        long endTime = System.nanoTime();
+        long remaining = (TICK_TIME - (endTime - lastTick)) - catchupTime;
+        new com.destroystokyo.paper.event.server.ServerTickEndEvent(this.tickCount, ((double)(endTime - lastTick) / 1000000D), remaining).callEvent();
+        this.server.spark.tickEnd(((double)(endTime - lastTick) / 1000000D)); // Paper - spark
+        // Paper end - Server Tick Events
         this.profiler.push("tallying");
-        long m = Util.getNanos() - l;
-        int i = this.tickCount % 100;
-        this.aggregatedTickTimesNanos = this.aggregatedTickTimesNanos - this.tickTimesNanos[i];
-        this.aggregatedTickTimesNanos += m;
-        this.tickTimesNanos[i] = m;
-        this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)m / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F;
-        this.logTickMethodTime(l);
+        long j = Util.getNanos() - i;
+        int k = this.tickCount % 100;
+
+        this.aggregatedTickTimesNanos -= this.tickTimesNanos[k];
+        this.aggregatedTickTimesNanos += j;
+        this.tickTimesNanos[k] = j;
+        this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float) j / (float) TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F;
+        // Paper start - Add tick times API and /mspt command
+        this.tickTimes5s.add(this.tickCount, j);
+        this.tickTimes10s.add(this.tickCount, j);
+        this.tickTimes60s.add(this.tickCount, j);
+        // Paper end - Add tick times API and /mspt command
+        this.logTickMethodTime(i);
         this.profiler.pop();
+        org.spigotmc.WatchdogThread.tick(); // Spigot
+        co.aikar.timings.TimingsManager.FULL_SERVER_TICK.stopTiming(); // Paper
     }
 
     private void logTickMethodTime(long tickStartTime) {
         if (this.isTickTimeLoggingEnabled()) {
             this.getTickTimeLogger().logPartialSample(Util.getNanos() - tickStartTime, TpsDebugDimensions.TICK_SERVER_METHOD.ordinal());
         }
+
     }
 
     private int computeNextAutosaveInterval() {
         float f;
+
         if (this.tickRateManager.isSprinting()) {
-            long l = this.getAverageTickTimeNanos() + 1L;
-            f = (float)TimeUtil.NANOSECONDS_PER_SECOND / (float)l;
+            long i = this.getAverageTickTimeNanos() + 1L;
+
+            f = (float) TimeUtil.NANOSECONDS_PER_SECOND / (float) i;
         } else {
             f = this.tickRateManager.tickrate();
         }
 
-        int i = 300;
-        return Math.max(100, (int)(f * 300.0F));
+        boolean flag = true;
+
+        return Math.max(100, (int) (f * 300.0F));
     }
 
     public void onTickRateChanged() {
         int i = this.computeNextAutosaveInterval();
+
         if (i < this.ticksUntilAutosave) {
             this.ticksUntilAutosave = i;
         }
+
     }
 
     protected abstract SampleLogger getTickTimeLogger();
@@ -962,101 +1691,178 @@
     public abstract boolean isTickTimeLoggingEnabled();
 
     private ServerStatus buildServerStatus() {
-        ServerStatus.Players players = this.buildPlayerStatus();
-        return new ServerStatus(
-            Component.nullToEmpty(this.motd),
-            Optional.of(players),
-            Optional.of(ServerStatus.Version.current()),
-            Optional.ofNullable(this.statusIcon),
-            this.enforceSecureProfile()
-        );
+        ServerStatus.Players serverping_serverpingplayersample = this.buildPlayerStatus();
+
+        return new ServerStatus(io.papermc.paper.adventure.PaperAdventure.asVanilla(this.motd), Optional.of(serverping_serverpingplayersample), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), this.enforceSecureProfile()); // Paper - Adventure
     }
 
     private ServerStatus.Players buildPlayerStatus() {
         List<ServerPlayer> list = this.playerList.getPlayers();
         int i = this.getMaxPlayers();
+
         if (this.hidesOnlinePlayers()) {
             return new ServerStatus.Players(i, list.size(), List.of());
         } else {
-            int j = Math.min(list.size(), 12);
-            ObjectArrayList<GameProfile> objectArrayList = new ObjectArrayList<>(j);
+            int j = Math.min(list.size(), org.spigotmc.SpigotConfig.playerSample); // Paper - PaperServerListPingEvent
+            ObjectArrayList<GameProfile> objectarraylist = new ObjectArrayList(j);
             int k = Mth.nextInt(this.random, 0, list.size() - j);
 
-            for (int l = 0; l < j; l++) {
-                ServerPlayer serverPlayer = list.get(k + l);
-                objectArrayList.add(serverPlayer.allowsListing() ? serverPlayer.getGameProfile() : ANONYMOUS_PLAYER_PROFILE);
+            for (int l = 0; l < j; ++l) {
+                ServerPlayer entityplayer = (ServerPlayer) list.get(k + l);
+
+                objectarraylist.add(entityplayer.allowsListing() ? entityplayer.getGameProfile() : MinecraftServer.ANONYMOUS_PLAYER_PROFILE);
             }
 
-            Util.shuffle(objectArrayList, this.random);
-            return new ServerStatus.Players(i, list.size(), objectArrayList);
+            Util.shuffle(objectarraylist, this.random);
+            return new ServerStatus.Players(i, list.size(), objectarraylist);
         }
     }
 
     public void tickChildren(BooleanSupplier shouldKeepTicking) {
-        this.getPlayerList().getPlayers().forEach(player -> player.connection.suspendFlushing());
+        this.getPlayerList().getPlayers().forEach((entityplayer) -> {
+            entityplayer.connection.suspendFlushing();
+        });
+        MinecraftTimings.bukkitSchedulerTimer.startTiming(); // Spigot // Paper
+        this.server.getScheduler().mainThreadHeartbeat(this.tickCount); // CraftBukkit
+        MinecraftTimings.bukkitSchedulerTimer.stopTiming(); // Spigot // Paper
+        // Paper start - Folia scheduler API
+        ((io.papermc.paper.threadedregions.scheduler.FoliaGlobalRegionScheduler) Bukkit.getGlobalRegionScheduler()).tick();
+        getAllLevels().forEach(level -> {
+            for (final Entity entity : level.moonrise$getEntityLookup().getAllCopy()) { // Paper - rewrite chunk system
+                if (entity.isRemoved()) {
+                    continue;
+                }
+                final org.bukkit.craftbukkit.entity.CraftEntity bukkit = entity.getBukkitEntityRaw();
+                if (bukkit != null) {
+                    bukkit.taskScheduler.executeTick();
+                }
+            }
+        });
+        // Paper end - Folia scheduler API
+        io.papermc.paper.adventure.providers.ClickCallbackProviderImpl.CALLBACK_MANAGER.handleQueue(this.tickCount); // Paper
         this.profiler.push("commandFunctions");
+        MinecraftTimings.commandFunctionsTimer.startTiming(); // Spigot // Paper
         this.getFunctions().tick();
+        MinecraftTimings.commandFunctionsTimer.stopTiming(); // Spigot // Paper
         this.profiler.popPush("levels");
+        //Iterator iterator = this.getAllLevels().iterator(); // Paper - Throw exception on world create while being ticked; moved down
 
-        for (ServerLevel serverLevel : this.getAllLevels()) {
-            this.profiler.push(() -> serverLevel + " " + serverLevel.dimension().location());
+        // CraftBukkit start
+        // Run tasks that are waiting on processing
+        MinecraftTimings.processQueueTimer.startTiming(); // Spigot
+        while (!this.processQueue.isEmpty()) {
+            this.processQueue.remove().run();
+        }
+        MinecraftTimings.processQueueTimer.stopTiming(); // Spigot
+
+        MinecraftTimings.timeUpdateTimer.startTiming(); // Spigot // Paper
+        // Send time updates to everyone, it will get the right time from the world the player is in.
+        // Paper start - Perf: Optimize time updates
+        for (final ServerLevel level : this.getAllLevels()) {
+            final boolean doDaylight = level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT);
+            final long dayTime = level.getDayTime();
+            long worldTime = level.getGameTime();
+            final ClientboundSetTimePacket worldPacket = new ClientboundSetTimePacket(worldTime, dayTime, doDaylight);
+            for (Player entityhuman : level.players()) {
+                if (!(entityhuman instanceof ServerPlayer) || (tickCount + entityhuman.getId()) % 20 != 0) {
+                    continue;
+                }
+                ServerPlayer entityplayer = (ServerPlayer) entityhuman;
+                long playerTime = entityplayer.getPlayerTime();
+                ClientboundSetTimePacket packet = (playerTime == dayTime) ? worldPacket :
+                    new ClientboundSetTimePacket(worldTime, playerTime, doDaylight);
+                entityplayer.connection.send(packet); // Add support for per player time
+            }
+        }
+        // Paper end - Perf: Optimize time updates
+        MinecraftTimings.timeUpdateTimer.stopTiming(); // Spigot // Paper
+
+        this.isIteratingOverLevels = true; // Paper - Throw exception on world create while being ticked
+        Iterator iterator = this.getAllLevels().iterator(); // Paper - Throw exception on world create while being ticked; move down
+        while (iterator.hasNext()) {
+            ServerLevel worldserver = (ServerLevel) iterator.next();
+            worldserver.hasPhysicsEvent = org.bukkit.event.block.BlockPhysicsEvent.getHandlerList().getRegisteredListeners().length > 0; // Paper - BlockPhysicsEvent
+            worldserver.hasEntityMoveEvent = io.papermc.paper.event.entity.EntityMoveEvent.getHandlerList().getRegisteredListeners().length > 0; // Paper - Add EntityMoveEvent
+            net.minecraft.world.level.block.entity.HopperBlockEntity.skipHopperEvents = worldserver.paperConfig().hopper.disableMoveEvent || org.bukkit.event.inventory.InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length == 0; // Paper - Perf: Optimize Hoppers
+            worldserver.updateLagCompensationTick(); // Paper - lag compensation
+
+            this.profiler.push(() -> {
+                String s = String.valueOf(worldserver);
+
+                return s + " " + String.valueOf(worldserver.dimension().location());
+            });
+            /* Drop global time updates
             if (this.tickCount % 20 == 0) {
                 this.profiler.push("timeSync");
-                this.synchronizeTime(serverLevel);
+                this.synchronizeTime(worldserver);
                 this.profiler.pop();
             }
+            // CraftBukkit end */
 
             this.profiler.push("tick");
 
             try {
-                serverLevel.tick(shouldKeepTicking);
-            } catch (Throwable var6) {
-                CrashReport crashReport = CrashReport.forThrowable(var6, "Exception ticking world");
-                serverLevel.fillReportDetails(crashReport);
-                throw new ReportedException(crashReport);
+                worldserver.timings.doTick.startTiming(); // Spigot
+                worldserver.tick(shouldKeepTicking);
+                worldserver.timings.doTick.stopTiming(); // Spigot
+            } catch (Throwable throwable) {
+                CrashReport crashreport = CrashReport.forThrowable(throwable, "Exception ticking world");
+
+                worldserver.fillReportDetails(crashreport);
+                throw new ReportedException(crashreport);
             }
 
             this.profiler.pop();
             this.profiler.pop();
+            worldserver.explosionDensityCache.clear(); // Paper - Optimize explosions
         }
+        this.isIteratingOverLevels = false; // Paper - Throw exception on world create while being ticked
 
         this.profiler.popPush("connection");
+        MinecraftTimings.connectionTimer.startTiming(); // Spigot // Paper
         this.getConnection().tick();
+        MinecraftTimings.connectionTimer.stopTiming(); // Spigot // Paper
         this.profiler.popPush("players");
+        MinecraftTimings.playerListTimer.startTiming(); // Spigot // Paper
         this.playerList.tick();
+        MinecraftTimings.playerListTimer.stopTiming(); // Spigot // Paper
         if (SharedConstants.IS_RUNNING_IN_IDE && this.tickRateManager.runsNormally()) {
             GameTestTicker.SINGLETON.tick();
         }
 
         this.profiler.popPush("server gui refresh");
 
-        for (int i = 0; i < this.tickables.size(); i++) {
-            this.tickables.get(i).run();
+        MinecraftTimings.tickablesTimer.startTiming(); // Spigot // Paper
+        for (int i = 0; i < this.tickables.size(); ++i) {
+            ((Runnable) this.tickables.get(i)).run();
         }
+        MinecraftTimings.tickablesTimer.stopTiming(); // Spigot // Paper
 
         this.profiler.popPush("send chunks");
+        iterator = this.playerList.getPlayers().iterator();
 
-        for (ServerPlayer serverPlayer : this.playerList.getPlayers()) {
-            serverPlayer.connection.chunkSender.sendNextChunks(serverPlayer);
-            serverPlayer.connection.resumeFlushing();
+        while (iterator.hasNext()) {
+            ServerPlayer entityplayer = (ServerPlayer) iterator.next();
+
+            entityplayer.connection.chunkSender.sendNextChunks(entityplayer);
+            entityplayer.connection.resumeFlushing();
         }
 
         this.profiler.pop();
     }
 
     private void synchronizeTime(ServerLevel world) {
-        this.playerList
-            .broadcastAll(
-                new ClientboundSetTimePacket(world.getGameTime(), world.getDayTime(), world.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)),
-                world.dimension()
-            );
+        this.playerList.broadcastAll(new ClientboundSetTimePacket(world.getGameTime(), world.getDayTime(), world.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)), world.dimension());
     }
 
     public void forceTimeSynchronization() {
         this.profiler.push("timeSync");
+        Iterator iterator = this.getAllLevels().iterator();
 
-        for (ServerLevel serverLevel : this.getAllLevels()) {
-            this.synchronizeTime(serverLevel);
+        while (iterator.hasNext()) {
+            ServerLevel worldserver = (ServerLevel) iterator.next();
+
+            this.synchronizeTime(worldserver);
         }
 
         this.profiler.pop();
@@ -1083,14 +1889,30 @@
     }
 
     public final ServerLevel overworld() {
-        return this.levels.get(Level.OVERWORLD);
+        return (ServerLevel) this.levels.get(Level.OVERWORLD);
     }
 
     @Nullable
     public ServerLevel getLevel(ResourceKey<Level> key) {
-        return this.levels.get(key);
+        return (ServerLevel) this.levels.get(key);
+    }
+
+    // CraftBukkit start
+    public void addLevel(ServerLevel level) {
+        Map<ResourceKey<Level>, ServerLevel> oldLevels = this.levels;
+        Map<ResourceKey<Level>, ServerLevel> newLevels = Maps.newLinkedHashMap(oldLevels);
+        newLevels.put(level.dimension(), level);
+        this.levels = Collections.unmodifiableMap(newLevels);
     }
 
+    public void removeLevel(ServerLevel level) {
+        Map<ResourceKey<Level>, ServerLevel> oldLevels = this.levels;
+        Map<ResourceKey<Level>, ServerLevel> newLevels = Maps.newLinkedHashMap(oldLevels);
+        newLevels.remove(level.dimension());
+        this.levels = Collections.unmodifiableMap(newLevels);
+    }
+    // CraftBukkit end
+
     public Set<ResourceKey<Level>> levelKeys() {
         return this.levels.keySet();
     }
@@ -1120,27 +1942,40 @@
 
     @DontObfuscate
     public String getServerModName() {
-        return "vanilla";
+        return io.papermc.paper.ServerBuildInfo.buildInfo().brandName(); // Paper
     }
 
     public SystemReport fillSystemReport(SystemReport details) {
-        details.setDetail("Server Running", () -> Boolean.toString(this.running));
+        details.setDetail("Server Running", () -> {
+            return Boolean.toString(this.running);
+        });
         if (this.playerList != null) {
-            details.setDetail(
-                "Player Count", () -> this.playerList.getPlayerCount() + " / " + this.playerList.getMaxPlayers() + "; " + this.playerList.getPlayers()
-            );
+            details.setDetail("Player Count", () -> {
+                int i = this.playerList.getPlayerCount();
+
+                return "" + i + " / " + this.playerList.getMaxPlayers() + "; " + String.valueOf(this.playerList.getPlayers());
+            });
         }
 
-        details.setDetail("Active Data Packs", () -> PackRepository.displayPackList(this.packRepository.getSelectedPacks()));
-        details.setDetail("Available Data Packs", () -> PackRepository.displayPackList(this.packRepository.getAvailablePacks()));
-        details.setDetail(
-            "Enabled Feature Flags",
-            () -> FeatureFlags.REGISTRY.toNames(this.worldData.enabledFeatures()).stream().map(ResourceLocation::toString).collect(Collectors.joining(", "))
-        );
-        details.setDetail("World Generation", () -> this.worldData.worldGenSettingsLifecycle().toString());
-        details.setDetail("World Seed", () -> String.valueOf(this.worldData.worldGenOptions().seed()));
+        details.setDetail("Active Data Packs", () -> {
+            return PackRepository.displayPackList(this.packRepository.getSelectedPacks());
+        });
+        details.setDetail("Available Data Packs", () -> {
+            return PackRepository.displayPackList(this.packRepository.getAvailablePacks());
+        });
+        details.setDetail("Enabled Feature Flags", () -> {
+            return (String) FeatureFlags.REGISTRY.toNames(this.worldData.enabledFeatures()).stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
+        });
+        details.setDetail("World Generation", () -> {
+            return this.worldData.worldGenSettingsLifecycle().toString();
+        });
+        details.setDetail("World Seed", () -> {
+            return String.valueOf(this.worldData.worldGenOptions().seed());
+        });
         if (this.serverId != null) {
-            details.setDetail("Server Id", () -> this.serverId);
+            details.setDetail("Server Id", () -> {
+                return this.serverId;
+            });
         }
 
         return this.fillServerSystemReport(details);
@@ -1154,7 +1989,7 @@
 
     @Override
     public void sendSystemMessage(Component message) {
-        LOGGER.info(message.getString());
+        MinecraftServer.LOGGER.info(io.papermc.paper.adventure.PaperAdventure.ANSI_SERIALIZER.serialize(io.papermc.paper.adventure.PaperAdventure.asAdventure(message))); // Paper - Log message with colors
     }
 
     public KeyPair getKeyPair() {
@@ -1183,20 +2018,23 @@
     }
 
     protected void initializeKeyPair() {
-        LOGGER.info("Generating keypair");
+        MinecraftServer.LOGGER.info("Generating keypair");
 
         try {
             this.keyPair = Crypt.generateKeyPair();
-        } catch (CryptException var2) {
-            throw new IllegalStateException("Failed to generate key pair", var2);
+        } catch (CryptException cryptographyexception) {
+            throw new IllegalStateException("Failed to generate key pair", cryptographyexception);
         }
     }
 
-    public void setDifficulty(Difficulty difficulty, boolean forceUpdate) {
-        if (forceUpdate || !this.worldData.isDifficultyLocked()) {
-            this.worldData.setDifficulty(this.worldData.isHardcore() ? Difficulty.HARD : difficulty);
-            this.updateMobSpawningFlags();
-            this.getPlayerList().getPlayers().forEach(this::sendDifficultyUpdate);
+    // Paper start - per level difficulty
+    public void setDifficulty(ServerLevel level, Difficulty difficulty, boolean forceUpdate) {
+        PrimaryLevelData worldData = level.serverLevelData;
+        if (forceUpdate || !worldData.isDifficultyLocked()) {
+            worldData.setDifficulty(worldData.isHardcore() ? Difficulty.HARD : difficulty);
+            level.setSpawnSettings(worldData.getDifficulty() != Difficulty.PEACEFUL && ((DedicatedServer) this).settings.getProperties().spawnMonsters, this.isSpawningAnimals());
+            // this.getPlayerList().getPlayers().forEach(this::sendDifficultyUpdate);
+            // Paper end - per level difficulty
         }
     }
 
@@ -1205,9 +2043,14 @@
     }
 
     private void updateMobSpawningFlags() {
-        for (ServerLevel serverLevel : this.getAllLevels()) {
-            serverLevel.setSpawnSettings(this.isSpawningMonsters(), this.isSpawningAnimals());
+        Iterator iterator = this.getAllLevels().iterator();
+
+        while (iterator.hasNext()) {
+            ServerLevel worldserver = (ServerLevel) iterator.next();
+
+            worldserver.setSpawnSettings(worldserver.serverLevelData.getDifficulty() != Difficulty.PEACEFUL && ((DedicatedServer) this).settings.getProperties().spawnMonsters, this.isSpawningAnimals()); // Paper - per level difficulty (from setDifficulty(ServerLevel, Difficulty, boolean))
         }
+
     }
 
     public void setDifficultyLocked(boolean locked) {
@@ -1216,8 +2059,9 @@
     }
 
     private void sendDifficultyUpdate(ServerPlayer player) {
-        LevelData levelData = player.level().getLevelData();
-        player.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
+        LevelData worlddata = player.level().getLevelData();
+
+        player.connection.send(new ClientboundChangeDifficultyPacket(worlddata.getDifficulty(), worlddata.isDifficultyLocked()));
     }
 
     public boolean isSpawningMonsters() {
@@ -1290,10 +2134,20 @@
 
     @Override
     public String getMotd() {
-        return this.motd;
+        return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(this.motd); // Paper - Adventure
     }
 
     public void setMotd(String motd) {
+        // Paper start - Adventure
+        this.motd = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserializeOr(motd, net.kyori.adventure.text.Component.empty());
+    }
+
+    public net.kyori.adventure.text.Component motd() {
+        return this.motd;
+    }
+
+    public void motd(net.kyori.adventure.text.Component motd) {
+        // Paper end - Adventure
         this.motd = motd;
     }
 
@@ -1316,7 +2170,7 @@
     }
 
     public ServerConnectionListener getConnection() {
-        return this.connection;
+        return this.connection == null ? this.connection = new ServerConnectionListener(this) : this.connection; // Spigot
     }
 
     public boolean isReady() {
@@ -1402,7 +2256,7 @@
     @Override
     public void executeIfPossible(Runnable runnable) {
         if (this.isStopped()) {
-            throw new RejectedExecutionException("Server already shutting down");
+            throw new io.papermc.paper.util.ServerStopRejectedExecutionException("Server already shutting down"); // Paper - do not prematurely disconnect players on stop
         } else {
             super.executeIfPossible(runnable);
         }
@@ -1441,144 +2295,165 @@
         return this.functionManager;
     }
 
+    // Paper start - Add ServerResourcesReloadedEvent
+    @Deprecated @io.papermc.paper.annotation.DoNotUse
     public CompletableFuture<Void> reloadResources(Collection<String> dataPacks) {
-        CompletableFuture<Void> completableFuture = CompletableFuture.<ImmutableList>supplyAsync(
-                () -> dataPacks.stream().map(this.packRepository::getPack).filter(Objects::nonNull).map(Pack::open).collect(ImmutableList.toImmutableList()),
-                this
-            )
-            .thenCompose(
-                resourcePacks -> {
-                    CloseableResourceManager closeableResourceManager = new MultiPackResourceManager(PackType.SERVER_DATA, resourcePacks);
-                    return ReloadableServerResources.loadResources(
-                            closeableResourceManager,
-                            this.registries,
-                            this.worldData.enabledFeatures(),
-                            this.isDedicatedServer() ? Commands.CommandSelection.DEDICATED : Commands.CommandSelection.INTEGRATED,
-                            this.getFunctionCompilationLevel(),
-                            this.executor,
-                            this
-                        )
-                        .whenComplete((dataPackContents, throwable) -> {
-                            if (throwable != null) {
-                                closeableResourceManager.close();
-                            }
-                        })
-                        .thenApply(dataPackContents -> new MinecraftServer.ReloadableResources(closeableResourceManager, dataPackContents));
+        return this.reloadResources(dataPacks, io.papermc.paper.event.server.ServerResourcesReloadedEvent.Cause.PLUGIN);
+    }
+    public CompletableFuture<Void> reloadResources(Collection<String> dataPacks, io.papermc.paper.event.server.ServerResourcesReloadedEvent.Cause cause) {
+        // Paper end - Add ServerResourcesReloadedEvent
+        CompletableFuture<Void> completablefuture = CompletableFuture.supplyAsync(() -> {
+            Stream<String> stream = dataPacks.stream(); // CraftBukkit - decompile error
+            PackRepository resourcepackrepository = this.packRepository;
+
+            Objects.requireNonNull(this.packRepository);
+            return stream.<Pack>map(resourcepackrepository::getPack).filter(Objects::nonNull).map(Pack::open).collect(ImmutableList.toImmutableList()); // CraftBukkit - decompile error // Paper - decompile error // todo: is this needed anymore?
+        }, this).thenCompose((immutablelist) -> {
+            MultiPackResourceManager resourcemanager = new MultiPackResourceManager(PackType.SERVER_DATA, immutablelist);
+
+            return ReloadableServerResources.loadResources(resourcemanager, this.registries, this.worldData.enabledFeatures(), this.isDedicatedServer() ? Commands.CommandSelection.DEDICATED : Commands.CommandSelection.INTEGRATED, this.getFunctionCompilationLevel(), this.executor, this).whenComplete((datapackresources, throwable) -> {
+                if (throwable != null) {
+                    resourcemanager.close();
                 }
-            )
-            .thenAcceptAsync(
-                resourceManagerHolder -> {
-                    this.resources.close();
-                    this.resources = resourceManagerHolder;
-                    this.packRepository.setSelected(dataPacks);
-                    WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(
-                        getSelectedPacks(this.packRepository, true), this.worldData.enabledFeatures()
-                    );
-                    this.worldData.setDataConfiguration(worldDataConfiguration);
-                    this.resources.managers.updateRegistryTags();
-                    this.getPlayerList().saveAll();
-                    this.getPlayerList().reloadResources();
-                    this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary());
-                    this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager);
-                },
-                this
-            );
+
+            }).thenApply((datapackresources) -> {
+                return new MinecraftServer.ReloadableResources(resourcemanager, datapackresources);
+            });
+        }).thenAcceptAsync((minecraftserver_reloadableresources) -> {
+            io.papermc.paper.command.brigadier.PaperBrigadier.moveBukkitCommands(this.resources.managers().getCommands(), minecraftserver_reloadableresources.managers().commands); // Paper
+            this.resources.close();
+            this.resources = minecraftserver_reloadableresources;
+            this.packRepository.setSelected(dataPacks);
+            WorldDataConfiguration worlddataconfiguration = new WorldDataConfiguration(MinecraftServer.getSelectedPacks(this.packRepository, true), this.worldData.enabledFeatures());
+
+            this.worldData.setDataConfiguration(worlddataconfiguration);
+            this.resources.managers.updateRegistryTags();
+            this.potionBrewing = this.potionBrewing.reload(this.worldData.enabledFeatures()); // Paper - Custom Potion Mixes
+            // Paper start
+            if (Thread.currentThread() != this.serverThread) {
+                return;
+            }
+            // this.getPlayerList().saveAll(); // Paper - we don't need to save everything, just advancements // TODO Move this to a different patch
+            for (ServerPlayer player : this.getPlayerList().getPlayers()) {
+                player.getAdvancements().save();
+            }
+            // Paper end
+            this.getPlayerList().reloadResources();
+            this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary());
+            this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager);
+            org.bukkit.craftbukkit.block.data.CraftBlockData.reloadCache(); // Paper - cache block data strings, they can be defined by datapacks so refresh it here
+            // Paper start - brigadier command API
+            io.papermc.paper.command.brigadier.PaperCommands.INSTANCE.setValid(); // reset invalid state for event fire below
+            io.papermc.paper.plugin.lifecycle.event.LifecycleEventRunner.INSTANCE.callReloadableRegistrarEvent(io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents.COMMANDS, io.papermc.paper.command.brigadier.PaperCommands.INSTANCE, org.bukkit.plugin.Plugin.class, io.papermc.paper.plugin.lifecycle.event.registrar.ReloadableRegistrarEvent.Cause.RELOAD); // call commands event for regular plugins
+            final org.bukkit.craftbukkit.help.SimpleHelpMap helpMap = (org.bukkit.craftbukkit.help.SimpleHelpMap) this.server.getHelpMap();
+            helpMap.clear();
+            helpMap.initializeGeneralTopics();
+            helpMap.initializeCommands();
+            this.server.syncCommands(); // Refresh commands after event
+            // Paper end
+            new io.papermc.paper.event.server.ServerResourcesReloadedEvent(cause).callEvent(); // Paper - fire after everything has been reloaded
+        }, this);
+
         if (this.isSameThread()) {
-            this.managedBlock(completableFuture::isDone);
+            Objects.requireNonNull(completablefuture);
+            this.managedBlock(completablefuture::isDone);
         }
 
-        return completableFuture;
+        return completablefuture;
     }
 
-    public static WorldDataConfiguration configurePackRepository(
-        PackRepository resourcePackManager, WorldDataConfiguration dataConfiguration, boolean initMode, boolean safeMode
-    ) {
-        DataPackConfig dataPackConfig = dataConfiguration.dataPacks();
-        FeatureFlagSet featureFlagSet = initMode ? FeatureFlagSet.of() : dataConfiguration.enabledFeatures();
-        FeatureFlagSet featureFlagSet2 = initMode ? FeatureFlags.REGISTRY.allFlags() : dataConfiguration.enabledFeatures();
+    public static WorldDataConfiguration configurePackRepository(PackRepository resourcePackManager, WorldDataConfiguration dataConfiguration, boolean initMode, boolean safeMode) {
+        DataPackConfig datapackconfiguration = dataConfiguration.dataPacks();
+        FeatureFlagSet featureflagset = initMode ? FeatureFlagSet.of() : dataConfiguration.enabledFeatures();
+        FeatureFlagSet featureflagset1 = initMode ? FeatureFlags.REGISTRY.allFlags() : dataConfiguration.enabledFeatures();
+
         resourcePackManager.reload();
         if (safeMode) {
-            return configureRepositoryWithSelection(resourcePackManager, List.of("vanilla"), featureFlagSet, false);
+            return MinecraftServer.configureRepositoryWithSelection(resourcePackManager, List.of("vanilla"), featureflagset, false);
         } else {
             Set<String> set = Sets.newLinkedHashSet();
+            Iterator iterator = datapackconfiguration.getEnabled().iterator();
 
-            for (String string : dataPackConfig.getEnabled()) {
-                if (resourcePackManager.isAvailable(string)) {
-                    set.add(string);
+            while (iterator.hasNext()) {
+                String s = (String) iterator.next();
+
+                if (resourcePackManager.isAvailable(s)) {
+                    set.add(s);
                 } else {
-                    LOGGER.warn("Missing data pack {}", string);
+                    MinecraftServer.LOGGER.warn("Missing data pack {}", s);
                 }
             }
 
-            for (Pack pack : resourcePackManager.getAvailablePacks()) {
-                String string2 = pack.getId();
-                if (!dataPackConfig.getDisabled().contains(string2)) {
-                    FeatureFlagSet featureFlagSet3 = pack.getRequestedFeatures();
-                    boolean bl = set.contains(string2);
-                    if (!bl && pack.getPackSource().shouldAddAutomatically()) {
-                        if (featureFlagSet3.isSubsetOf(featureFlagSet2)) {
-                            LOGGER.info("Found new data pack {}, loading it automatically", string2);
-                            set.add(string2);
+            iterator = resourcePackManager.getAvailablePacks().iterator();
+
+            while (iterator.hasNext()) {
+                Pack resourcepackloader = (Pack) iterator.next();
+                String s1 = resourcepackloader.getId();
+
+                if (!datapackconfiguration.getDisabled().contains(s1)) {
+                    FeatureFlagSet featureflagset2 = resourcepackloader.getRequestedFeatures();
+                    boolean flag2 = set.contains(s1);
+
+                    if (!flag2 && resourcepackloader.getPackSource().shouldAddAutomatically()) {
+                        if (featureflagset2.isSubsetOf(featureflagset1)) {
+                            MinecraftServer.LOGGER.info("Found new data pack {}, loading it automatically", s1);
+                            set.add(s1);
                         } else {
-                            LOGGER.info(
-                                "Found new data pack {}, but can't load it due to missing features {}",
-                                string2,
-                                FeatureFlags.printMissingFlags(featureFlagSet2, featureFlagSet3)
-                            );
+                            MinecraftServer.LOGGER.info("Found new data pack {}, but can't load it due to missing features {}", s1, FeatureFlags.printMissingFlags(featureflagset1, featureflagset2));
                         }
                     }
 
-                    if (bl && !featureFlagSet3.isSubsetOf(featureFlagSet2)) {
-                        LOGGER.warn(
-                            "Pack {} requires features {} that are not enabled for this world, disabling pack.",
-                            string2,
-                            FeatureFlags.printMissingFlags(featureFlagSet2, featureFlagSet3)
-                        );
-                        set.remove(string2);
+                    if (flag2 && !featureflagset2.isSubsetOf(featureflagset1)) {
+                        MinecraftServer.LOGGER.warn("Pack {} requires features {} that are not enabled for this world, disabling pack.", s1, FeatureFlags.printMissingFlags(featureflagset1, featureflagset2));
+                        set.remove(s1);
                     }
                 }
             }
 
             if (set.isEmpty()) {
-                LOGGER.info("No datapacks selected, forcing vanilla");
+                MinecraftServer.LOGGER.info("No datapacks selected, forcing vanilla");
                 set.add("vanilla");
             }
 
-            return configureRepositoryWithSelection(resourcePackManager, set, featureFlagSet, true);
+            return MinecraftServer.configureRepositoryWithSelection(resourcePackManager, set, featureflagset, true);
         }
     }
 
-    private static WorldDataConfiguration configureRepositoryWithSelection(
-        PackRepository resourcePackManager, Collection<String> enabledProfiles, FeatureFlagSet enabledFeatures, boolean allowEnabling
-    ) {
+    private static WorldDataConfiguration configureRepositoryWithSelection(PackRepository resourcePackManager, Collection<String> enabledProfiles, FeatureFlagSet enabledFeatures, boolean allowEnabling) {
         resourcePackManager.setSelected(enabledProfiles);
-        enableForcedFeaturePacks(resourcePackManager, enabledFeatures);
-        DataPackConfig dataPackConfig = getSelectedPacks(resourcePackManager, allowEnabling);
-        FeatureFlagSet featureFlagSet = resourcePackManager.getRequestedFeatureFlags().join(enabledFeatures);
-        return new WorldDataConfiguration(dataPackConfig, featureFlagSet);
+        MinecraftServer.enableForcedFeaturePacks(resourcePackManager, enabledFeatures);
+        DataPackConfig datapackconfiguration = MinecraftServer.getSelectedPacks(resourcePackManager, allowEnabling);
+        FeatureFlagSet featureflagset1 = resourcePackManager.getRequestedFeatureFlags().join(enabledFeatures);
+
+        return new WorldDataConfiguration(datapackconfiguration, featureflagset1);
     }
 
     private static void enableForcedFeaturePacks(PackRepository resourcePackManager, FeatureFlagSet enabledFeatures) {
-        FeatureFlagSet featureFlagSet = resourcePackManager.getRequestedFeatureFlags();
-        FeatureFlagSet featureFlagSet2 = enabledFeatures.subtract(featureFlagSet);
-        if (!featureFlagSet2.isEmpty()) {
-            Set<String> set = new ObjectArraySet<>(resourcePackManager.getSelectedIds());
+        FeatureFlagSet featureflagset1 = resourcePackManager.getRequestedFeatureFlags();
+        FeatureFlagSet featureflagset2 = enabledFeatures.subtract(featureflagset1);
 
-            for (Pack pack : resourcePackManager.getAvailablePacks()) {
-                if (featureFlagSet2.isEmpty()) {
+        if (!featureflagset2.isEmpty()) {
+            Set<String> set = new ObjectArraySet(resourcePackManager.getSelectedIds());
+            Iterator iterator = resourcePackManager.getAvailablePacks().iterator();
+
+            while (iterator.hasNext()) {
+                Pack resourcepackloader = (Pack) iterator.next();
+
+                if (featureflagset2.isEmpty()) {
                     break;
                 }
 
-                if (pack.getPackSource() == PackSource.FEATURE) {
-                    String string = pack.getId();
-                    FeatureFlagSet featureFlagSet3 = pack.getRequestedFeatures();
-                    if (!featureFlagSet3.isEmpty() && featureFlagSet3.intersects(featureFlagSet2) && featureFlagSet3.isSubsetOf(enabledFeatures)) {
-                        if (!set.add(string)) {
-                            throw new IllegalStateException("Tried to force '" + string + "', but it was already enabled");
+                if (resourcepackloader.getPackSource() == PackSource.FEATURE) {
+                    String s = resourcepackloader.getId();
+                    FeatureFlagSet featureflagset3 = resourcepackloader.getRequestedFeatures();
+
+                    if (!featureflagset3.isEmpty() && featureflagset3.intersects(featureflagset2) && featureflagset3.isSubsetOf(enabledFeatures)) {
+                        if (!set.add(s)) {
+                            throw new IllegalStateException("Tried to force '" + s + "', but it was already enabled");
                         }
 
-                        LOGGER.info("Found feature pack ('{}') for requested feature, forcing to enabled", string);
-                        featureFlagSet2 = featureFlagSet2.subtract(featureFlagSet3);
+                        MinecraftServer.LOGGER.info("Found feature pack ('{}') for requested feature, forcing to enabled", s);
+                        featureflagset2 = featureflagset2.subtract(featureflagset3);
                     }
                 }
             }
@@ -1590,20 +2465,29 @@
     private static DataPackConfig getSelectedPacks(PackRepository dataPackManager, boolean allowEnabling) {
         Collection<String> collection = dataPackManager.getSelectedIds();
         List<String> list = ImmutableList.copyOf(collection);
-        List<String> list2 = allowEnabling ? dataPackManager.getAvailableIds().stream().filter(name -> !collection.contains(name)).toList() : List.of();
-        return new DataPackConfig(list, list2);
+        List<String> list1 = allowEnabling ? dataPackManager.getAvailableIds().stream().filter((s) -> {
+            return !collection.contains(s);
+        }).toList() : List.of();
+
+        return new DataPackConfig(list, list1);
     }
 
     public void kickUnlistedPlayers(CommandSourceStack source) {
         if (this.isEnforceWhitelist()) {
-            PlayerList playerList = source.getServer().getPlayerList();
-            UserWhiteList userWhiteList = playerList.getWhiteList();
+            PlayerList playerlist = source.getServer().getPlayerList();
+            UserWhiteList whitelist = playerlist.getWhiteList();
+            if (!((DedicatedServer) getServer()).getProperties().whiteList.get()) return; // Paper - whitelist not enabled
+            List<ServerPlayer> list = Lists.newArrayList(playerlist.getPlayers());
+            Iterator iterator = list.iterator();
 
-            for (ServerPlayer serverPlayer : Lists.newArrayList(playerList.getPlayers())) {
-                if (!userWhiteList.isWhiteListed(serverPlayer.getGameProfile())) {
-                    serverPlayer.connection.disconnect(Component.translatable("multiplayer.disconnect.not_whitelisted"));
+            while (iterator.hasNext()) {
+                ServerPlayer entityplayer = (ServerPlayer) iterator.next();
+
+                if (!whitelist.isWhiteListed(entityplayer.getGameProfile()) && !this.getPlayerList().isOp(entityplayer.getGameProfile())) { // Paper - Fix kicking ops when whitelist is reloaded (MC-171420)
+                    entityplayer.connection.disconnect(net.kyori.adventure.text.Component.text(org.spigotmc.SpigotConfig.whitelistMessage), org.bukkit.event.player.PlayerKickEvent.Cause.WHITELIST); // Paper - use configurable message & kick event cause
                 }
             }
+
         }
     }
 
@@ -1616,18 +2500,9 @@
     }
 
     public CommandSourceStack createCommandSourceStack() {
-        ServerLevel serverLevel = this.overworld();
-        return new CommandSourceStack(
-            this,
-            serverLevel == null ? Vec3.ZERO : Vec3.atLowerCornerOf(serverLevel.getSharedSpawnPos()),
-            Vec2.ZERO,
-            serverLevel,
-            4,
-            "Server",
-            Component.literal("Server"),
-            this,
-            null
-        );
+        ServerLevel worldserver = this.overworld();
+
+        return new CommandSourceStack(this, worldserver == null ? Vec3.ZERO : Vec3.atLowerCornerOf(worldserver.getSharedSpawnPos()), Vec2.ZERO, worldserver, 4, "Server", Component.literal("Server"), this, (Entity) null);
     }
 
     @Override
@@ -1684,7 +2559,7 @@
     }
 
     public long getAverageTickTimeNanos() {
-        return this.aggregatedTickTimesNanos / (long)Math.min(100, Math.max(this.tickCount, 1));
+        return this.aggregatedTickTimesNanos / (long) Math.min(100, Math.max(this.tickCount, 1));
     }
 
     public long[] getTickTimesNanos() {
@@ -1693,16 +2568,9 @@
 
     public int getProfilePermissions(GameProfile profile) {
         if (this.getPlayerList().isOp(profile)) {
-            ServerOpListEntry serverOpListEntry = this.getPlayerList().getOps().get(profile);
-            if (serverOpListEntry != null) {
-                return serverOpListEntry.getLevel();
-            } else if (this.isSingleplayerOwner(profile)) {
-                return 4;
-            } else if (this.isSingleplayer()) {
-                return this.getPlayerList().isAllowCommandsForAllPlayers() ? 4 : 0;
-            } else {
-                return this.getOperatorUserPermissionLevel();
-            }
+            ServerOpListEntry oplistentry = (ServerOpListEntry) this.getPlayerList().getOps().get(profile);
+
+            return oplistentry != null ? oplistentry.getLevel() : (this.isSingleplayerOwner(profile) ? 4 : (this.isSingleplayer() ? (this.getPlayerList().isAllowCommandsForAllPlayers() ? 4 : 0) : this.getOperatorUserPermissionLevel()));
         } else {
             return 0;
         }
@@ -1714,18 +2582,21 @@
 
     public abstract boolean isSingleplayerOwner(GameProfile profile);
 
-    public void dumpServerProperties(Path file) throws IOException {
-    }
+    public void dumpServerProperties(Path file) throws IOException {}
 
     private void saveDebugReport(Path path) {
-        Path path2 = path.resolve("levels");
+        Path path1 = path.resolve("levels");
 
         try {
-            for (Entry<ResourceKey<Level>, ServerLevel> entry : this.levels.entrySet()) {
-                ResourceLocation resourceLocation = entry.getKey().location();
-                Path path3 = path2.resolve(resourceLocation.getNamespace()).resolve(resourceLocation.getPath());
-                Files.createDirectories(path3);
-                entry.getValue().saveDebugReport(path3);
+            Iterator iterator = this.levels.entrySet().iterator();
+
+            while (iterator.hasNext()) {
+                Entry<ResourceKey<Level>, ServerLevel> entry = (Entry) iterator.next();
+                ResourceLocation minecraftkey = ((ResourceKey) entry.getKey()).location();
+                Path path2 = path1.resolve(minecraftkey.getNamespace()).resolve(minecraftkey.getPath());
+
+                Files.createDirectories(path2);
+                ((ServerLevel) entry.getValue()).saveDebugReport(path2);
             }
 
             this.dumpGameRules(path.resolve("gamerules.txt"));
@@ -1734,94 +2605,231 @@
             this.dumpThreads(path.resolve("threads.txt"));
             this.dumpServerProperties(path.resolve("server.properties.txt"));
             this.dumpNativeModules(path.resolve("modules.txt"));
-        } catch (IOException var7) {
-            LOGGER.warn("Failed to save debug report", (Throwable)var7);
+        } catch (IOException ioexception) {
+            MinecraftServer.LOGGER.warn("Failed to save debug report", ioexception);
         }
+
     }
 
     private void dumpMiscStats(Path path) throws IOException {
-        try (Writer writer = Files.newBufferedWriter(path)) {
-            writer.write(String.format(Locale.ROOT, "pending_tasks: %d\n", this.getPendingTasksCount()));
-            writer.write(String.format(Locale.ROOT, "average_tick_time: %f\n", this.getCurrentSmoothedTickTime()));
-            writer.write(String.format(Locale.ROOT, "tick_times: %s\n", Arrays.toString(this.tickTimesNanos)));
-            writer.write(String.format(Locale.ROOT, "queue: %s\n", Util.backgroundExecutor()));
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
+
+        try {
+            bufferedwriter.write(String.format(Locale.ROOT, "pending_tasks: %d\n", this.getPendingTasksCount()));
+            bufferedwriter.write(String.format(Locale.ROOT, "average_tick_time: %f\n", this.getCurrentSmoothedTickTime()));
+            bufferedwriter.write(String.format(Locale.ROOT, "tick_times: %s\n", Arrays.toString(this.tickTimesNanos)));
+            bufferedwriter.write(String.format(Locale.ROOT, "queue: %s\n", Util.backgroundExecutor()));
+        } catch (Throwable throwable) {
+            if (bufferedwriter != null) {
+                try {
+                    bufferedwriter.close();
+                } catch (Throwable throwable1) {
+                    throwable.addSuppressed(throwable1);
+                }
+            }
+
+            throw throwable;
+        }
+
+        if (bufferedwriter != null) {
+            bufferedwriter.close();
         }
+
     }
 
     private void dumpGameRules(Path path) throws IOException {
-        try (Writer writer = Files.newBufferedWriter(path)) {
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
+
+        try {
             final List<String> list = Lists.newArrayList();
-            final GameRules gameRules = this.getGameRules();
-            GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
+            final GameRules gamerules = this.getGameRules();
+
+            GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() { // CraftBukkit - decompile error
                 @Override
                 public <T extends GameRules.Value<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
-                    list.add(String.format(Locale.ROOT, "%s=%s\n", key.getId(), gameRules.getRule(key)));
+                    list.add(String.format(Locale.ROOT, "%s=%s\n", key.getId(), gamerules.getRule(key)));
                 }
             });
+            Iterator iterator = list.iterator();
 
-            for (String string : list) {
-                writer.write(string);
+            while (iterator.hasNext()) {
+                String s = (String) iterator.next();
+
+                bufferedwriter.write(s);
+            }
+        } catch (Throwable throwable) {
+            if (bufferedwriter != null) {
+                try {
+                    bufferedwriter.close();
+                } catch (Throwable throwable1) {
+                    throwable.addSuppressed(throwable1);
+                }
             }
+
+            throw throwable;
         }
+
+        if (bufferedwriter != null) {
+            bufferedwriter.close();
+        }
+
     }
 
     private void dumpClasspath(Path path) throws IOException {
-        try (Writer writer = Files.newBufferedWriter(path)) {
-            String string = System.getProperty("java.class.path");
-            String string2 = System.getProperty("path.separator");
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
 
-            for (String string3 : Splitter.on(string2).split(string)) {
-                writer.write(string3);
-                writer.write("\n");
+        try {
+            String s = System.getProperty("java.class.path");
+            String s1 = System.getProperty("path.separator");
+            Iterator iterator = Splitter.on(s1).split(s).iterator();
+
+            while (iterator.hasNext()) {
+                String s2 = (String) iterator.next();
+
+                bufferedwriter.write(s2);
+                bufferedwriter.write("\n");
+            }
+        } catch (Throwable throwable) {
+            if (bufferedwriter != null) {
+                try {
+                    bufferedwriter.close();
+                } catch (Throwable throwable1) {
+                    throwable.addSuppressed(throwable1);
+                }
             }
+
+            throw throwable;
         }
+
+        if (bufferedwriter != null) {
+            bufferedwriter.close();
+        }
+
     }
 
     private void dumpThreads(Path path) throws IOException {
-        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
-        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
-        Arrays.sort(threadInfos, Comparator.comparing(ThreadInfo::getThreadName));
+        ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean();
+        ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true);
 
-        try (Writer writer = Files.newBufferedWriter(path)) {
-            for (ThreadInfo threadInfo : threadInfos) {
-                writer.write(threadInfo.toString());
-                writer.write(10);
+        Arrays.sort(athreadinfo, Comparator.comparing(ThreadInfo::getThreadName));
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
+
+        try {
+            ThreadInfo[] athreadinfo1 = athreadinfo;
+            int i = athreadinfo.length;
+
+            for (int j = 0; j < i; ++j) {
+                ThreadInfo threadinfo = athreadinfo1[j];
+
+                bufferedwriter.write(threadinfo.toString());
+                bufferedwriter.write(10);
+            }
+        } catch (Throwable throwable) {
+            if (bufferedwriter != null) {
+                try {
+                    bufferedwriter.close();
+                } catch (Throwable throwable1) {
+                    throwable.addSuppressed(throwable1);
+                }
             }
+
+            throw throwable;
+        }
+
+        if (bufferedwriter != null) {
+            bufferedwriter.close();
         }
+
     }
 
     private void dumpNativeModules(Path path) throws IOException {
-        try (Writer writer = Files.newBufferedWriter(path)) {
-            List<NativeModuleLister.NativeModuleInfo> list;
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
+
+        label50:
+        {
             try {
-                list = Lists.newArrayList(NativeModuleLister.listModules());
-            } catch (Throwable var7) {
-                LOGGER.warn("Failed to list native modules", var7);
-                return;
-            }
+                label51:
+                {
+                    ArrayList<NativeModuleLister.NativeModuleInfo> arraylist; // CraftBukkit - decompile error
 
-            list.sort(Comparator.comparing(module -> module.name));
+                    try {
+                        arraylist = Lists.newArrayList(NativeModuleLister.listModules());
+                    } catch (Throwable throwable) {
+                        MinecraftServer.LOGGER.warn("Failed to list native modules", throwable);
+                        break label51;
+                    }
 
-            for (NativeModuleLister.NativeModuleInfo nativeModuleInfo : list) {
-                writer.write(nativeModuleInfo.toString());
-                writer.write(10);
+                    arraylist.sort(Comparator.comparing((nativemodulelister_a) -> {
+                        return nativemodulelister_a.name;
+                    }));
+                    Iterator iterator = arraylist.iterator();
+
+                    while (true) {
+                        if (!iterator.hasNext()) {
+                            break label50;
+                        }
+
+                        NativeModuleLister.NativeModuleInfo nativemodulelister_a = (NativeModuleLister.NativeModuleInfo) iterator.next();
+
+                        bufferedwriter.write(nativemodulelister_a.toString());
+                        bufferedwriter.write(10);
+                    }
+                }
+            } catch (Throwable throwable1) {
+                if (bufferedwriter != null) {
+                    try {
+                        bufferedwriter.close();
+                    } catch (Throwable throwable2) {
+                        throwable1.addSuppressed(throwable2);
+                    }
+                }
+
+                throw throwable1;
             }
+
+            if (bufferedwriter != null) {
+                bufferedwriter.close();
+            }
+
+            return;
+        }
+
+        if (bufferedwriter != null) {
+            bufferedwriter.close();
         }
+
     }
 
+    // Paper start - rewrite chunk system
+    @Override
+    public boolean isSameThread() {
+        return ca.spottedleaf.moonrise.common.util.TickThread.isTickThread();
+    }
+    // Paper end - rewrite chunk system
+
+    // CraftBukkit start
+    public boolean isDebugging() {
+        return false;
+    }
+
+    public static MinecraftServer getServer() {
+        return SERVER; // Paper
+    }
+
+    @Deprecated
+    public static RegistryAccess getDefaultRegistryAccess() {
+        return CraftRegistry.getMinecraftRegistry();
+    }
+    // CraftBukkit end
+
     private void startMetricsRecordingTick() {
         if (this.willStartRecordingMetrics) {
-            this.metricsRecorder = ActiveMetricsRecorder.createStarted(
-                new ServerMetricsSamplersProvider(Util.timeSource, this.isDedicatedServer()),
-                Util.timeSource,
-                Util.ioPool(),
-                new MetricsPersister("server"),
-                this.onMetricsRecordingStopped,
-                path -> {
-                    this.executeBlocking(() -> this.saveDebugReport(path.resolve("server")));
-                    this.onMetricsRecordingFinished.accept(path);
-                }
-            );
+            this.metricsRecorder = ActiveMetricsRecorder.createStarted(new ServerMetricsSamplersProvider(Util.timeSource, this.isDedicatedServer()), Util.timeSource, Util.ioPool(), new MetricsPersister("server"), this.onMetricsRecordingStopped, (path) -> {
+                this.executeBlocking(() -> {
+                    this.saveDebugReport(path.resolve("server"));
+                });
+                this.onMetricsRecordingFinished.accept(path);
+            });
             this.willStartRecordingMetrics = false;
         }
 
@@ -1840,9 +2848,9 @@
     }
 
     public void startRecordingMetrics(Consumer<ProfileResults> resultConsumer, Consumer<Path> dumpConsumer) {
-        this.onMetricsRecordingStopped = result -> {
+        this.onMetricsRecordingStopped = (methodprofilerresults) -> {
             this.stopRecordingMetrics();
-            resultConsumer.accept(result);
+            resultConsumer.accept(methodprofilerresults);
         };
         this.onMetricsRecordingFinished = dumpConsumer;
         this.willStartRecordingMetrics = true;
@@ -1894,7 +2902,7 @@
     }
 
     public ServerPlayerGameMode createGameModeForPlayer(ServerPlayer player) {
-        return (ServerPlayerGameMode)(this.isDemo() ? new DemoMode(player) : new ServerPlayerGameMode(player));
+        return (ServerPlayerGameMode) (this.isDemo() ? new DemoMode(player) : new ServerPlayerGameMode(player));
     }
 
     @Nullable
@@ -1922,9 +2930,10 @@
         if (this.debugCommandProfiler == null) {
             return EmptyProfileResults.EMPTY;
         } else {
-            ProfileResults profileResults = this.debugCommandProfiler.stop(Util.getNanos(), this.tickCount);
+            ProfileResults methodprofilerresults = this.debugCommandProfiler.stop(Util.getNanos(), this.tickCount);
+
             this.debugCommandProfiler = null;
-            return profileResults;
+            return methodprofilerresults;
         }
     }
 
@@ -1933,24 +2942,31 @@
     }
 
     public void logChatMessage(Component message, ChatType.Bound params, @Nullable String prefix) {
-        String string = params.decorate(message).getString();
+        // Paper start
+        net.kyori.adventure.text.Component s1 = io.papermc.paper.adventure.PaperAdventure.asAdventure(params.decorate(message));
+
         if (prefix != null) {
-            LOGGER.info("[{}] {}", prefix, string);
+            MinecraftServer.COMPONENT_LOGGER.info("[{}] {}", prefix, s1);
         } else {
-            LOGGER.info("{}", string);
+            MinecraftServer.COMPONENT_LOGGER.info("{}", s1);
+            // Paper end
         }
+
     }
 
+    public final java.util.concurrent.ExecutorService chatExecutor = java.util.concurrent.Executors.newCachedThreadPool(
+            new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon(true).setNameFormat("Async Chat Thread - #%d").setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build()); // Paper
+
+    public final ChatDecorator improvedChatDecorator = new io.papermc.paper.adventure.ImprovedChatDecorator(this); // Paper - adventure
     public ChatDecorator getChatDecorator() {
-        return ChatDecorator.PLAIN;
+        return this.improvedChatDecorator; // Paper - support async chat decoration events
     }
 
     public boolean logIPs() {
         return true;
     }
 
-    public void subscribeToDebugSample(ServerPlayer player, RemoteDebugSampleType type) {
-    }
+    public void subscribeToDebugSample(ServerPlayer player, RemoteDebugSampleType type) {}
 
     public boolean acceptsTransfers() {
         return false;
@@ -1960,38 +2976,47 @@
         Util.ioPool().execute(() -> {
             try {
                 Path path = this.getFile("debug");
+
                 FileUtil.createDirectoriesSafe(path);
-                String string = FileUtil.sanitizeName(key.level());
-                Path path2 = path.resolve("chunk-" + string + "-" + Util.getFilenameFormattedDateTime() + "-server.txt");
-                FileStore fileStore = Files.getFileStore(path);
-                long l = fileStore.getUsableSpace();
-                if (l < 8192L) {
-                    LOGGER.warn("Not storing chunk IO report due to low space on drive {}", fileStore.name());
+                String s = FileUtil.sanitizeName(key.level());
+                Path path1 = path.resolve("chunk-" + s + "-" + Util.getFilenameFormattedDateTime() + "-server.txt");
+                FileStore filestore = Files.getFileStore(path);
+                long i = filestore.getUsableSpace();
+
+                if (i < 8192L) {
+                    MinecraftServer.LOGGER.warn("Not storing chunk IO report due to low space on drive {}", filestore.name());
                     return;
                 }
 
-                CrashReportCategory crashReportCategory = report.addCategory("Chunk Info");
-                crashReportCategory.setDetail("Level", key::level);
-                crashReportCategory.setDetail("Dimension", () -> key.dimension().location().toString());
-                crashReportCategory.setDetail("Storage", key::type);
-                crashReportCategory.setDetail("Position", pos::toString);
-                report.saveToFile(path2, ReportType.CHUNK_IO_ERROR);
-                LOGGER.info("Saved details to {}", report.getSaveFile());
-            } catch (Exception var11) {
-                LOGGER.warn("Failed to store chunk IO exception", (Throwable)var11);
+                CrashReportCategory crashreportsystemdetails = report.addCategory("Chunk Info");
+
+                Objects.requireNonNull(key);
+                crashreportsystemdetails.setDetail("Level", key::level);
+                crashreportsystemdetails.setDetail("Dimension", () -> {
+                    return key.dimension().location().toString();
+                });
+                Objects.requireNonNull(key);
+                crashreportsystemdetails.setDetail("Storage", key::type);
+                Objects.requireNonNull(pos);
+                crashreportsystemdetails.setDetail("Position", pos::toString);
+                report.saveToFile(path1, ReportType.CHUNK_IO_ERROR);
+                MinecraftServer.LOGGER.info("Saved details to {}", report.getSaveFile());
+            } catch (Exception exception) {
+                MinecraftServer.LOGGER.warn("Failed to store chunk IO exception", exception);
             }
+
         });
     }
 
     @Override
     public void reportChunkLoadFailure(Throwable exception, RegionStorageInfo key, ChunkPos chunkPos) {
-        LOGGER.error("Failed to load chunk {},{}", chunkPos.x, chunkPos.z, exception);
+        MinecraftServer.LOGGER.error("Failed to load chunk {},{}", new Object[]{chunkPos.x, chunkPos.z, exception});
         this.storeChunkIoError(CrashReport.forThrowable(exception, "Chunk load failure"), chunkPos, key);
     }
 
     @Override
     public void reportChunkSaveFailure(Throwable exception, RegionStorageInfo key, ChunkPos chunkPos) {
-        LOGGER.error("Failed to save chunk {},{}", chunkPos.x, chunkPos.z, exception);
+        MinecraftServer.LOGGER.error("Failed to save chunk {},{}", new Object[]{chunkPos.x, chunkPos.z, exception});
         this.storeChunkIoError(CrashReport.forThrowable(exception, "Chunk save failure"), chunkPos, key);
     }
 
@@ -2004,16 +3029,14 @@
     }
 
     public static record ReloadableResources(CloseableResourceManager resourceManager, ReloadableServerResources managers) implements AutoCloseable {
-        @Override
+
         public void close() {
             this.resourceManager.close();
         }
     }
 
-    public static record ServerResourcePackInfo(UUID id, String url, String hash, boolean isRequired, @Nullable Component prompt) {
-    }
+    private static class TimeProfiler {
 
-    static class TimeProfiler {
         final long startNanos;
         final int startTick;
 
@@ -2022,7 +3045,7 @@
             this.startTick = tick;
         }
 
-        ProfileResults stop(long endTime, int endTick) {
+        ProfileResults stop(final long endTime, final int endTick) {
             return new ProfileResults() {
                 @Override
                 public List<ResultField> getTimes(String parentPath) {
@@ -2061,4 +3084,34 @@
             };
         }
     }
+
+    public static record ServerResourcePackInfo(UUID id, String url, String hash, boolean isRequired, @Nullable Component prompt) {
+
+    }
+
+    // Paper start - Add tick times API and /mspt command
+    public static class TickTimes {
+        private final long[] times;
+
+        public TickTimes(int length) {
+            times = new long[length];
+        }
+
+        void add(int index, long time) {
+            times[index % times.length] = time;
+        }
+
+        public long[] getTimes() {
+            return times.clone();
+        }
+
+        public double getAverage() {
+            long total = 0L;
+            for (long value : times) {
+                total += value;
+            }
+            return ((double) total / (double) times.length) * 1.0E-6D;
+        }
+    }
+    // Paper end - Add tick times API and /mspt command
 }
