--- a/net/minecraft/server/MinecraftServer.java
+++ b/net/minecraft/server/MinecraftServer.java
@@ -2,6 +2,9 @@
 
 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;
@@ -12,10 +15,10 @@
 import com.mojang.logging.LogUtils;
 import it.unimi.dsi.fastutil.longs.LongIterator;
 import java.awt.image.BufferedImage;
+import java.io.BufferedWriter;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.IOException;
-import java.io.Writer;
 import java.lang.management.ManagementFactory;
 import java.lang.management.ThreadInfo;
 import java.lang.management.ThreadMXBean;
@@ -24,6 +27,7 @@
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.security.KeyPair;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Base64;
 import java.util.Collection;
@@ -33,6 +37,7 @@
 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;
@@ -44,6 +49,7 @@
 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;
@@ -62,6 +68,8 @@
 import net.minecraft.core.registries.Registries;
 import net.minecraft.data.worldgen.features.MiscOverworldFeatures;
 import net.minecraft.gametest.framework.GameTestTicker;
+import net.minecraft.nbt.NbtOps;
+import net.minecraft.nbt.Tag;
 import net.minecraft.network.chat.ChatDecorator;
 import net.minecraft.network.chat.ChatType;
 import net.minecraft.network.chat.Component;
@@ -71,7 +79,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;
@@ -103,6 +110,7 @@
 import net.minecraft.util.RandomSource;
 import net.minecraft.util.SignatureValidator;
 import net.minecraft.util.Unit;
+import net.minecraft.util.datafix.DataFixers;
 import net.minecraft.util.profiling.EmptyProfileResults;
 import net.minecraft.util.profiling.ProfileResults;
 import net.minecraft.util.profiling.ProfilerFiller;
@@ -136,21 +144,18 @@
 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.dimension.LevelStem;
-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.feature.ConfiguredFeature;
 import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
 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.LevelResource;
 import net.minecraft.world.level.storage.LevelStorageSource;
 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.storage.loot.ItemModifierManager;
@@ -161,7 +166,37 @@
 import org.apache.commons.lang3.Validate;
 import org.slf4j.Logger;
 
+// CraftBukkit start
+import com.mojang.datafixers.util.Pair;
+import com.mojang.serialization.DynamicOps;
+import com.mojang.serialization.Lifecycle;
+import java.util.Random;
+// import jline.console.ConsoleReader; // Paper
+import joptsimple.OptionSet;
+import net.minecraft.core.HolderLookup;
+import net.minecraft.resources.RegistryOps;
+import net.minecraft.server.bossevents.CustomBossEvents;
+import net.minecraft.server.dedicated.DedicatedServer;
+import net.minecraft.server.dedicated.DedicatedServerProperties;
+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.WorldDimensions;
+import net.minecraft.world.level.levelgen.presets.WorldPresets;
+import org.bukkit.Bukkit;
+import org.bukkit.craftbukkit.v1_19_R2.CraftServer;
+import org.bukkit.craftbukkit.v1_19_R2.Main;
+import org.bukkit.craftbukkit.v1_19_R2.util.CraftChatMessage;
+import org.bukkit.craftbukkit.v1_19_R2.util.LazyPlayerSet;
+import org.bukkit.event.player.AsyncPlayerChatPreviewEvent;
+import org.bukkit.event.server.ServerLoadEvent;
+// CraftBukkit end
+
+import co.aikar.timings.MinecraftTimings; // Paper
+
 public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTask> implements CommandSource, AutoCloseable {
+
+    private static MinecraftServer SERVER; // Paper
     public static final Logger LOGGER = LogUtils.getLogger();
     public static final String VANILLA_BRAND = "vanilla";
     private static final float AVERAGE_TICK_TIME_SMOOTHING = 0.8F;
@@ -182,28 +217,26 @@
     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;
     private boolean debugCommandProfilerDelayStart;
     private ServerConnectionListener connection;
     public final ChunkProgressListenerFactory progressListenerFactory;
-    private final ServerStatus status = new ServerStatus();
-    private final RandomSource random = RandomSource.create();
+    private final ServerStatus status;
+    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;
     protected final Proxy proxy;
@@ -213,8 +246,14 @@
     private boolean allowFlight;
     @Nullable
     private String motd;
+    @Nullable private net.kyori.adventure.text.Component cachedMotd; // Paper
     private int playerIdleTimeout;
-    public final long[] tickTimes = new long[100];
+    public final long[] tickTimes;
+    // Paper start
+    public final TickTimes tickTimes5s = new TickTimes(100);
+    public final TickTimes tickTimes10s = new TickTimes(200);
+    public final TickTimes tickTimes60s = new TickTimes(1200);
+    // Paper end
     @Nullable
     private KeyPair keyPair;
     @Nullable
@@ -225,16 +264,16 @@
     protected final Services services;
     private long lastServerStatus;
     public final Thread serverThread;
-    private long nextTickTime = Util.getMillis();
+    private long nextTickTime;
     private long delayedTasksMaxNextTickTime;
     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 final FrameTimer frameTimer = new FrameTimer();
+    private final FrameTimer frameTimer;
     private boolean enforceWhitelist;
     private float averageTickTime;
     public final Executor executor;
@@ -245,184 +284,460 @@
     protected WorldData worldData;
     private volatile boolean isSaving;
 
+    // CraftBukkit start
+    public final WorldLoader.DataLoadContext worldLoader;
+    public org.bukkit.craftbukkit.v1_19_R2.CraftServer server;
+    public OptionSet options;
+    public org.bukkit.command.ConsoleCommandSender console;
+    public org.bukkit.command.RemoteConsoleCommandSender remoteConsole;
+    //public ConsoleReader reader; // Paper
+    public static int currentTick = 0; // Paper - Further improve tick loop
+    public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
+    public int autosavePeriod;
+    public Commands vanillaCommandDispatcher;
+    public boolean forceTicks; // Paper
+    // 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
+    public final double[] recentTps = new double[ 3 ];
+    // Spigot end
+    public final io.papermc.paper.configuration.PaperConfigurations paperConfigurations;
+    public static long currentTickLong = 0L; // Paper
+
+    public volatile Thread shutdownThread; // Paper
+    public volatile boolean abnormalExit = false; // Paper
+    public boolean isIteratingOverLevels = false; // Paper
+
     public static <S extends MinecraftServer> S spin(Function<Thread, S> serverFactory) {
-        AtomicReference<S> atomicReference = new AtomicReference<>();
-        Thread thread = new Thread(() -> {
-            atomicReference.get().runServer();
+        AtomicReference<S> atomicreference = new AtomicReference();
+        Thread thread = new io.papermc.paper.util.TickThread(() -> { // Paper - rewrite chunk system
+            ((MinecraftServer) atomicreference.get()).runServer();
         }, "Server thread");
-        thread.setUncaughtExceptionHandler((threadx, throwable) -> {
-            LOGGER.error("Uncaught exception in server thread", throwable);
+
+        thread.setUncaughtExceptionHandler((thread1, throwable) -> {
+            MinecraftServer.LOGGER.error("Uncaught exception in server thread", throwable);
         });
         if (Runtime.getRuntime().availableProcessors() > 4) {
             thread.setPriority(8);
         }
 
-        S minecraftServer = serverFactory.apply(thread);
-        atomicReference.set(minecraftServer);
+        S s0 = serverFactory.apply(thread); // CraftBukkit - decompile error
+
+        atomicreference.set(s0);
+        thread.setPriority(Thread.NORM_PRIORITY+2); // Paper - boost priority
         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) {
+    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.status = new ServerStatus();
+        this.random = RandomSource.create();
+        this.port = -1;
+        this.levels = Maps.newLinkedHashMap();
+        this.running = true;
+        this.tickTimes = new long[100];
+        this.nextTickTime = Util.getMillis();
+        this.scoreboard = new ServerScoreboard(this);
+        this.customBossEvents = new CustomBossEvents();
+        this.frameTimer = new FrameTimer();
+        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.progressListenerFactory = worldGenerationProgressListenerFactory;
-            this.storageSource = session;
-            this.playerDataStorage = session.createPlayerStorage();
-            this.fixerUpper = dataFixer;
+            // this.connection = new ServerConnection(this); // Spigot
+            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();
         }
+        // CraftBukkit start
+        this.options = options;
+        this.worldLoader = worldLoader;
+        this.vanillaCommandDispatcher = worldstem.dataPackResources().commands; // CraftBukkit
+        // 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
+        Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.v1_19_R2.util.ServerShutdownThread(this));
+        this.paperConfigurations = services.paperConfigurations(); // Paper
     }
+    // CraftBukkit end
 
     private void readScoreboard(DimensionDataStorage persistentStateManager) {
-        persistentStateManager.computeIfAbsent(this.getScoreboard()::createData, this.getScoreboard()::createData, "scoreboard");
+        ServerScoreboard scoreboardserver = this.getScoreboard();
+
+        Objects.requireNonNull(scoreboardserver);
+        Function<net.minecraft.nbt.CompoundTag, net.minecraft.world.scores.ScoreboardSaveData> function = scoreboardserver::createData; // CraftBukkit - decompile error
+        ServerScoreboard scoreboardserver1 = this.getScoreboard();
+
+        Objects.requireNonNull(scoreboardserver1);
+        persistentStateManager.computeIfAbsent(function, scoreboardserver1::createData, "scoreboard");
     }
 
     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(11);
-        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() {
-    }
+    // CraftBukkit start
+    private void loadWorld0(String s) {
+        LevelStorageSource.LevelStorageAccess worldSession = this.storageSource;
 
-    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);
-        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);
+        Registry<LevelStem> dimensions = this.registries.compositeAccess().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.isNetherEnabled()) {
+                    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();
+            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 var22) {
-                CrashReport crashReport = CrashReport.forThrowable(var22, "Exception initializing level");
 
                 try {
-                    serverLevel.fillReportDetails(crashReport);
-                } catch (Throwable var21) {
+                    worldSession = LevelStorageSource.createDefault(this.server.getWorldContainer().toPath()).createAccess(name, dimensionKey);
+                } catch (IOException ex) {
+                    throw new RuntimeException(ex);
                 }
+            }
 
-                throw new ReportedException(crashReport);
+            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);
+            DynamicOps<Tag> dynamicops = RegistryOps.create(NbtOps.INSTANCE, (HolderLookup.Provider) worldloader_a.datapackWorldgen());
+            Pair<WorldData, WorldDimensions.Complete> pair = worldSession.getDataTag(dynamicops, worldloader_a.dataConfiguration(), iregistry, worldloader_a.datapackWorldgen().allRegistriesLifecycle());
+
+            if (pair != null) {
+                worlddata = (PrimaryLevelData) pair.getFirst();
+            } 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)
+            // Paper - move down
 
-            serverLevelData.setInitialized(true);
+            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.v1_19_R2.generator.CraftWorldInfo(iworlddataserver, worldSession, org.bukkit.World.Environment.getEnvironment(dimension), worlddimension.type().value(), worlddimension.generator(), this.registryAccess()); // Paper
+            if (biomeProvider == null && gen != null) {
+                biomeProvider = gen.getDefaultBiomeProvider(worldInfo);
+            }
+
+            // Paper start - fix and optimise world upgrading
+            if (options.has("forceUpgrade")) {
+                net.minecraft.server.Main.convertWorldButItWorks(
+                    dimensionKey, worldSession, DataFixers.getDataFixer(), worlddimension.generator().getTypeNameForDataFixer(), options.has("eraseCache")
+                );
+            }
+            // Paper end - fix and optimise world upgrading
+            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(11);
+
+                world = new ServerLevel(this, this.executor, worldSession, iworlddataserver, worldKey, worlddimension, worldloadlistener, flag, j, list, true, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+                DimensionDataStorage worldpersistentdata = world.getDataStorage();
+                this.readScoreboard(worldpersistentdata);
+                this.server.scoreboardManager = new org.bukkit.craftbukkit.v1_19_R2.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
+                this.commandStorage = new CommandStorage(worldpersistentdata);
+            } else {
+                ChunkProgressListener worldloadlistener = this.progressListenerFactory.create(11);
+                // 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, org.bukkit.World.Environment.getEnvironment(dimension), gen, biomeProvider);
+                // Paper end
+            }
+
+            worlddata.setModdedInfo(this.getServerModName(), this.getModdedStatus().shouldReportAsModified());
+            this.addLevel(world); // Paper - move up
+            this.initWorld(world, worlddata, worldData, worldoptions);
+
+            // Paper - move up
+            this.getPlayerList().addWorldborderListener(world);
+
+            if (worlddata.getCustomBossEvents() != null) {
+                this.getCustomBossEvents().load(worlddata.getCustomBossEvents());
+            }
+        }
+        this.forceDifficulty();
+        for (ServerLevel worldserver : this.getAllLevels()) {
+            this.prepareLevels(worldserver.getChunkSource().chunkMap.progressListener, worldserver);
+            //worldserver.entityManager.tick(); // SPIGOT-6526: Load pending entities so they are available to the API // Paper - rewrite chunk system, not required to "tick" anything
+            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());
+        // Paper start - 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
         }
 
-        for(Map.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);
-                worldBorder.addListener(new BorderChangeListener.DelegateBorderChangeListener(serverLevel2.getWorldBorder()));
-                this.levels.put(resourceKey2, serverLevel2);
+        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
+
+        this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD);
+        this.server.getPluginManager().callEvent(new ServerLoadEvent(ServerLoadEvent.LoadType.STARTUP));
+        this.connection.acceptConnections();
+    }
+    // CraftBukkit end
+
+    protected void forceDifficulty() {}
+
+    // CraftBukkit start
+    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 n = 5;
+            int i1 = -1;
+            boolean flag2 = true;
 
-            for(int o = 0; o < Mth.square(11); ++o) {
+            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 p = l;
-                    l = -m;
-                    m = p;
+                    int k1 = l;
+
+                    l = -i1;
+                    i1 = k1;
                 }
 
                 j += l;
-                k += m;
+                k += i1;
             }
 
             if (bonusChest) {
-                world.registryAccess().registry(Registries.CONFIGURED_FEATURE).flatMap((featureRegistry) -> {
-                    return featureRegistry.getHolder(MiscOverworldFeatures.BONUS_CHEST);
-                }).ifPresent((feature) -> {
-                    feature.value().place(world, serverChunkCache.getGenerator(), world.random, new BlockPos(worldProperties.getXSpawn(), worldProperties.getYSpawn(), worldProperties.getZSpawn()));
+                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, new BlockPos(worldProperties.getXSpawn(), worldProperties.getYSpawn(), worldProperties.getZSpawn()));
                 });
             }
 
@@ -432,50 +747,75 @@
     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 {}", (Object)serverLevel.dimension().location());
-        BlockPos blockPos = serverLevel.getSharedSpawnPos();
-        worldGenerationProgressListener.updateSpawnPos(new ChunkPos(blockPos));
-        ServerChunkCache serverChunkCache = serverLevel.getChunkSource();
-        serverChunkCache.getLightEngine().setTaskPerBatch(500);
+    // CraftBukkit start
+    public void prepareLevels(ChunkProgressListener worldloadlistener, ServerLevel worldserver) {
+        ServerChunkCache chunkproviderserver = worldserver.getChunkSource(); // Paper
+        // WorldServer worldserver = this.overworld();
+        this.forceTicks = true;
+        // CraftBukkit end
+        if (worldserver.getWorld().getKeepSpawnInMemory()) { // Paper
+
+        MinecraftServer.LOGGER.info("Preparing start region for dimension {}", worldserver.dimension().location());
+        BlockPos blockposition = worldserver.getSharedSpawnPos();
+
+        worldloadlistener.updateSpawnPos(new ChunkPos(blockposition));
+        //ChunkProviderServer chunkproviderserver = worldserver.getChunkProvider(); // Paper - move up
+
+        chunkproviderserver.getLightEngine().setTaskPerBatch(500);
         this.nextTickTime = Util.getMillis();
-        serverChunkCache.addRegionTicket(TicketType.START, new ChunkPos(blockPos), 11, Unit.INSTANCE);
+        // Paper start - configurable spawn reason
+        int radiusBlocks = worldserver.paperConfig().spawn.keepSpawnLoadedRange * 16;
+        int radiusChunks = radiusBlocks / 16 + ((radiusBlocks & 15) != 0 ? 1 : 0);
+        int totalChunks = ((radiusChunks) * 2 + 1);
+        totalChunks *= totalChunks;
+        worldloadlistener.setChunkRadius(radiusBlocks / 16);
 
-        while(serverChunkCache.getTickingGenerated() != 441) {
-            this.nextTickTime = Util.getMillis() + 10L;
-            this.waitUntilNextTick();
+        worldserver.addTicketsForSpawn(radiusBlocks, blockposition);
+        // Paper end
+
+        // this.nextTickTime = SystemUtils.getMillis() + 10L;
+        this.executeModerately();
+        // Iterator iterator = this.levels.values().iterator();
         }
 
-        this.nextTickTime = Util.getMillis() + 10L;
-        this.waitUntilNextTick();
+        if (true) {
+            ServerLevel worldserver1 = worldserver;
+            // CraftBukkit end
+            ForcedChunksSavedData forcedchunk = (ForcedChunksSavedData) worldserver1.getDataStorage().get(ForcedChunksSavedData::load, "chunks");
 
-        for(ServerLevel serverLevel2 : this.levels.values()) {
-            ForcedChunksSavedData forcedChunksSavedData = serverLevel2.getDataStorage().get(ForcedChunksSavedData::load, "chunks");
-            if (forcedChunksSavedData != null) {
-                LongIterator longIterator = forcedChunksSavedData.getChunks().iterator();
+            if (forcedchunk != null) {
+                LongIterator longiterator = forcedchunk.getChunks().iterator();
 
-                while(longIterator.hasNext()) {
-                    long l = longIterator.nextLong();
-                    ChunkPos chunkPos = new ChunkPos(l);
-                    serverLevel2.getChunkSource().updateChunkForced(chunkPos, true);
+                while (longiterator.hasNext()) {
+                    long i = longiterator.nextLong();
+                    ChunkPos chunkcoordintpair = new ChunkPos(i);
+
+                    worldserver1.getChunkSource().updateChunkForced(chunkcoordintpair, true);
                 }
             }
         }
 
-        this.nextTickTime = Util.getMillis() + 10L;
-        this.waitUntilNextTick();
-        worldGenerationProgressListener.stop();
-        serverChunkCache.getLightEngine().setTaskPerBatch(5);
-        this.updateMobSpawningFlags();
+        // CraftBukkit start
+        // this.nextTickTime = SystemUtils.getMillis() + 10L;
+        this.executeModerately();
+        // CraftBukkit end
+        if (worldserver.getWorld().getKeepSpawnInMemory()) worldloadlistener.stop(); // Paper
+        chunkproviderserver.getLightEngine().setTaskPerBatch(worldserver.paperConfig().misc.lightQueueSize); // Paper - increase light queue size
+        // 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() {
@@ -493,44 +833,65 @@
     public abstract boolean shouldRconBroadcast();
 
     public boolean saveAllChunks(boolean suppressLogs, boolean flush, boolean force) {
-        boolean bl = false;
+        // Paper start - rewrite chunk system - add close param
+        // This allows us to avoid double saving chunks by closing instead of saving then closing
+        return this.saveAllChunks(suppressLogs, flush, force, false);
+    }
+    public boolean saveAllChunks(boolean suppressLogs, boolean flush, boolean force, boolean close) {
+        // Paper end - rewrite chunk system - 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((ProgressListener)null, flush, serverLevel.noSave && !force);
-            bl = true;
+            // Paper start - rewrite chunk system
+            worldserver.save((ProgressListener) null, flush, worldserver.noSave && !force, close);
+            if (flush) {
+                MinecraftServer.LOGGER.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", worldserver.getChunkSource().chunkMap.getStorageName());
+            }
+            // Paper end - rewrite chunk system
         }
 
-        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.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", (Object)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()); // Paper - move up
             }
 
-            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(); // Diff on change
+            flag3 = this.saveAllChunks(suppressLogs, flush, force);
         } finally {
             this.isSaving = false;
         }
 
-        return var4;
+        return flag3;
     }
 
     @Override
@@ -538,67 +899,108 @@
         this.stopServer();
     }
 
+    // CraftBukkit start
+    private boolean hasStopped = false;
+    public volatile boolean hasFullyShutdown = false; // Paper
+    private boolean hasLoggedStop = 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
+        // Paper start - kill main thread, and kill it hard
+        shutdownThread = Thread.currentThread();
+        org.spigotmc.WatchdogThread.doStop(); // Paper
+        if (!isSameThread()) {
+            MinecraftServer.LOGGER.info("Stopping main thread (Ignore any thread death message you see! - DO NOT REPORT THREAD DEATH TO PAPER)");
+            while (this.getRunningThread().isAlive()) {
+                this.getRunningThread().stop();
+                try {
+                    Thread.sleep(1);
+                } catch (InterruptedException e) {}
+            }
+        }
+        // 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 - Shutdown and don't bother finishing
+        MinecraftTimings.stopServer(); // Paper
+        // CraftBukkit start
+        if (this.server != null) {
+            this.server.disablePlugins();
+            this.server.waitForAsyncTasksShutdown(); // Paper
+        }
+        // CraftBukkit end
         if (this.getConnection() != null) {
             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");
-
-        for(ServerLevel serverLevel : this.getAllLevels()) {
-            if (serverLevel != null) {
-                serverLevel.noSave = false;
-            }
-        }
+        MinecraftServer.LOGGER.info("Saving worlds");
+        Iterator iterator = this.getAllLevels().iterator();
 
-        while(this.levels.values().stream().anyMatch((world) -> {
-            return world.getChunkSource().chunkMap.hasWork();
-        })) {
-            this.nextTickTime = Util.getMillis() + 1L;
+        ServerLevel worldserver;
 
-            for(ServerLevel serverLevel2 : this.getAllLevels()) {
-                serverLevel2.getChunkSource().removeTicketsOnClosing();
-                serverLevel2.getChunkSource().tick(() -> {
-                    return true;
-                }, false);
+        while (iterator.hasNext()) {
+            worldserver = (ServerLevel) iterator.next();
+            if (worldserver != null) {
+                worldserver.noSave = 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, false, true); // Paper - rewrite chunk system - move closing into here
 
         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
+        }
+        // Spigot end
+        // Paper start - move final shutdown items here
+        LOGGER.info("Flushing Chunk IO");
+        io.papermc.paper.chunk.system.io.RegionFileIOThread.close(true); // Paper // Paper - rewrite chunk system
+        LOGGER.info("Closing Thread Pool");
+        Util.shutdownExecutors(); // Paper
+        LOGGER.info("Closing Server");
+        try {
+            net.minecrell.terminalconsole.TerminalConsoleAppender.close(); // Paper - Use TerminalConsoleAppender
+        } catch (Exception e) {
+        }
+        io.papermc.paper.log.CustomLogManager.forceReset(); // Paper - Reset loggers after shutdown
+        this.onServerExit();
+        // Paper end
     }
 
     public String getLocalIp() {
@@ -614,19 +1016,88 @@
     }
 
     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
+        if (isDebugging()) io.papermc.paper.util.TraceUtil.dumpTraceForThread("Server stopped"); // Paper
+        // 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
+
+    public static volatile RuntimeException chunkSystemCrash; // Paper - rewrite chunk system
+
     protected void runServer() {
         try {
+            long serverStartTime = Util.getNanos(); // Paper
             if (!this.initServer()) {
                 throw new IllegalStateException("Failed to initialize server");
             }
@@ -637,20 +1108,65 @@
             this.status.setEnforcesSecureChat(this.enforceSecureProfile());
             this.updateStatusIcon(this.status);
 
-            while(this.running) {
-                long l = Util.getMillis() - this.nextTickTime;
-                if (l > 2000L && this.nextTickTime - this.lastOverloadWarning >= 15000L) {
-                    long m = l / 50L;
-                    LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", l, m);
-                    this.nextTickTime += m * 50L;
+            // Spigot start
+            // Paper start - move done tracking
+            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
+            String doneTime = String.format(java.util.Locale.ROOT, "%.3fs", (double) (Util.getNanos() - serverStartTime) / 1.0E9D);
+            LOGGER.info("Done ({})! For help, type \"help\"", doneTime);
+            // Paper end
+
+            org.spigotmc.WatchdogThread.tick(); // Paper
+            org.spigotmc.WatchdogThread.hasStarted = true; // Paper
+            Arrays.fill( recentTps, 20 );
+            long start = System.nanoTime(), curTime, tickSection = start; // Paper - Further improve server tick loop
+            lastTick = start - TICK_TIME; // Paper
+            while (this.running) {
+                // Paper start - rewrite chunk system
+                // guarantee that nothing can stop the server from halting if it can at least still tick
+                if (this.chunkSystemCrash != null) {
+                    throw this.chunkSystemCrash;
+                }
+                // Paper end - rewrite chunk system
+                long i = ((curTime = System.nanoTime()) / (1000L * 1000L)) - this.nextTickTime; // Paper
+
+                if (i > 5000L && this.nextTickTime - this.lastOverloadWarning >= 30000L) { // CraftBukkit
+                    long j = i / 50L;
+
+                    if (this.server.getWarnOnOverload()) // CraftBukkit
+                    MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", i, j);
+                    this.nextTickTime += j * 50L;
                     this.lastOverloadWarning = this.nextTickTime;
                 }
 
+                ++MinecraftServer.currentTickLong; // Paper
+                if ( ++MinecraftServer.currentTick % MinecraftServer.SAMPLE_INTERVAL == 0 )
+                {
+                    final long diff = curTime - tickSection;
+                    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();
+                    // Paper end
+                    tickSection = curTime;
+                }
+                // Spigot end
+
                 if (this.debugCommandProfilerDelayStart) {
                     this.debugCommandProfilerDelayStart = false;
                     this.debugCommandProfiler = new MinecraftServer.TimeProfiler(Util.getNanos(), this.tickCount);
                 }
 
+                //MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit // Paper - don't overwrite current tick time
+                lastTick = curTime;
                 this.nextTickTime += 50L;
                 this.startMetricsRecordingTick();
                 this.profiler.push("tick");
@@ -664,30 +1180,51 @@
                 this.isReady = true;
                 JvmProfiler.INSTANCE.onServerTick(this.averageTickTime);
             }
-        } catch (Throwable var44) {
-            LOGGER.error("Encountered an unexpected exception", var44);
-            CrashReport crashReport = constructOrExtractCrashReport(var44);
-            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);
+            // Spigot Start
+            if ( throwable.getCause() != null )
+            {
+                MinecraftServer.LOGGER.error( "\tCause of unexpected exception was", throwable.getCause() );
+            }
+            // Spigot End
+            CrashReport crashreport = MinecraftServer.constructOrExtractCrashReport(throwable);
+
+            this.fillSystemReport(crashreport.getSystemReport());
             File file = new File(new File(this.getServerDirectory(), "crash-reports"), "crash-" + Util.getFilenameFormattedDateTime() + "-server.txt");
-            if (crashReport.saveToFile(file)) {
-                LOGGER.error("This crash report has been saved to: {}", (Object)file.getAbsolutePath());
+
+            if (crashreport.saveToFile(file)) {
+                MinecraftServer.LOGGER.error("This crash report has been saved to: {}", file.getAbsolutePath());
             } 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 var42) {
-                LOGGER.error("Exception stopping the server", var42);
+            } 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
+                //this.onServerExit(); // Paper - moved into stop
             }
 
         }
@@ -695,94 +1232,137 @@
     }
 
     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) {
+                ReportedException reportedexception1 = (ReportedException) throwable1;
+
+                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.getMillis() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTime : this.nextTickTime);
+        // Paper start
+        if (this.forceTicks) {
+            return true;
+        }
+        // Paper end
+        // CraftBukkit start
+        if (isOversleep) return canOversleep();// Paper - because of our changes, this logic is broken
+        return this.forceTicks || this.runningTask() || Util.getMillis() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTime : this.nextTickTime);
     }
 
-    protected void waitUntilNextTick() {
+    // Paper start
+    boolean isOversleep = false;
+    private boolean canOversleep() {
+        return this.mayHaveDelayedTasks && Util.getMillis() < this.delayedTasksMaxNextTickTime;
+    }
+
+    private boolean canSleepForTickNoOversleep() {
+        return this.forceTicks || this.runningTask() || Util.getMillis() < this.nextTickTime;
+    }
+    // Paper end
+
+    private void executeModerately() {
         this.runAllTasks();
+        java.util.concurrent.locks.LockSupport.parkNanos("executing tasks", 1000L);
+    }
+    // CraftBukkit end
+
+    protected void waitUntilNextTick() {
+        //this.executeAll(); // Paper - move this into the tick method for timings
         this.managedBlock(() -> {
-            return !this.haveTime();
+            return !this.canSleepForTickNoOversleep(); // Paper - move oversleep into full server tick
         });
     }
 
     @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.executeMidTickTasks(); // Paper - execute chunk tasks mid tick
             return true;
         } else {
+            boolean ret = false; // Paper - force execution of all worlds, do not just bias the first
             if (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 void updateStatusIcon(ServerStatus metadata) {
         Optional<File> optional = Optional.of(this.getFile("server-icon.png")).filter(File::isFile);
+
         if (!optional.isPresent()) {
             optional = this.storageSource.getIconFile().map(Path::toFile).filter(File::isFile);
         }
 
         optional.ifPresent((file) -> {
             try {
-                BufferedImage bufferedImage = ImageIO.read(file);
-                Validate.validState(bufferedImage.getWidth() == 64, "Must be 64 pixels wide");
-                Validate.validState(bufferedImage.getHeight() == 64, "Must be 64 pixels high");
-                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-                ImageIO.write(bufferedImage, "PNG", byteArrayOutputStream);
-                byte[] bs = Base64.getEncoder().encode(byteArrayOutputStream.toByteArray());
-                metadata.setFavicon("data:image/png;base64," + new String(bs, StandardCharsets.UTF_8));
-            } catch (Exception var5) {
-                LOGGER.error("Couldn't load server icon", (Throwable)var5);
+                BufferedImage bufferedimage = ImageIO.read(file);
+
+                Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
+                Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
+                ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
+
+                ImageIO.write(bufferedimage, "PNG", bytearrayoutputstream);
+                byte[] abyte = Base64.getEncoder().encode(bytearrayoutputstream.toByteArray());
+                String s = new String(abyte, StandardCharsets.UTF_8);
+
+                metadata.setFavicon("data:image/png;base64," + s);
+            } catch (Exception exception) {
+                MinecraftServer.LOGGER.error("Couldn't load server icon", exception);
             }
 
         });
@@ -796,95 +1376,209 @@
         return new File(".");
     }
 
-    public void onServerCrash(CrashReport report) {
-    }
+    public void onServerCrash(CrashReport report) {}
 
-    public void onServerExit() {
-    }
+    public void onServerExit() {}
 
     public void tickServer(BooleanSupplier shouldKeepTicking) {
-        long l = Util.getNanos();
+        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
+        new com.destroystokyo.paper.event.server.ServerTickStartEvent(this.tickCount+1).callEvent(); // Paper
+
         ++this.tickCount;
         this.tickChildren(shouldKeepTicking);
-        if (l - this.lastServerStatus >= 5000000000L) {
-            this.lastServerStatus = l;
+        if (i - this.lastServerStatus >= 5000000000L) {
+            this.lastServerStatus = i;
             this.status.setPlayers(new ServerStatus.Players(this.getMaxPlayers(), this.getPlayerCount()));
             if (!this.hidesOnlinePlayers()) {
-                GameProfile[] gameProfiles = new GameProfile[Math.min(this.getPlayerCount(), 12)];
-                int i = Mth.nextInt(this.random, 0, this.getPlayerCount() - gameProfiles.length);
+                GameProfile[] agameprofile = new GameProfile[Math.min(this.getPlayerCount(), org.spigotmc.SpigotConfig.playerSample)]; // Paper
+                int j = Mth.nextInt(this.random, 0, this.getPlayerCount() - agameprofile.length);
 
-                for(int j = 0; j < gameProfiles.length; ++j) {
-                    ServerPlayer serverPlayer = this.playerList.getPlayers().get(i + j);
-                    if (serverPlayer.allowsListing()) {
-                        gameProfiles[j] = serverPlayer.getGameProfile();
+                for (int k = 0; k < agameprofile.length; ++k) {
+                    ServerPlayer entityplayer = (ServerPlayer) this.playerList.getPlayers().get(j + k);
+
+                    if (entityplayer.allowsListing()) {
+                        agameprofile[k] = entityplayer.getGameProfile();
                     } else {
-                        gameProfiles[j] = ANONYMOUS_PLAYER_PROFILE;
+                        agameprofile[k] = MinecraftServer.ANONYMOUS_PLAYER_PROFILE;
                     }
                 }
 
-                Collections.shuffle(Arrays.asList(gameProfiles));
-                this.status.getPlayers().setSample(gameProfiles);
+                Collections.shuffle(Arrays.asList(agameprofile));
+                this.status.getPlayers().setSample(agameprofile);
             }
         }
 
-        if (this.tickCount % 6000 == 0) {
-            LOGGER.debug("Autosave started");
-            this.profiler.push("save");
-            this.saveEverything(true, false, false);
-            this.profiler.pop();
-            LOGGER.debug("Autosave finished");
+        // 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
+        io.papermc.paper.util.CachedLists.reset(); // Paper
+        // Paper start - move executeAll() into full server tick timing
+        try (co.aikar.timings.Timing ignored = MinecraftTimings.processTasksTimer.startTiming()) {
+            this.runAllTasks();
+        }
+        // Paper end
+        // Paper start
+        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();
+        // Paper end
         this.profiler.push("tallying");
-        long m = this.tickTimes[this.tickCount % 100] = Util.getNanos() - l;
-        this.averageTickTime = this.averageTickTime * 0.8F + (float)m / 1000000.0F * 0.19999999F;
-        long n = Util.getNanos();
-        this.frameTimer.logFrameDuration(n - l);
+        long l = this.tickTimes[this.tickCount % 100] = Util.getNanos() - i;
+
+        this.averageTickTime = this.averageTickTime * 0.8F + (float) l / 1000000.0F * 0.19999999F;
+        long i1 = Util.getNanos();
+
+        // Paper start
+        tickTimes5s.add(this.tickCount, l);
+        tickTimes10s.add(this.tickCount, l);
+        tickTimes60s.add(this.tickCount, l);
+        // Paper end
+
+        this.frameTimer.logFrameDuration(i1 - i);
         this.profiler.pop();
+        org.spigotmc.WatchdogThread.tick(); // Spigot
+        co.aikar.timings.TimingsManager.FULL_SERVER_TICK.stopTiming(); // Paper
     }
 
     public void tickChildren(BooleanSupplier shouldKeepTicking) {
+        MinecraftTimings.bukkitSchedulerTimer.startTiming(); // Spigot // Paper
+        this.server.getScheduler().mainThreadHeartbeat(this.tickCount); // CraftBukkit
+        MinecraftTimings.bukkitSchedulerTimer.stopTiming(); // Spigot // 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 - moved down
+
+        // 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 - optimize time updates
+        for (final ServerLevel world : this.getAllLevels()) {
+            final boolean doDaylight = world.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT);
+            final long dayTime = world.getDayTime();
+            long worldTime = world.getGameTime();
+            final ClientboundSetTimePacket worldPacket = new ClientboundSetTimePacket(worldTime, dayTime, doDaylight);
+            for (Player entityhuman : world.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
+        MinecraftTimings.timeUpdateTimer.stopTiming(); // Spigot // Paper
+
+        this.isIteratingOverLevels = true; // Paper
+        Iterator iterator = this.getAllLevels().iterator(); // Paper - move down
+        while (iterator.hasNext()) {
+            ServerLevel worldserver = (ServerLevel) iterator.next();
+            worldserver.hasPhysicsEvent =  org.bukkit.event.block.BlockPhysicsEvent.getHandlerList().getRegisteredListeners().length > 0; // Paper
+            worldserver.hasEntityMoveEvent =  io.papermc.paper.event.entity.EntityMoveEvent.getHandlerList().getRegisteredListeners().length > 0; // Paper
+            net.minecraft.world.level.block.entity.HopperBlockEntity.skipHopperEvents = worldserver.paperConfig().hopper.disableMoveEvent || org.bukkit.event.inventory.InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length == 0; // Paper
 
-        for(ServerLevel serverLevel : this.getAllLevels()) {
             this.profiler.push(() -> {
-                return serverLevel + " " + serverLevel.dimension().location();
+                return worldserver + " " + worldserver.dimension().location();
             });
+            /* Drop global time updates
             if (this.tickCount % 20 == 0) {
                 this.profiler.push("timeSync");
-                this.playerList.broadcastAll(new ClientboundSetTimePacket(serverLevel.getGameTime(), serverLevel.getDayTime(), serverLevel.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)), serverLevel.dimension());
+                this.playerList.broadcastAll(new PacketPlayOutUpdateTime(worldserver.getGameTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT)), worldserver.dimension());
                 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);
+                // Paper start
+                for (final io.papermc.paper.chunk.SingleThreadChunkRegionManager regionManager : worldserver.getChunkSource().chunkMap.regionManagers) {
+                    regionManager.recalculateRegions();
+                }
+                // Paper end
+                worldserver.timings.doTick.stopTiming(); // Spigot
+            } catch (Throwable throwable) {
+                // Spigot Start
+                CrashReport crashreport;
+                try {
+                    crashreport = CrashReport.forThrowable(throwable, "Exception ticking world");
+                } catch (Throwable t) {
+                    if (throwable instanceof ThreadDeath) { throw (ThreadDeath)throwable; } // Paper
+                    throw new RuntimeException("Error generating crash report", t);
+                }
+                // Spigot End
+
+                worldserver.fillReportDetails(crashreport);
+                throw new ReportedException(crashreport);
             }
 
             this.profiler.pop();
             this.profiler.pop();
+            worldserver.explosionDensityCache.clear(); // Paper - Optimize explosions
         }
+        this.isIteratingOverLevels = false; // Paper
 
         this.profiler.popPush("connection");
+        MinecraftTimings.connectionTimer.startTiming(); // Spigot
         this.getConnection().tick();
+        MinecraftTimings.connectionTimer.stopTiming(); // Spigot
         this.profiler.popPush("players");
+        MinecraftTimings.playerListTimer.startTiming(); // Spigot // Paper
         this.playerList.tick();
+        MinecraftTimings.playerListTimer.stopTiming(); // Spigot // Paper
         if (SharedConstants.IS_RUNNING_IN_IDE) {
             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.pop();
     }
@@ -910,13 +1604,29 @@
     }
 
     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();
@@ -944,7 +1654,7 @@
 
     @DontObfuscate
     public String getServerModName() {
-        return "vanilla";
+        return "Paper"; // Paper - Paper > // Spigot - Spigot > // CraftBukkit - cb > vanilla!
     }
 
     public SystemReport fillSystemReport(SystemReport details) {
@@ -953,17 +1663,21 @@
         });
         if (this.playerList != null) {
             details.setDetail("Player Count", () -> {
-                return this.playerList.getPlayerCount() + " / " + this.playerList.getMaxPlayers() + "; " + this.playerList.getPlayers();
+                int i = this.playerList.getPlayerCount();
+
+                return i + " / " + this.playerList.getMaxPlayers() + "; " + this.playerList.getPlayers();
             });
         }
 
         details.setDetail("Data Packs", () -> {
-            return this.packRepository.getSelectedPacks().stream().map((profile) -> {
-                return profile.getId() + (profile.getCompatibility().isCompatible() ? "" : " (incompatible)");
+            return (String) this.packRepository.getSelectedPacks().stream().map((resourcepackloader) -> {
+                String s = resourcepackloader.getId();
+
+                return s + (resourcepackloader.getCompatibility().isCompatible() ? "" : " (incompatible)");
             }).collect(Collectors.joining(", "));
         });
         details.setDetail("Enabled Feature Flags", () -> {
-            return FeatureFlags.REGISTRY.toNames(this.worldData.enabledFeatures()).stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
+            return (String) FeatureFlags.REGISTRY.toNames(this.worldData.enabledFeatures()).stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
         });
         details.setDetail("World Generation", () -> {
             return this.worldData.worldGenSettingsLifecycle().toString();
@@ -985,7 +1699,7 @@
 
     @Override
     public void sendSystemMessage(Component message) {
-        LOGGER.info(message.getString());
+        MinecraftServer.LOGGER.info(io.papermc.paper.console.HexFormattingConverter.SERIALIZER.serialize(io.papermc.paper.adventure.PaperAdventure.asAdventure(message))); // Paper - Log message with colors
     }
 
     public KeyPair getKeyPair() {
@@ -1014,20 +1728,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 - remember 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
         }
     }
 
@@ -1036,8 +1753,12 @@
     }
 
     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))
         }
 
     }
@@ -1048,8 +1769,9 @@
     }
 
     private void sendDifficultyUpdate(ServerPlayer player) {
-        LevelData levelData = player.getLevel().getLevelData();
-        player.connection.send(new ClientboundChangeDifficultyPacket(levelData.getDifficulty(), levelData.isDifficultyLocked()));
+        LevelData worlddata = player.getLevel().getLevelData();
+
+        player.connection.send(new ClientboundChangeDifficultyPacket(worlddata.getDifficulty(), worlddata.isDifficultyLocked()));
     }
 
     public boolean isSpawningMonsters() {
@@ -1124,8 +1846,18 @@
         return this.motd;
     }
 
+    public net.kyori.adventure.text.Component getComponentMotd() {
+        net.kyori.adventure.text.Component component = cachedMotd;
+        if (this.motd != null && this.cachedMotd == null) {
+            component = cachedMotd = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(this.motd);
+        }
+
+        return component != null ? component : net.kyori.adventure.text.Component.empty();
+    }
+
     public void setMotd(String motd) {
         this.motd = motd;
+        this.cachedMotd = null; // Paper
     }
 
     public boolean isStopped() {
@@ -1148,7 +1880,7 @@
 
     @Nullable
     public ServerConnectionListener getConnection() {
-        return this.connection;
+        return this.connection == null ? this.connection = new ServerConnectionListener(this) : this.connection; // Spigot
     }
 
     public boolean isReady() {
@@ -1270,37 +2002,64 @@
         return this.functionManager;
     }
 
+    // Paper start - add cause
+    @Deprecated
     public CompletableFuture<Void> reloadResources(Collection<String> dataPacks) {
-        RegistryAccess.Frozen frozen = this.registries.getAccessForLoading(RegistryLayer.RELOADABLE);
-        CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> {
-            return 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, frozen, this.worldData.enabledFeatures(), this.isDedicatedServer() ? Commands.CommandSelection.DEDICATED : Commands.CommandSelection.INTEGRATED, this.getFunctionCompilationLevel(), this.executor, this).whenComplete((dataPackContents, throwable) -> {
+        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
+        RegistryAccess.Frozen iregistrycustom_dimension = this.registries.getAccessForLoading(RegistryLayer.RELOADABLE);
+        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, iregistrycustom_dimension, this.worldData.enabledFeatures(), this.isDedicatedServer() ? Commands.CommandSelection.DEDICATED : Commands.CommandSelection.INTEGRATED, this.getFunctionCompilationLevel(), this.executor, this).whenComplete((datapackresources, throwable) -> {
                 if (throwable != null) {
-                    closeableResourceManager.close();
+                    resourcemanager.close();
                 }
 
-            }).thenApply((dataPackContents) -> {
-                return new MinecraftServer.ReloadableResources(closeableResourceManager, dataPackContents);
+            }).thenApply((datapackresources) -> {
+                return new MinecraftServer.ReloadableResources(resourcemanager, datapackresources);
             });
-        }).thenAcceptAsync((resourceManagerHolder) -> {
+        }).thenAcceptAsync((minecraftserver_reloadableresources) -> {
             this.resources.close();
-            this.resources = resourceManagerHolder;
+            this.resources = minecraftserver_reloadableresources;
+            this.server.syncCommands(); // SPIGOT-5884: Lost on reload
             this.packRepository.setSelected(dataPacks);
-            WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(getSelectedPacks(this.packRepository), this.worldData.enabledFeatures());
-            this.worldData.setDataConfiguration(worldDataConfiguration);
+            WorldDataConfiguration worlddataconfiguration = new WorldDataConfiguration(MinecraftServer.getSelectedPacks(this.packRepository), this.worldData.enabledFeatures());
+
+            this.worldData.setDataConfiguration(worlddataconfiguration);
             this.resources.managers.updateRegistryTags(this.registryAccess());
-            this.getPlayerList().saveAll();
+            io.papermc.paper.registry.PaperRegistry.clearCaches(); // Paper
+            net.minecraft.world.item.alchemy.PotionBrewing.reload(); // Paper
+            new io.papermc.paper.event.server.ServerResourcesReloadedEvent(cause).callEvent(); // Paper
+            // Paper start
+            if (Thread.currentThread() != this.serverThread) {
+                return;
+            }
+            // this.getPlayerList().saveAll(); // Paper - we don't need to save everything, just advancements
+            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.v1_19_R2.block.data.CraftBlockData.reloadCache(); // Paper - cache block data strings, they can be defined by datapacks so refresh it here
         }, 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, DataPackConfig dataPackSettings, boolean safeMode, FeatureFlagSet enabledFeatures) {
@@ -1310,65 +2069,80 @@
             return WorldDataConfiguration.DEFAULT;
         } else {
             Set<String> set = Sets.newLinkedHashSet();
+            Iterator iterator = dataPackSettings.getEnabled().iterator();
 
-            for(String string : dataPackSettings.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 {}", (Object)string);
+                    MinecraftServer.LOGGER.warn("Missing data pack {}", s);
                 }
             }
 
-            for(Pack pack : resourcePackManager.getAvailablePacks()) {
-                String string2 = pack.getId();
-                if (!dataPackSettings.getDisabled().contains(string2)) {
-                    FeatureFlagSet featureFlagSet = pack.getRequestedFeatures();
-                    boolean bl = set.contains(string2);
-                    if (!bl && pack.getPackSource().shouldAddAutomatically()) {
-                        if (featureFlagSet.isSubsetOf(enabledFeatures)) {
-                            LOGGER.info("Found new data pack {}, loading it automatically", (Object)string2);
-                            set.add(string2);
+            iterator = resourcePackManager.getAvailablePacks().iterator();
+
+            while (iterator.hasNext()) {
+                Pack resourcepackloader = (Pack) iterator.next();
+                String s1 = resourcepackloader.getId();
+
+                if (!dataPackSettings.getDisabled().contains(s1)) {
+                    FeatureFlagSet featureflagset1 = resourcepackloader.getRequestedFeatures();
+                    boolean flag1 = set.contains(s1);
+
+                    if (!flag1 && resourcepackloader.getPackSource().shouldAddAutomatically()) {
+                        if (featureflagset1.isSubsetOf(enabledFeatures)) {
+                            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(enabledFeatures, featureFlagSet));
+                            MinecraftServer.LOGGER.info("Found new data pack {}, but can't load it due to missing features {}", s1, FeatureFlags.printMissingFlags(enabledFeatures, featureflagset1));
                         }
                     }
 
-                    if (bl && !featureFlagSet.isSubsetOf(enabledFeatures)) {
-                        LOGGER.warn("Pack {} requires features {} that are not enabled for this world, disabling pack.", string2, FeatureFlags.printMissingFlags(enabledFeatures, featureFlagSet));
-                        set.remove(string2);
+                    if (flag1 && !featureflagset1.isSubsetOf(enabledFeatures)) {
+                        MinecraftServer.LOGGER.warn("Pack {} requires features {} that are not enabled for this world, disabling pack.", s1, FeatureFlags.printMissingFlags(enabledFeatures, featureflagset1));
+                        set.remove(s1);
                     }
                 }
             }
 
             if (set.isEmpty()) {
-                LOGGER.info("No datapacks selected, forcing vanilla");
+                MinecraftServer.LOGGER.info("No datapacks selected, forcing vanilla");
                 set.add("vanilla");
             }
 
             resourcePackManager.setSelected(set);
-            DataPackConfig dataPackConfig = getSelectedPacks(resourcePackManager);
-            FeatureFlagSet featureFlagSet2 = resourcePackManager.getRequestedFeatureFlags();
-            return new WorldDataConfiguration(dataPackConfig, featureFlagSet2);
+            DataPackConfig datapackconfiguration1 = MinecraftServer.getSelectedPacks(resourcePackManager);
+            FeatureFlagSet featureflagset2 = resourcePackManager.getRequestedFeatureFlags();
+
+            return new WorldDataConfiguration(datapackconfiguration1, featureflagset2);
         }
     }
 
     private static DataPackConfig getSelectedPacks(PackRepository dataPackManager) {
         Collection<String> collection = dataPackManager.getSelectedIds();
         List<String> list = ImmutableList.copyOf(collection);
-        List<String> list2 = dataPackManager.getAvailableIds().stream().filter((name) -> {
-            return !collection.contains(name);
+        List<String> list1 = (List) dataPackManager.getAvailableIds().stream().filter((s) -> {
+            return !collection.contains(s);
         }).collect(ImmutableList.toImmutableList());
-        return new DataPackConfig(list, list2);
+
+        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 - white list 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(org.spigotmc.SpigotConfig.whitelistMessage, org.bukkit.event.player.PlayerKickEvent.Cause.WHITELIST); // Paper - use configurable message
                 }
             }
 
@@ -1384,8 +2158,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, (Entity)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
@@ -1451,16 +2226,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().isAllowCheatsForAllPlayers() ? 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().isAllowCheatsForAllPlayers() ? 4 : 0) : this.getOperatorUserPermissionLevel()));
         } else {
             return 0;
         }
@@ -1476,18 +2244,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(Map.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"));
@@ -1496,101 +2267,216 @@
             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.getAverageTickTime()));
-            writer.write(String.format(Locale.ROOT, "tick_times: %s\n", Arrays.toString(this.tickTimes)));
-            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.getAverageTickTime()));
+            bufferedwriter.write(String.format(Locale.ROOT, "tick_times: %s\n", Arrays.toString(this.tickTimes)));
+            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();
+            final GameRules gamerules = this.getGameRules();
+
             GameRules.visitGameRuleTypes(new GameRules.GameRuleTypeVisitor() {
                 @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.<T>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 {
-        label49: {
-            try (Writer writer = Files.newBufferedWriter(path)) {
-                label50: {
-                    List<NativeModuleLister.NativeModuleInfo> list;
+        BufferedWriter bufferedwriter = Files.newBufferedWriter(path);
+
+        label50:
+        {
+            try {
+                label51:
+                {
+                    ArrayList<NativeModuleLister.NativeModuleInfo> arraylist; // CraftBukkit - decompile error
+
                     try {
-                        list = Lists.newArrayList(NativeModuleLister.listModules());
-                    } catch (Throwable var7) {
-                        LOGGER.warn("Failed to list native modules", var7);
-                        break label50;
+                        arraylist = Lists.newArrayList(NativeModuleLister.listModules());
+                    } catch (Throwable throwable) {
+                        MinecraftServer.LOGGER.warn("Failed to list native modules", throwable);
+                        break label51;
                     }
 
-                    list.sort(Comparator.comparing((module) -> {
-                        return module.name;
+                    arraylist.sort(Comparator.comparing((nativemodulelister_a) -> {
+                        return nativemodulelister_a.name;
                     }));
-                    Iterator throwable = list.iterator();
+                    Iterator iterator = arraylist.iterator();
 
-                    while(true) {
-                        if (!throwable.hasNext()) {
-                            break label49;
+                    while (true) {
+                        if (!iterator.hasNext()) {
+                            break label50;
                         }
 
-                        NativeModuleLister.NativeModuleInfo nativeModuleInfo = (NativeModuleLister.NativeModuleInfo)throwable.next();
-                        writer.write(nativeModuleInfo.toString());
-                        writer.write(10);
+                        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();
+        }
+
+    }
+
+    // CraftBukkit start
+    @Override
+    public boolean isSameThread() {
+        return io.papermc.paper.util.TickThread.isTickThread(); // Paper - rewrite chunk system
+    }
+
+    public boolean isDebugging() {
+        return false;
     }
 
+    public static MinecraftServer getServer() {
+        return SERVER; // Paper
+    }
+    // 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) -> {
@@ -1617,9 +2503,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;
@@ -1667,7 +2553,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
@@ -1695,9 +2581,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;
         }
     }
 
@@ -1706,30 +2593,39 @@
     }
 
     public void logChatMessage(Component message, ChatType.Bound params, @Nullable String prefix) {
-        String string = params.decorate(message).getString();
+        String s1 = params.decorate(message).getString();
+
         if (prefix != null) {
-            LOGGER.info("[{}] {}", prefix, string);
+            MinecraftServer.LOGGER.info("[{}] {}", prefix, s1);
         } else {
-            LOGGER.info("{}", (Object)string);
+            MinecraftServer.LOGGER.info("{}", s1);
         }
 
     }
 
+    // CraftBukkit start
+    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 ChatDecorator getChatDecorator() {
-        return ChatDecorator.PLAIN;
+        // Paper start - moved to ChatPreviewProcessor
+        return ChatDecorator.create((sender, commandSourceStack, message) -> {
+            final io.papermc.paper.adventure.ChatDecorationProcessor processor = new io.papermc.paper.adventure.ChatDecorationProcessor(this, sender, commandSourceStack, message);
+            return processor.process();
+        });
+        // Paper end
+        // CraftBukkit end
     }
 
     public static record ReloadableResources(CloseableResourceManager resourceManager, ReloadableServerResources managers) implements AutoCloseable {
-        @Override
+
         public void close() {
             this.resourceManager.close();
         }
     }
 
-    public static record ServerResourcePackInfo(String url, String hash, boolean isRequired, @Nullable Component prompt) {
-    }
+    private static class TimeProfiler {
 
-    static class TimeProfiler {
         final long startNanos;
         final int startTick;
 
@@ -1777,4 +2673,104 @@
             };
         }
     }
+
+    public static record ServerResourcePackInfo(String url, String hash, boolean isRequired, @Nullable Component prompt) {
+
+    }
+
+    // Paper start
+    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
+
+    // Paper start - execute chunk tasks mid tick
+    static final long CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME = 25L * 1000L; // 25us
+    static final long MAX_CHUNK_EXEC_TIME = 1000L; // 1us
+
+    static final long TASK_EXECUTION_FAILURE_BACKOFF = 5L * 1000L; // 5us
+
+    private static long lastMidTickExecute;
+    private static long lastMidTickExecuteFailure;
+
+    private boolean tickMidTickTasks() {
+        // give all worlds a fair chance at by targetting 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 (ServerLevel world : this.getAllLevels()) {
+            long currTime = System.nanoTime();
+            if (currTime - world.lastMidTickExecuteFailure <= TASK_EXECUTION_FAILURE_BACKOFF) {
+                continue;
+            }
+            if (!world.getChunkSource().pollTask()) {
+                // we need to back off if this fails
+                world.lastMidTickExecuteFailure = currTime;
+            } else {
+                executed = true;
+            }
+        }
+
+        return executed;
+    }
+
+    public final void executeMidTickTasks() {
+        org.spigotmc.AsyncCatcher.catchOp("mid tick chunk task execution");
+        long startTime = System.nanoTime();
+        if ((startTime - lastMidTickExecute) <= CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME || (startTime - 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;
+        }
+
+        co.aikar.timings.MinecraftTimings.midTickChunkTasks.startTiming();
+        try {
+            for (;;) {
+                boolean moreTasks = this.tickMidTickTasks();
+                long currTime = System.nanoTime();
+                long diff = currTime - startTime;
+
+                if (!moreTasks || diff >= MAX_CHUNK_EXEC_TIME) {
+                    if (!moreTasks) {
+                        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
+                    }
+
+                    double overuseCount = (double)overuse/(double)MAX_CHUNK_EXEC_TIME;
+                    long extraSleep = (long)Math.round(overuseCount*CHUNK_TASK_QUEUE_BACKOFF_MIN_TIME);
+
+                    lastMidTickExecute = currTime + extraSleep;
+                    return;
+                }
+            }
+        } finally {
+            co.aikar.timings.MinecraftTimings.midTickChunkTasks.stopTiming();
+        }
+    }
+    // Paper end - execute chunk tasks mid tick
 }
