Отключить swap mac os big sur

Question: Q: Increase SWAP on macOS Big Sur (Macbook M1)

Is there possibility to increase swap on macOS Big Sur on Apple Silicon M1?

dynamic_pager has only -F parameter.

Posted on Feb 9, 2021 5:47 AM

All replies

Loading page content

Page content loaded

I’m not sure why you would want to increase swap usage, but it doesn’t appear to have the controls needed to set a minimum or maximum size.

macOS first tries to use all of the available memory (RAM) in your Mac before resorting to swap. This is because using swap results in lots of reads and writes on the internal SSD, slowly shortening its lifetime.

Feb 9, 2021 7:33 AM

The problem is, when macOS takes 8GB RAM and 8GB swap memory, it runs very slow.

The solution could be increasing swap memory.

Feb 9, 2021 7:37 AM

Possibly, but macOS will still try to first maximize RAM usage, since that is always faster (and safer) than the internal SSD.

The swapfile resides in a hidden APFS volume named «VM». This allows for the swapfile to grow or shrink as it needs.

Now, because APFS volumes can optionally have a minimum and/or maximum size, I wonder if somehow your VM volume has a maximum size of 8 GB. To resolve this issue, you’ll need to erase your VM volume from macOS Recovery:

  1. Start up in macOS Recovery.
  2. If prompted, authenticate with admin credentials.
  3. At the top of the screen, select Utilities -> Terminal.
  4. Type this command and hit Enter (Return): diskutil apfs eraseVolume VM -name VM -role V
  5. When the process is finished, restart your Mac. Swap should now (hopefully) be permitted to grow beyond 8 GB large if it ever needs to.

Feb 9, 2021 6:00 PM

I will check that today.

Could you please tell me, what is the risk?

For now I have checked: diskutil apfs list

APFS Volume Disk (Role): disk3s6 (VM)

Name: VM (Case-insensitive)

Mount Point: /System/Volumes/VM

Capacity Consumed: 8589979648 B (8.6 GB)

Maybe could I create the new VM volume with size 16GB or more?

Feb 9, 2021 11:06 PM

If done correctly, there should be no risk. But definitely back up your data before proceeding. AFAIK if macOS can’t find the correct VM volume at startup it will make a new one.

Also, APFS volumes are dynamic by default — they have no fixed size. When you erase the VM volume, it will have an initial size of 0, and will automatically grow and/or shrink as macOS adjusts swap usage.

The true size limit of the VM volume is the amount of free space on your Mac, as your startup disk and VM share free space with each other.

Feb 10, 2021 6:15 AM

I have done that command: diskutil apfs eraseVolume VM -name VM -role V

It is better, but I still have slowmotion, when too many swap is taken.

APFS Volume Disk (Role): disk3s6 (VM)

Name: VM (Case-insensitive)

Mount Point: /System/Volumes/VM

Capacity Consumed: 11811209216 B (11.8 GB)

Feb 12, 2021 6:33 AM

By definition, swap is always going to be slower than true memory (RAM).

Just out of curiosity, what process(es) is consuming that much memory? You might want to get EtreCheck from the App Store and post a text report here.

Feb 12, 2021 10:40 AM

I know that swap will be slower than RAM.

But if the swap is used less than 10GB (before it was 8GB), everything runs OK.

Feb 16, 2021 2:59 AM

The biggest problem is now, look at stats.

Feb 16, 2021 6:34 AM

Thanks for posting the report. The stats in Activity Monitor are worrying.

Looking at the report, a runaway process is using significant amounts of CPU performance (likely also the memory hog). I recommend starting up in Safe Mode to diagnose the issue:

  1. Shut down your MacBook Air (M1).
  2. Press and hold Touch ID until the screen says «Loading startup options».
  3. Select Macintosh HD, hold down the Shift key, and select «Continue in Safe Mode».

When in Safe Mode, no third party apps are permitted to run automatically. If the problem is related to an app, you should notice that initially (before any apps are opened), little to no swap is being used.

Now, open Activity Monitor, and proceed with the below test:

  1. Open an app that you commonly use.
  2. Check swap usage in Activity Monitor.
  3. If swap usage suddenly spikes, that app is the culprit.
  4. If swap usage remains normal, quit the open app, then open another commonly used app.
  5. Repeat steps 1-4 until you find the culprit.

To leave Safe Mode, restart your Mac.

Feb 16, 2021 9:23 PM

Use the Activity Monitor’s %CPU column sorted to show what process is hogging CPU usage:

Feb 16, 2021 10:39 PM

Thank you for the reply.

I think the CPU is not a problem here.

The computer is running slowly because of memory usage. On the Memory tab I can see the Safari cards with 2 opened pipedrive cards (https://pipedrive.com ), each taking 1-1.5 GB. Safari has killed that because of memory usage and now everything is OK.

I am using a lot of web-applications like Asana, Pipedrive, Microsoft Tasks or LinkedIn and I think that could be a problem.

Feb 16, 2021 10:47 PM

The problem is not with just one application.

The problem occurs when I open too much applications.

So it could not help if I open applications step-by-step.

Feb 19, 2021 2:56 AM

Start by completely removing CleanMyMac. It is unneeded because the macOS, catlike, has cleaned itself for the last two decades. ANY third-party app that claims to clean or maintain yourt Mac WILL slow it and can contribute the the problems you see. CCM is the likely cause of the «runaway process» flag.

Based on hundreds of other EtreCheck reports here, removing CMM improves performance. You also have a number of third party enhancements install. I would review those and see which you really need. Amphetamine an Insomniac may be fighting. More than one installed ad blocker has been suspected in slow computer reports here. Find the one you love and send the other to summer camp.

Читайте также:  Awesome window manager windows

    macOS Big Sur 11.1 (20C69)Â

    Time since boot: About 6 days

In the presence of a mere 8GB RAM, restarting the computer more often than every six days will nicely keep that SWAP issue under control.

Источник

Маковод — маководу #14: избавляем macOS Big Sur от лагов

Задача, обозначенная в названии статьи, встала передо мной вскоре после официального релиза macOS Big Sur в середине ноября 2020-го года. Почему? Да просто мой не самый стремный MacBook Pro 2015 года превратился в натуральный лагодром после обычного обновления с Catalina. Пользоваться было практически невозможно — анимации тормозили на ровном месте, ноутбук грелся до 85-90 просто при старте Safari. Не за такой ноут я отдавал ворох заработанных мною денег.

Но юзать новую ОС очень хотелось, так как мелких удобностей и полезностей в ней появилось просто уйма. Статистика расхода аккумулятора, общая «шторка» аля iPhone для всех коммуникаций, возможнось вывода в статус-бар почти всего, что только захочется. да и просто свежий дизайн всей системы. Всё это очень привлекало. Но тормоза.

Откатившись обратно на Catalina (кстати, пошаговая инструкция по откату есть здесь) , я решил подъехать на другой козе. Алгоритм описываю ниже. Он пригодится обладателям MacBook 2013-2015 модельных годов, включая Pro, Air, и даже 12-дюймовые. Метод подразумевает чистую установку системы и настройку ее почти с нуля, с максимально возможным сохранением личных данных. Установив Big Sur таким образом, я увидел совсем иную работу macOS — более легкую и быструю. Разница действительно заметна.


Это необходимо для того, чтобы перенести свои данные в новую ОС. Если важных данных у тебя нет, или они легко помещаются на флешку — этот пункт можно пропустить. Еще один вариант не создавать копию — установить Big Sur прямо рядом с основной системой. Я сделал именно так.

Кстати, обязательно заскринь или сфотографируй список своих программ — понадобится.

Чтобы установить Big Sur рядом с основной системой:

  • открой Дисковую утилиту;
  • выбери строку «Контейнер №. » (если в левом списке есть только две строчки «Macintosh HD» и «Macintosh HD — данные», то над этими строчками находим менюшку «Вид» и выбираем там «Показать все устройства»);
  • в верхней части окна нажми на значок «+» — это кнопка добавляет новый том для нашего «бигсура»; для простоты лучше назвать его аналогично названию новой macOS;
  • теперь открывай загруженный образ Big Sur двойным тапом;
  • жми «Продолжить» и «Принять» и обязательно выбери наш новый созданный том в качестве диска для установки системы;
  • далее следуй подсказкам программы установки;
  • после завершения установки пройди шаги активации, в том числе введи свой Apple ID.

В результате ты получишь на своем SSD сразу две macOS — свою прежнюю систему, и новую Big Sur, установленную начисто. Любая из этих систем остается полнофункциональной, в любую из них можно загрузиться и воспользоваться.
Если же свободного места (минимум 40Гб) на внутреннем SSD у тебя нет — нужно записать загрузочную флешку с macOS Big Sur, чтобы установить систему начисто с флешки.

Запись загрузочной флешки:

  • вставь в Mac флеш-накопитель минимум на 16Гб;
  • переименуй флешку в «BigSur» (тап на флешку на рабочем столе → Enter);
  • перемести загруженный файл macOS Big Sur в папку «Программы»;
  • открой Терминал;
  • введи (или copy-paste) вот эту строку:

sudo /Applications/Install\ macOS\ Big\ Sur.app/Contents/Resources/createinstallmedia —volume /Volumes/BigSur

  • нажми Enter, введи пароль администратора и подтверди действие буквой «y», если потребуется;
  • подожди около 20 минут (зависит от скорости флеш-накопителя);

Готово. Загрузочная флешка записана и можно приступать к установке.


Здесь две дорожки.

  • Если ты не создавал копию старой системы и установил новую ОС начисто с форматированием SSD — просто загружай и устанавливайнужные программы, настраивай окна, шрифты, иконки по своему вкусу.
  • Если ты создавал полную копию системы, либо выборочную копию своих файлов на флешку, либо ставил систему рядом с основной — алгоритм ниже для тебя.

Восстанавливаем свои данные из копии/флешки:

  • открой резервную копию в Finder, как обычный жесткий диск/флешку;
  • двумя пальцами нажми на значок Finder в док-панели и выбери «Новое окно»;
  • размести два окна рядом;
  • перемести папки с Загрузками, Документами и прочими своими файлами в соответствующие каталоги новой ОС;
  • не нужно перемещать папку пользователя целиком, папки с установленными программами, системные папки;
  • загрузи, установи и настрой необходимые приложения и программы вручную.

Восстанавливаем данные из старой системы:

  • открой раздел со старой системой в Finder (в большинстве случаев это Macintosh HD);
  • двумя пальцами нажми на значок Finder в док-панели и выбери «Новое окно»;
  • размести два окна рядом;
  • пройди по пути «Пользователи → имя пользователя»;
  • перемести папки с Загрузками, Документами и прочими своими файлами в соответствующие каталоги новой ОС;
  • не нужно перемещать папку пользователя целиком, папки с установленными программами, системные папки;
  • загрузи, установи и настрой необходимые приложения и программы вручную.

Готово.

В результате мы получили начисто установленную macOS Big Sur с нашими файлами, данными и настроенными для работы программами. Кроме того, в определенном случае у нас на SSD сохранилась наша старая macOS в замороженном виде. Если ты уверен, что не будешь ее использовать — можно удалить ее, удалив том в Дисковой утилите. Но я рекомендую оставить ее на пару недель, чтобы можно было без проблем вернуться, если Big Sur даже при таком сценарии настройки тебя не устроит.

Стоит заметить, что через определенное время система может начать работать медленнее — это объясняется тем, что она постепенно «утяжеляется» кэш-файлами и различными подкапотными связками между элементами ОС. Спустя две недели, моя Big Sur немножко замедлилась, но разница между просто обновленной и установленной заново системой всё еще остается ощутимой.

Источник

Mac Virtual Memory – What it is, the Swap Location, and How to Disable Swap in Mac OS X

I was asked recently about the Mac OS X swapfile, specifically how to disable Mac OS X swapping entirely. I decided I will take this opportunity to talk a bit about Mac virtual memory (swap), it’s location in the Mac file system, and also to explain how to disable it.

Mac OS X Swap aka Virtual Memory

You may recall that in older versions of Mac OS (OS 8 and 9) you could manually disable swapping, then called Virtual Memory, by just adjusting a setting in the Control Panels. Mac OS X is a bit different because it’s built on top of a unix core which relies heavily on swap files and paging for general memory and cache management. Because of this, swap is actually more important now than it was in prior versions of Mac OS.

Читайте также:  Замерить fps windows 10

Basically when your Mac needs memory it will push something that isn’t currently being used into a swapfile for temporary storage. When it needs accessing again, it will read the data from the swap file and back into memory. In a sense this can create unlimited memory, but it is significantly slower since it is limited by the speed of your hard disk, versus the near immediacy of reading data from RAM.

If you’re curious, you can check Mac OS X’s virtual memory usage using the ‘vm_stat’ command, or by using the Activity Monitor (often erroneously called the Mac task manager by Windows converts).

Mac OS X Swap File Location

If you’re curious where the swap files are stored on your Mac, they’re located at:

This directly also contains your sleepimage file, which is essentially what your Mac has been storing in memory prior to system sleep. This file is read again when you wake your Mac up to return to it’s previous state. Anyway, back to swap files in the same directory: they are named successively swapfile0, swapfile1, swapfile2, swapfile3, swapfile4, swapfile5. You can see them for yourself with the following command:

ls -lh /private/var/vm/swapfile*

The swapfiles are generally staggered in size, ranging from 64MB to 512MB.

Disable Mac OS X Paging / Swap

Caution: I would highly recommend against modifying how Mac OS X handles memory management and swap files. Unless you know exactly what you’re doing and why, this is not a recommended adjustment. Again, if you don’t know what you’re doing, do not mess around with Mac OS X’s swapfiles or paging ability!

In the Terminal, enter the following command. This will unload the dynamic pager from the Mac OS X kernel:

sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.dynamic_pager.plist

Again, this completely disables the Mac OS X paging ability, do not mess around with this for fun.

Your next step would be to remove the swapfiles that are currently stored, they are generally pretty large (it is your virtual memory after all) and take up a fair amount of disk space.

sudo rm /private/var/vm/swapfile*

That’s all there is to it.

Enjoy this tip? Subscribe to our newsletter!

Get more of our great Apple tips, tricks, and important news delivered to your inbox with the OSXDaily newsletter.

Thank you!

You have successfully joined our subscriber list.

36 Comments

I want to relocate /private/var/vm/ to a 16 gig optane
Can I relocate to a swap drive/ partition?

I’ve been getting “Mac OS X startup disk has no more space…” Messages for a week now with 100GB of space available. On restart the free space jumps back up to 160GB free but can drop to 100 in a matter of hours with almost nothing running. Using OmniDiskSweeper I found 47 swapfile(s), each over 1GB! As the swapfile(s) propagate, my Mac runs slower and slower, becoming almost useless until the “no more space…” messages forces a reboot. I’ve never had this problem before and have never seen the “no more space…” message before unless the free space dropped into the MB range, certainly not with 100GB free. Is there a fix for this?

What version of Mac OS X are you running? Is the Mac older or newer?

New Macs with SSD volumes should not slowdown as much when swap is used.

If you are running an older version of Mac OS X, and the Mac is new enough to support it, updating to a newer release may resolve the issue (Snow Leopard 10.6.8, Mavericks 10.9.5, El Capitan 10.11.3 are probably the best bets for Mac OS X overall)

$ du -sh /private/var/vm
6.1G /private/var/vm
$ ls -alt /private/var/vm
total 12713984
-rw——- 1 root wheel 1073741824 Jun 13 08:40 swapfile1
-rw——- 1 root wheel 1073741824 Jun 13 08:40 swapfile2
-rw——- 1 root wheel 1073741824 Jun 13 08:40 swapfile3
-rw——- 1 root wheel 1073741824 Jun 13 08:40 swapfile4
-rw——- 1 root wheel 1073741824 Jun 13 08:07 swapfile5
drwxr-xr-x 9 root wheel 306 Jun 13 08:07 .
-rw——- 1 root wheel 67108864 May 30 10:07 swapfile0
-rw——T 1 root wheel 1073741824 May 28 2014 sleepimage
drwxr-xr-x 27 root wheel 918 May 28 2014 ..
$ sudo dynamic_pager -L 1073741824
Password:
$ r ls
ls -alt /private/var/vm
total 2136216
drwxr-xr-x 4 root wheel 136 Jun 13 08:41 .
-rw——- 1 root wheel 20000000 Jun 13 08:41 swapfile0
-rw——T 1 root wheel 1073741824 May 28 2014 sleepimage
drwxr-xr-x 27 root wheel 918 May 28 2014 ..

Certainly does wipe out the swapfiles! But how to make it a
permanent configuration?

Can I change te location of swap file, for example creating a small partition? If yes, how?

Hey I wouldnt mess with the swap files because I wanted to save some space on my mac and it ended up freezing some days after. I had to restart it but it didn’t turn on. I had to take it to apple and had it reset. Maybe it was for something else, but just in case, dont delete them.

Thank you so much, this post gave me the info I needed to move my swap off the SSD and on to the secondary HD.
—-
Bdens

Setup:
Mac Mini 2011 2.5, 8g Ram, 2 HD mod, and Arctic silver 5 – thermal paste

P.S. Apple, PLEASE use better thermal paste and Apply it correctly I lost 10c doing this!

three_jeeps is absolutely right, guys — if you disable virtual memory, you’re going to have a bad time.

Seriously, though, unless you’re doing arcane, deep black magic stuff with the kernel or OS research, DO NOT DO THIS! Very bad things can happen, from your system just being slow and unresponsive to DATA LOSS from the system memory management routines forcibly killing off processes when memory has run out for allocation requests.

Disabling VM is a bad idea. A better way of doing things is to force the dynamic pager to do garbage collection with the command

sudo dynamic_pager -L 1073741824

do you have do to a reset for this to worK?

Has anyone done this?

Tell us how this has been working out — is the warning from ‘Three Jeeps’ above scaring people off?

I’ve got 12GB of RAM on a current Mini, and am puzzling over whether this disabling VM is a good idea.

Or, whether increasing the size of the swap file instead (how?)

I’ve been using my MacPro (32GB RAM) like this for about a week now. I notice SIGNIFICANTLY less drive chatter and many many operations are noticeably faster. Especially OS operations like browsing around in folders with hundreds or thousands of images in each. Icons once displayed are actually instant… I don’t mean fast either. On my system they were fast before. This is instant. Poof! A maximized window populated with any sized icons of RAW (or any kind of) images just appears and scrolling to the bottom of multiple folders each containing 4,000+ images works the same way. Browsing images in LR was sped up by about 10 or 20% too. Good news for those who like LR. Bridge was already very fast (about 6 to 8 times faster than LR) for poking around in image folders but it too became slightly faster. It’s too fast in the first place to measure proper differences but doing the best I could with my stop-watch it’s about double the speed with 1st time page displays (from about 2s to about 1s) and instant every time after that – for hours and hours and hours… and hours…

Читайте также:  Azure windows virtual desktop

I don’t recommend doing this with only 8GB or less however. But if you have 24GB or more then I feel comfortable recommending running your machine full-time with the dynamic pager turned off. 16GB would probably be OK too. It works on my older 12GB mac pro system just fine. This is why “with lots of RAM” is in the title. Furthermore you should probably run some kind of memory monitor in the BG. I’ve been using MenuMeters since, like, forever… so I didn’t need to add anything to the installation.

I guess this will help with all versions of OS X from about 10.5 on up – which is when the paging system in OS X became slightly ridiculous.

I have a swap file of 209 GB.
How to set a maximum size for it?

I just read this article and the majority of posts and all I can say that it is extremely bad advice to turn off your swap space. To be blunt, this is a very stupid idea. The entire operating system is built around the idea of a backing store for RAM – that is basic Operating System Design 101. Memory allocation and deallocation use some fairly complicated algorithms to provide low-latency response to having multiple applications loaded, run, and then deactivated. Having a very small amount of RAM (e.g. 1 Gig) causes the allocation/deallocation algorithms to be somewhat inefficient, causing bottlenecked or wedged applications. The more apps one runs, the worse the situation becomes. Your system will literally crawl or wedge. Buy as much RAM as you can afford, and increase your swap to something like 10GB or more. Disks are cheap and althought not as fast as RAM, it will not slow your system to a crawl.If you are worried about killing your SSD, you have two choices: max out the RAM and buy a mechanical HD, or, disable swap and watch your system crawl…..To be honest, the likely hood of destroying your SSD is very slim.

DO NOT disable dynamic_pager!

I had it disabled for a few weeks and noticed that my Mac’s wired memory usage would grow out of control. Turns out that dynamic_pager is involved in cleaning up wired memory…

“Wired memory is not immediately released back to the free list when it becomes invalid. Instead it is “garbage collected” when the free-page count falls below the threshold that triggers page out events.”

How can we tell if this worked? I ran the terminal commands>Restarted>Opened Activity Monitor>Chose the System Memory Tab>VM Size: around 190.55GB… Shouldn’t this be 0?

[…] code was a lot weaker. Snow Leopard (10.6) has massive improvements in Apple’s code, and it seems you can get away with this extremely easy technique: In the Terminal, enter the following command. This will unload the dynamic pager from the Mac OS […]

[…] apps open right now and I’m not even close to hitting virtual memory (you can read more about virtual memory in Mac OS X here). Anytime you can avoid using virtual memory your Mac will perform faster since it does not need to […]

[…] Virtual Memory (commonly called swap) […]

[…] Mac OS XはSnow Leopardになってからメモリマネージメントが大分賢くなったけれど、依然としてswapの発生頻度はかなり高い。場合によってはInactiveが数GBあるのにもかかわらずswapを使い始めたりするので、4GB以上搭載していることが当たり前の今は、思い切ってoffにしてしまうのが良い。 今まではswapを無効化するために専門的な知識が必要な部分が多かったのだけど、最近簡単な方法を見つけたので紹介する。下記コマンドをTerminalで実行し、再起動する。 […]

How does OS X keep track of the location of information in the swapfiles? In some systems there is a page table (sometimes actually a tree), but I’ve not been able to locate that in OS X (version 6). Any help out there?

Mac OS X and virtual memory. While it is true that Mac OS X is built on Unix base, the management of virtual memory by OS X is not akin to raw Unix or Linux vm management since virtual memory allocations occur via the microkernel API (Mach).

The Darwin and osfmk source tree does not directly tie to any PPC hardware or x86 hardware related to paging, so that if you’re expecting to find an operating system structure (exposed and accessible through _asm() or c/c++ lib), you will find none. In fact, if you attempt to access memory that is not “pre-allocated” by Mac OS X, it achieves a “bus error” and fails whereas some Unix OS would allocate another VM page and continue. In cases where the kernel can not create more VM for itself, it enters a hard stop and crashes (why you should leave VM “on”).

The latter is also why porting “other Unix” code to Mac OS X is a chore if the c/c++ source is not well-behaved and cooperating with OS API to allocate VM. These “rules” prevent code allocating beyond (overrun) established code and data boundaries (especially the heap and stack).

Also, to thwart “hacking,” the structures used to govern memory allocation are not exposed in c/c++ API libraries, not even for _setjmp() and _longjmp() functions.

Another layer of protection is that virtual memory init begins during Open Firmware initialization and setup of context which is based as “values” for Mach-O to use.

[…] Virtual memory in any operating system isn’t something you should really mess with, as the operating system likes to do it’s own thing in terms of handling it’s own memory management. That being said, if you want to disable virtual memory altogether on your Mac because you’re foolhardy and/or have oodles of RAM, then by all means, go right ahead. […]

Источник

Оцените статью