オブジェクトは kfree されているのに、システムのエイドメモリがすぐに増えない。この現象は2つの勘定で説明できる。呼び出し元がまだいくつのオブジェクトを保持しているか、アロケータがいくつのページを保持しているか である。
200バイトのオブジェクトから始め、スロット内のオーバーヘッドと予備容量を計算し、割り当て、CPU跨ぎの解放、失敗時のロールバック、アドレスの再利用を追跡する。
説明すべき現象 読むべき箇所
200バイトのオブジェクトがなぜより多くのスペースを占有するのか? 第1節:オブジェクト、スロット、ページ全体
kmalloc、cache、kvmalloc の選択基準は? 第2節:割り当てと解放の契約
kfree の後、ページはいつ返還されるのか? 第3~4節:キャッシュと所有権
リークとUAFの証拠はどのように異なるのか? 第5~6節:検出と読み取り専用統計
1. 200バイトのオブジェクトで3種類のスペースを明確にする
ビジネスで200バイトが必要で、使用されているキャッシュの実際のオブジェクトストライドが256バイト、保持ページが4096バイトであり、ページ外の管理メタデータを無視すると仮定する。1つのslabページには16個のスロットを配置でき、16個のスロットがすべて占有されている場合、ビジネスの有効コンテンツは3200バイト、スロット内のアライメントなどのオーバーヘッドは合計896バイトとなる。
10個のオブジェクトのみが生存している場合、同じページの4096バイトは次のように勘定する必要がある。
去向 計算 バイト数
ビジネスコンテンツ 10 × 200 2000
使用中のスロット内部オーバーヘッド 10 × (256 − 200) 560
再利用可能な空スロット 6 × 256 1536
合計 1つの保持ページ 4096
ビジネスコンテンツ以外の2096バイトには明確な用途があり、すべてをリークとして扱うことはできない。
少数の長寿命オブジェクトがなぜ多くのページを保持し続けるのか
2つのslabにそれぞれ1つのオブジェクトしか生存していない場合、合計で400バイトのビジネスコンテンツしかないが、2つのページを保持し続ける必要があるかもしれない。アロケータは任意のオブジェクトを自由に移動できない。呼び出し元がポインタを保持しているため、任意の移動はこれらのポインタを無効にするからである。一部のサブシステムは独自の回収プロトコルを通じてオブジェクトを解放できるが、これはページ整理によるユーザーページの移動能力とは異なる。
オブジェクトは解放されているが、それらを保持するslabは保持し続ける必要がある場合がある
2つのslabにそれぞれ1つのオブジェクトが残っている
slab A
slab B
オブジェクトが1つのページに集中していると仮定
slab A
slab B
各マスは1つのスロットを表す;通常のslabオブジェクトは任意に移動できない。下段は、占有分布が解放可能なページ数に与える影響のみを示している。
これは、slab order を増やすことが両刃の剣である理由も説明している。一度に多くのオブジェクトスロットを取得することで共有リソースへの補充頻度を減らせるが、より高い順序の連続ページに依存することになる。1つの長寿命オブジェクトが、より大きな保持ブロックの返還を妨げる可能性もある。デバッグ用の redzone、割り当て追跡、アライメントはオブジェクトのストライドを変更するため、チェックを有効にすると、スペースの占有状況と割り当て成功率が変化する可能性がある。slab管理とデバッグ を参照。
オブジェクトの数を同じまま、集中型と分散型のレイアウトを切り替える。以下では、同じスロットサイズを使って、コンテンツ、スロット内のオーバーヘッド、空スロット、保持ページをそれぞれ勘定する。スロットをクリックして、独自の寿命分布を構築することもできる。
SP = Nq + N ( s − q ) + ( S n − N ) s , n = P / s
このモデルでは、1ページあたりのスロット数 n = 16 、P = 4096 B、q = 200 B、s = 256 B。S は生存オブジェクトを持つページの数、N は生存オブジェクトの総数である。
図を準備しています 再読み込み
同じ4つのオブジェクトで、なぜ4倍のページを占有できるのか? 有効コンテンツ、使用中のスロットの内部オーバーヘッド、ページ全体の保持は異なる数量である。分散した少量の生存オブジェクトは、複数のslabが返還されないようにでき、1つのスロットを解放しても1つのページが解放されたわけではない。
{"id":"slab-retained-pages","title":"同じ4つのオブジェクトで、なぜ4倍のページを占有できるのか?","summary":"有効コンテンツ、使用中のスロットの内部オーバーヘッド、ページ全体の保持は異なる数量である。分散した少量の生存オブジェクトは、複数のslabが返還されないようにでき、1つのスロットを解放しても1つのページが解放されたわけではない。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><div class=\"control\"><label for=\"count\" data-i18n=\"count\"></label><output for=\"count\" id=\"count-value\"></output><input id=\"count\" type=\"range\" min=\"0\" max=\"64\" value=\"4\" step=\"1\"></div><div class=\"presets\" role=\"group\" data-i18n-label=\"layout\"><button data-mode=\"packed\" data-i18n=\"packed\"></button><button data-mode=\"spread\" data-i18n=\"spread\"></button></div><div class=\"slabs\"><section class=\"card slab\" id=\"slab-0\"><header>slab 0</header><div class=\"slots\"><button data-slot=\"0\" aria-label=\"slab 0, slot 0\"><i></i></button><button data-slot=\"1\" aria-label=\"slab 0, slot 1\"><i></i></button><button data-slot=\"2\" aria-label=\"slab 0, slot 2\"><i></i></button><button data-slot=\"3\" aria-label=\"slab 0, slot 3\"><i></i></button><button data-slot=\"4\" aria-label=\"slab 0, slot 4\"><i></i></button><button data-slot=\"5\" aria-label=\"slab 0, slot 5\"><i></i></button><button data-slot=\"6\" aria-label=\"slab 0, slot 6\"><i></i></button><button data-slot=\"7\" aria-label=\"slab 0, slot 7\"><i></i></button><button data-slot=\"8\" aria-label=\"slab 0, slot 8\"><i></i></button><button data-slot=\"9\" aria-label=\"slab 0, slot 9\"><i></i></button><button data-slot=\"10\" aria-label=\"slab 0, slot 10\"><i></i></button><button data-slot=\"11\" aria-label=\"slab 0, slot 11\"><i></i></button><button data-slot=\"12\" aria-label=\"slab 0, slot 12\"><i></i></button><button data-slot=\"13\" aria-label=\"slab 0, slot 13\"><i></i></button><button data-slot=\"14\" aria-label=\"slab 0, slot 14\"><i></i></button><button data-slot=\"15\" aria-label=\"slab 0, slot 15\"><i></i></button></div><small id=\"live-0\"></small></section><section class=\"card slab\" id=\"slab-1\"><header>slab 1</header><div class=\"slots\"><button data-slot=\"16\" aria-label=\"slab 1, slot 0\"><i></i></button><button data-slot=\"17\" aria-label=\"slab 1, slot 1\"><i></i></button><button data-slot=\"18\" aria-label=\"slab 1, slot 2\"><i></i></button><button data-slot=\"19\" aria-label=\"slab 1, slot 3\"><i></i></button><button data-slot=\"20\" aria-label=\"slab 1, slot 4\"><i></i></button><button data-slot=\"21\" aria-label=\"slab 1, slot 5\"><i></i></button><button data-slot=\"22\" aria-label=\"slab 1, slot 6\"><i></i></button><button data-slot=\"23\" aria-label=\"slab 1, slot 7\"><i></i></button><button data-slot=\"24\" aria-label=\"slab 1, slot 8\"><i></i></button><button data-slot=\"25\" aria-label=\"slab 1, slot 9\"><i></i></button><button data-slot=\"26\" aria-label=\"slab 1, slot 10\"><i></i></button><button data-slot=\"27\" aria-label=\"slab 1, slot 11\"><i></i></button><button data-slot=\"28\" aria-label=\"slab 1, slot 12\"><i></i></button><button data-slot=\"29\" aria-label=\"slab 1, slot 13\"><i></i></button><button data-slot=\"30\" aria-label=\"slab 1, slot 14\"><i></i></button><button data-slot=\"31\" aria-label=\"slab 1, slot 15\"><i></i></button></div><small id=\"live-1\"></small></section><section class=\"card slab\" id=\"slab-2\"><header>slab 2</header><div class=\"slots\"><button data-slot=\"32\" aria-label=\"slab 2, slot 0\"><i></i></button><button data-slot=\"33\" aria-label=\"slab 2, slot 1\"><i></i></button><button data-slot=\"34\" aria-label=\"slab 2, slot 2\"><i></i></button><button data-slot=\"35\" aria-label=\"slab 2, slot 3\"><i></i></button><button data-slot=\"36\" aria-label=\"slab 2, slot 4\"><i></i></button><button data-slot=\"37\" aria-label=\"slab 2, slot 5\"><i></i></button><button data-slot=\"38\" aria-label=\"slab 2, slot 6\"><i></i></button><button data-slot=\"39\" aria-label=\"slab 2, slot 7\"><i></i></button><button data-slot=\"40\" aria-label=\"slab 2, slot 8\"><i></i></button><button data-slot=\"41\" aria-label=\"slab 2, slot 9\"><i></i></button><button data-slot=\"42\" aria-label=\"slab 2, slot 10\"><i></i></button><button data-slot=\"43\" aria-label=\"slab 2, slot 11\"><i></i></button><button data-slot=\"44\" aria-label=\"slab 2, slot 12\"><i></i></button><button data-slot=\"45\" aria-label=\"slab 2, slot 13\"><i></i></button><button data-slot=\"46\" aria-label=\"slab 2, slot 14\"><i></i></button><button data-slot=\"47\" aria-label=\"slab 2, slot 15\"><i></i></button></div><small id=\"live-2\"></small></section><section class=\"card slab\" id=\"slab-3\"><header>slab 3</header><div class=\"slots\"><button data-slot=\"48\" aria-label=\"slab 3, slot 0\"><i></i></button><button data-slot=\"49\" aria-label=\"slab 3, slot 1\"><i></i></button><button data-slot=\"50\" aria-label=\"slab 3, slot 2\"><i></i></button><button data-slot=\"51\" aria-label=\"slab 3, slot 3\"><i></i></button><button data-slot=\"52\" aria-label=\"slab 3, slot 4\"><i></i></button><button data-slot=\"53\" aria-label=\"slab 3, slot 5\"><i></i></button><button data-slot=\"54\" aria-label=\"slab 3, slot 6\"><i></i></button><button data-slot=\"55\" aria-label=\"slab 3, slot 7\"><i></i></button><button data-slot=\"56\" aria-label=\"slab 3, slot 8\"><i></i></button><button data-slot=\"57\" aria-label=\"slab 3, slot 9\"><i></i></button><button data-slot=\"58\" aria-label=\"slab 3, slot 10\"><i></i></button><button data-slot=\"59\" aria-label=\"slab 3, slot 11\"><i></i></button><button data-slot=\"60\" aria-label=\"slab 3, slot 12\"><i></i></button><button data-slot=\"61\" aria-label=\"slab 3, slot 13\"><i></i></button><button data-slot=\"62\" aria-label=\"slab 3, slot 14\"><i></i></button><button data-slot=\"63\" aria-label=\"slab 3, slot 15\"><i></i></button></div><small id=\"live-3\"></small></section></div><div class=\"legend\"><span data-i18n=\"payload\"></span><span class=\"second\" data-i18n=\"padding\"></span></div><div class=\"space-bar\"><i id=\"payload-bar\"></i><i id=\"padding-bar\"></i><i id=\"empty-bar\"></i></div><div class=\"metrics\"><div><span data-i18n=\"payload\"></span><strong id=\"payload\"></strong></div><div><span data-i18n=\"padding\"></span><strong id=\"padding\"></strong></div><div><span data-i18n=\"capacity\"></span><strong id=\"empty-space\"></strong></div><div><span data-i18n=\"retained\"></span><strong id=\"retained\"></strong></div></div><div class=\"formula\" id=\"sum\"></div><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"emptyNote\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"packedNote\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"spreadNote\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"customNote\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:500;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:500 20px var(--viz-font-ui)}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:var(--viz-font-mono);font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px var(--viz-font-ui);background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n.slabs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:18px 0}.slab{transition:opacity .2s}.slab.empty{opacity:.5}.slots{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px}.slots button{min-width:0;min-height:26px;height:26px;padding:0;border:1px solid var(--rule);background:var(--surface);border-radius:3px;display:block;overflow:hidden}.slots button.live{background:var(--second-soft);border-color:var(--second)}.slots button i{display:block;height:100%;width:78.125%;background:transparent}.slots button.live i{background:var(--accent)}.slab small{min-height:3.2em;margin-top:10px}.space-bar{display:flex;height:24px;border:1px solid var(--rule);background:var(--paper);margin:16px 0}.space-bar i{display:block;height:100%;background:var(--accent);transition:width .25s}#padding-bar{background:var(--second)}#empty-bar{background:var(--surface)}.formula{min-height:4.8em}@media(max-width:480px){.slabs{gap:8px}.slab{padding:12px 6px}.slots{gap:3px}}","js":"const $=s=>document.querySelector(s);let slots=Array(64).fill(false),mode='packed';function seed(n){slots.fill(false);for(let i=0;i<n;i++)slots[mode==='spread'?(i%4)*16+Math.floor(i/4):i]=true;}function draw(){const n=slots.filter(Boolean).length,live=Array.from({length:4},(_,s)=>slots.slice(s*16,s*16+16).filter(Boolean).length),retained=live.filter(Boolean).length*4096,payload=n*200,padding=n*56,empty=retained-n*256;$('#count').value=n;$('#count-value').textContent=n;document.querySelectorAll('[data-slot]').forEach(e=>{e.classList.toggle('live',slots[+e.dataset.slot]);e.setAttribute('aria-pressed',String(slots[+e.dataset.slot]));});for(let s=0;s<4;s++){$('#slab-'+s).classList.toggle('empty',!live[s]);$('#live-'+s).textContent=live[s]?viz.t('alive')+' '+live[s]+' / 16':viz.t('returned');}for(const[id,value]of [['payload',payload],['padding',padding],['empty-space',empty],['retained',retained]])$('#'+id).textContent=value+' B';$('#payload-bar').style.width=payload/16384*100+'%';$('#padding-bar').style.width=padding/16384*100+'%';$('#empty-bar').style.width=empty/16384*100+'%';$('#sum').textContent=payload+' + '+padding+' + '+empty+' = '+retained+' B';$('#explanation').textContent=viz.t(n===0?'emptyNote':mode==='packed'?'packedNote':mode==='spread'?'spreadNote':'customNote');document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}document.querySelectorAll('[data-mode]').forEach(e=>e.addEventListener('click',()=>{const n=slots.filter(Boolean).length;mode=e.dataset.mode;seed(n);draw();}));$('#count').addEventListener('input',()=>{if(!mode)mode='packed';seed(+$('#count').value);draw();});document.querySelectorAll('[data-slot]').forEach(e=>e.addEventListener('click',()=>{const i=+e.dataset.slot;slots[i]=!slots[i];mode='';draw();}));seed(4);draw();","audio":false,"strings":{"alive":"生存オブジェクト","capacity":"空だがページに保持されているスロット","count":"生存オブジェクト数","customNote":"スロットの状態が、どのページに生存オブジェクトが残っているかを直接決定する。そのページの最後のオブジェクトを解放して初めて、そのページの必須保持理由が解消される。","emptyNote":"すべてのオブジェクトが解放された。このモデルの必須保持ページは0であるが、実際のアロケータはポリシーに従って空slabをキャッシュし続ける可能性がある。","heading":"同じ4つのオブジェクトで、なぜ4倍のページを占有できるのか?","intro":"同じ数のオブジェクトの集中型と分散型レイアウトを比較する。オブジェクトスロットをクリックして割り当てまたは解放し、特に1つのslabの最後の生存オブジェクトを観察する。","layout":"割り当て位置のスナップショット","packed":"少ないslabに集中","packedNote":"同じ数のオブジェクトがより少ないslabに集中し、残りのページ全体は生存オブジェクトによって強制的に保持されない。有効コンテンツとスロット内部オーバーヘッドはこれによって変わらない。","padding":"使用中のスロット内部オーバーヘッド","payload":"ビジネス有効コンテンツ","reset":"リセット","retained":"保持しなければならないページスペース","returned":"生存オブジェクトなし","scope":"オブジェクト 200 B、スロット 256 B、slab 4096 B、合計4つのslab。生存オブジェクトを含む必須保持ページのみを統計し、ページ外のメタデータとアロケータの空slabキャッシュは省略する。レイアウトボタンは「同じ数、異なる割り当て位置」のスナップショットを再構築し、カーネルが生存オブジェクトを移動するわけではないことを示す。スロット内の青色はコンテンツ、金色はスロット内のオーバーヘッドを表す。","scopeLabel":"モデルの範囲と規約","spread":"4つのslabに分散","spreadNote":"生存オブジェクトが分散している場合、関与する各slabを保持しなければならない。大多数のスロットが空でも、残りのオブジェクトを任意に移動してページを返還することはできない。"}}
2. kmalloc と kmem_cache は呼び出し元にそれぞれ何を決定させるか
kmalloc は要求サイズとフラグに基づいて一般的な割り当てパスを選択し、小規模なオブジェクトは通常適切なサイズクラスに入る。より大きな要求は、すべてのサイズに同名のキャッシュが存在する必然性がないため、直接高い順序のページに依存できる。サイズクラスと各用途のグループ分けは、アーキテクチャ、設定、バージョンによって異なり、キャッシュの名前を1つ並べただけで、すべてのマシンで同じであるとは限らない。
専用の kmem_cache は、固定のオブジェクトレイアウト、アライメント、フラグ、およびオプションのコンストラクタ要件を表す。類似したキャッシュは条件を満たす場合にマージできるが、その条件はサイズが近いだけでなく、フラグ、アライメント、コンストラクタ、およびデバッグ要件を含む。sysfs で異なる名前が同じ基盤となるキャッシュを指す場合もある。専用キャッシュを定義する理由は、オブジェクトの用途と管理ニーズから来るべきであり、単に見栄えの良い統計名を得るためではない。
オブジェクトを再利用する場合、初期化の責任は依然として呼び出し元にある
コンストラクタは通常、slab内の新しいオブジェクトの初期作成に使用され、呼び出し元に割り当てられるたびに再実行されるものではない。前のユーザーが書き込んだフィールドが、次の alloc でコンストラクタによって自動的に復元されることを期待してはならない。kmalloc/kmem_cache_alloc もゼロ初期化を保証しない。ゼロにする必要がある場合は、適切なインターフェースを使用するかフィールドを明示的に初期化し、オブジェクトを他のスレッドに公開する。
インターフェースを選択する場合、連続性と解放インターフェースは1組の契約である
割り当て方法 適した要件 解放と境界
kmalloc/kzalloc通常のカーネルバッファ、物理的に連続した割り当て結果 kfree;要求された有効範囲を超えてアクセスしてはならない
kmalloc_array/kcalloc要素数 × 要素サイズの配列 乗算オーバーフローをチェックする割り当てインターフェース、NULL の処理も必要
kmem_cache_alloc作成済みのキャッシュの固定オブジェクト 対応する kmem_cache_free を使用し、他のキャッシュと混用してはならない
kvmalloc/kvzalloc仮想連続、物理的に不連続の大きなバッファを受け入れ可能 kvfree;使用シナリオと GFP はフォールバックパスの要件に適合する必要がある
vmalloc複数のバックアップページへの仮想連続マッピング vfree;単一のDMA物理バッファとして使用してはならない
実際の割り当てサイズは要求サイズより大きくなる可能性があるが、末尾のスペースはビジネスが自由に使用できる暗黙の許可ではない。サイズクラスで丸める必要がある場合は、適切なインターフェースを使用し、要求/割り当て契約を基準とする。DMAデバイスがバッファにアクセスできるかどうかは、DMA API を経由して確認する必要があり、「kmalloc が連続している」からといって、任意のデバイスがそのCPUアドレスを直接使用できるわけではない。メモリ割り当てガイド を参照。
3. 割り当て、CPU跨ぎの解放、ページ返還の一連の流れ
CPU 0 がオブジェクトを割り当てるとき、ローカルに適切な空スロットがあれば、それを迅速に取得できる。ローカルにオブジェクトがない場合、共有リザーブまたはパーシャルスラブから補充する必要がある。これらも不足している場合に限り、ページアロケータに保持ページを要求して、さらに多くのスロットを構築する。小規模なオブジェクトの割り当てでも、ページアロケータのスローパスに入る可能性があるため、「200バイトしか割り当てない」からといって、スリープや失敗の可能性がないわけではない。
オブジェクトが CPU 1 に渡されて処理され、解放されると、それは CPU 1 が現在使用しているローカルスラブ/キャッシュに属していない可能性がある。アロケータは、所属するスラブ、空の数、キャッシュの帰属などの情報を維持する必要があり、必要に応じてアトミック更新やロックを使用する。すべての free が単に現在のCPUのリストヘッダーに2回ポインタを書き込むだけと仮定してはならない。
オブジェクトの要求から物理ページへ:高速パスはキャッシュに依存、低速パスはリソースを補充
オブジェクトの割り当て / 解放
kmalloc または専用キャッシュ
CPU側オブジェクトキャッシュ
ローカルでの再利用とバッチ処理を優先
共有リソースとパーシャルスラブ
必要に応じて他のオブジェクトリザーブと調整
ページアロケータ
保持ページの追加 / 返還
キャッシュ階層を示すものであり、特定のバージョンの freelist/sheaf 構造に固定されるものではない;デバッグと NUMA 制約により高速パスが変更される可能性がある。
オブジェクトを解放することは、その使用権をアロケータに返還するにすぎない。一定のオブジェクトバッチが空になり、slab が返還条件を満たすと、保持ページがページアロケータに戻される可能性がある。一定数の空スラブまたはローカルオブジェクト容量を保持することで、次の割り当てラウンドが高速化されるが、低負荷後のメモリ減少が瞬時に完了するわけではない。異常の判断は、安定した負荷下で継続的に増加しているかどうか、キャッシュの設計された保持ポリシー、および参照チェーンと組み合わせて行うべきであり、1回の kfree の前後の MemFree を比較するだけでは不十分である。
ソースコードの読み取り:キャッシュの組織はバージョンによって変化する
旧版の SLUB では、高速パスを説明するために per-CPU active slab/freelist が一般的に使用されていた。今回確認した Linux 7.2 の mm/slub.c では、CPU側 sheaves オブジェクト配列、NUMA ノードの barn を使用して、バッチキャッシュと交換が行われている。
これらはすべて共有リソース操作の頻度を減らすことを目的としているが、同期、RT、およびデバッグパスは対象バージョンに応じて読み取る必要がある。kmalloc などのインターフェース契約を学ぶ際には、これらの内部組織の変化を別個に扱うべきである。
4. 割り当て失敗時、未完成品には明確な所有者が必要である
初期化プロセスを考慮する。キャッシュを作成し、ポインタ配列を割り当て、32個のオブジェクトを割り当てる必要があるとする。19番目のオブジェクトの割り当てに失敗した場合、成功した前の18個のオブジェクトは依然として初期化者に属している。配列のみを解放すると、それらのアドレスが失われる。キャッシュのみを破棄しても、生存しているオブジェクトを解放する代わりにはならない。
19回目のオブジェクト割り当てに失敗した場合、クリーンアップの責任は成功した記録に従って逆展開される。
取り消し順序 解放するもの なぜこのステップで処理しなければならないか
1 成功した前の18個のオブジェクト それらは依然として初期化者に属しており、アドレスを失ってはならない
2 ポインタ配列 すべてのオブジェクトが解放されて初めて、インデックスは不要になる
3 キャッシュ 生存オブジェクトがないことを確認してから、保持メカニズムを破棄する
複雑なドライバーでは、エントリ、バックグラウンドタスク、非同期参照を先に停止する必要がある。アロケータはスロットが空かどうかを知っていても、外部コールバックがまだそれをアクセスするかどうかは知らない。
実験コード:ロールバック順序を先に確認し、各エラーラベルを確認する
以下は、完全な教学モジュールの初期化パスである。少量のオブジェクトを割り当て、フィールドを検証し、返却前にクリーンアップする。このコードは段階的なロールバックを示すために使用され、モジュールのロードを要求せずにコンパイルチェックを行う。
#include < linux/errno.h>
#include < linux/init.h>
#include < linux/module.h>
#include < linux/slab.h>
struct kb_item {
unsigned int id;
unsigned char payload[ 196 ] ;
} ;
static int __init kb_alloc_init ( void )
{
struct kmem_cache * cache;
struct kb_item * * items;
unsigned int made = 0 ;
int result = - ENOMEM;
cache = kmem_cache_create ( " kb_alloc_example" , sizeof ( struct kb_item) ,
0 , 0 , NULL ) ;
if ( ! cache)
return - ENOMEM;
items = kcalloc ( 32 , sizeof ( * items) , GFP_KERNEL) ;
if ( ! items)
goto destroy_cache;
while ( made < 32 ) {
struct kb_item * item = kmem_cache_zalloc ( cache, GFP_KERNEL ) ;
if ( ! item)
goto free_items;
item-> id = made;
items[ made+ + ] = item;
}
result = 0 ;
for ( unsigned int i = 0 ; i < made; + + i) {
if ( items[ i] -> id != i || items[ i] -> payload[ 0 ] != 0 ) {
result = - EINVAL;
break ;
}
}
free_items :
while ( made)
kmem_cache_free ( cache, items[ - - made] ) ;
kfree ( items ) ;
destroy_cache :
kmem_cache_destroy ( cache ) ;
return result;
}
static void __exit kb_alloc_exit ( void ) { }
module_init ( kb_alloc_init ) ;
module_exit ( kb_alloc_exit ) ;
MODULE_LICENSE ( " GPL" ) ;
MODULE_DESCRIPTION ( " Slab allocation and rollback teaching example" ) ;
Kbuild では obj-m += kb_alloc_example.o を使用できる。実際の障害分岐が期待通りに実行されるかどうかは、別の制御された失敗注入が必要である。コンパイルが成功しただけでは、19回目の失敗パスが実行されたとは見なせない。生存オブジェクトがまだ参照されている場合に、キャッシュを破棄して「リークを修正」してはならない。
5. 解放後の再利用は UAF を説明し、検出ツールの異なる証拠も説明する
オブジェクト A が解放され、元のアドレスがその後オブジェクト B に割り当てられると仮定する。A の古いポインタは同じアドレスを指し続けているため、誤った書き込みは、すぐにクラッシュするのではなく、B を破壊する可能性がある。解放されたメモリをポイズンで埋めることで、後の異常の識別に役立つが、誤ったアクセスが常に発生した瞬間に検出されるとは限らない。割り当て/解放追跡も、後のチェックポイントで破壊を発見する可能性がある。
検出ツール:不正アクセスと到達不能な割り当ては2種類の証拠である
KASAN の異なるモードは、シャドウメモリやタグなどのメカニズムを利用して不正アクセスをチェックし、コスト、カバー範囲、および粒度が異なる。Generic KASAN の 1:8 シャドウ比率はシステム全体の唯一のコストではなく、quarantine、アライメント、および他のメタデータが含まれる可能性がある。タグベースの検出も、同じタグを持つエラーやチェック粒度内にあるエラーをすべて識別できるとは限らない。KASAN を参照。
kmemleak は、主に疑わしいオブジェクトが既知のルートから到達可能かどうかをスキャンすることで、潜在的なリークを報告する。それはすべての C ポインタセマンティクスを追跡する証明機ではない。隠蔽されたポインタやエンコードされたポインタは誤報をもたらし、偶然ポインタのような値は、リークが到達可能であるかのように見せる可能性がある。したがって、それは「どの割り当てをチェックする価値があるか」に答えるが、KASAN はより直接的に特定の不正アクセスを対象とする。kmemleak を参照。
通常の slab オブジェクトの回収責任は、それを使用するサブシステムに属する。回収可能なキャッシュセマンティクスを持つサブシステムは、shrinker を登録して、圧力下で不要なオブジェクトを解放できる。キャッシュを某種の回収可能な用途としてマークしただけでは、カーネルが自動的に理解して、まだ使用されているビジネスオブジェクトを破棄するわけではない。
6. オブジェクトサイズ、スロットストライド、ページオーダの読み取り専用比較
from pathlib import Path
import os
root = Path ( " /sys/kernel/slab/dentry" )
if not root . exists ( ) :
print ( " 現在 dentry slab sysfs は公開されていない" )
else :
print ( " 実際のキャッシュパス:" , root . resolve ( ) )
values = { }
for name in ( " object_size" , " slab_size" , " order" , " objects" , " slabs" ) :
try :
values [ name ] = ( root / name ) . read_text ( ) . strip ( )
except OSError as error :
values [ name ] = type ( error ) . __name__
print ( name , values [ name ] )
if values [ " order" ] . isdigit ( ) :
print ( " 現在の order で計算した slab バイト数:" ,
os . sysconf ( " SC_PAGE_SIZE" ) * ( 1 < < int ( values [ " order" ] ) ) )
読み取り結果を確認する際は、単位を先に確認する。
フィールド どのように理解すべきか
object_size オブジェクトコンテンツのサイズに関連するフィールド
slab_size オブジェクトスロットのサイズに関連するフィールド、スラブ全体のバイト数ではない
order 基本ページサイズと組み合わせて、スラブ全体の保持スペースを計算する必要がある
objects、slabs ノード分布情報が付随する可能性があるため、行全体を直接整数に変換してはならない
既存の slab の実際のオーダ、デバッグモード、およびフォールバックには、より詳細な統計情報が必要である。現在の設定値からすべての履歴割り当てを逆算することはできない。
/proc/slabinfo と組み合わせて使用する際は、active objects、容量、および保持ページを別々に確認する。統計情報はローカルキャッシュと実装の勘定方法の影響を受けるため、active 数を無条件にビジネスがまだ保持している正確なオブジェクト数と見なしてはならない。次に ページ回収とスワップ で、slab shrinker を通常のファイルページや匿名ページと同じ圧力モデルに組み込む。