← Documents Documentation/process/applying-patches.rst GitHub 원문 ↗

Linux 6.18.37 · 개발 절차

Linux kernel patch 적용과 되돌리기

Patch의 base를 확인하고 patch -p1로 적용·복구하는 방법, fuzz와 reject 진단, stable·rc patch의 기준 tree를 설명합니다.

Source pathDocumentation/process/applying-patches.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

현재는 Git을 우선 사용한다

applying-patches.rst:3-21

이 원문은 obsolete로 표시되어 있다. 현재 kernel 개발에서는 수동 patch 명령보다 Git commit, git am과 git cherry-pick을 쓰는 경우가 대부분이다. 다만 release delta patch의 구조와 오류 메시지를 이해하는 자료로 남아 있다.

Patch는 두 source tree version 사이의 차이를 담은 text다. 올바르게 적용하려면 어느 base에서 만들어졌고 적용 뒤 어느 version이 되는지를 알아야 한다. 이 정보는 patch metadata 또는 file name에서 확인한다.

patch -p1 적용과 -R 복구

applying-patches.rst:24-108

Linux kernel patch의 file path는 보통 source directory의 parent 기준이거나 a/와 b/ prefix를 포함한다. Kernel source root로 이동한 뒤 -p1로 첫 path component를 제거해 적용한다.

patch -p1 < ../patch-x.y.z
patch -R -p1 < ../patch-x.y.z
patch -p1 -i ../patch-x.y.z

압축 patch는 xzcat·zcat output을 patch stdin으로 보낼 수 있고, 먼저 xz -d나 gunzip으로 풀어도 된다. --dry-run은 file을 바꾸지 않고 적용 결과를 확인하며, -s는 error 외 출력을 줄이고 --verbose는 세부 동작을 보여 준다.

Fuzz, offset, reject와 손상된 mail

applying-patches.rst:111-206
메시지의미확인할 항목
File to patch:대상 file path를 찾지 못했다.-p1 누락, 잘못된 현재 directory, 드물게 -p0 patch인지 확인한다.
succeeded ... with fuzzContext 일부가 달라 patch가 근사 일치로 적용됐다.다른 kernel base인지 확인하고 결과 code를 직접 검토한다.
Hunk FAILED변경을 적용하지 못해 .rej와 .orig가 생겼다..rej의 의도와 현재 code를 비교해 수동 해결한다.
Reversed or previously applied이미 적용됐거나 source·destination이 뒤집혔다.중복 적용이면 중단하고, 실제 되돌리기라면 -R을 사용한다.
unexpected end of file압축 file, 불완전 download 또는 mailer가 줄을 변형했다.원본을 다시 받고 line wrapping과 encoding을 확인한다.

수정하지 않은 정확한 base tree에 kernel.org patch를 순서대로 적용했다면 fuzz나 reject가 나와서는 안 된다. 발생하면 억지로 진행하기보다 patch와 source tree의 무결성을 먼저 의심하고 깨끗한 tree에서 다시 시작한다.

Patch 분석 보조 도구

applying-patches.rst:209-238
  • interdiff는 두 patch 사이의 차이를 만들어 stable subversion 사이를 한 번에 이동할 수 있지만 잘못된 결과 가능성이 있어 단계별 적용이 더 안전하다.
  • diffstat은 patch의 file별 insertion·deletion 요약을 보여 준다.
  • lsdiff는 영향받는 file과 선택적으로 hunk 시작 줄을 나열한다.
  • grepdiff는 diff에 특정 regular expression이 들어 있는 file을 찾는다.
  • ketchup은 patch download와 적용을 자동화하던 Python 도구다.

Base release와 stable patch의 기준

applying-patches.rst:241-350

문서의 5.x 표기는 예시일 뿐 원칙은 현재 version에도 같다. x.y base release 사이의 delta는 이전 base에 적용한다. x.y.z normal stable patch는 직전 x.y.z-1 tree가 아니라 x.y base에 적용된다.

따라서 x.y.2 source에서 normal x.y.3 patch로 갈 때는 먼저 x.y.2 patch를 -R로 되돌려 x.y base를 만든 뒤 x.y.3 patch를 적용한다. 반면 incremental x.y.2-3 patch는 x.y.2에 바로 적용해 x.y.3으로 이동한다.

# normal stable patch
patch -R -p1 < ../patch-5.7.2
patch -p1 < ../patch-5.7.3

# incremental stable patch
patch -p1 < ../patch-5.7.2-3

Release candidate patch

applying-patches.rst:352-400

x.y-rcN은 다음 x.y release 후보이며 바로 전 base인 x.(y-1)에 적용한다. -rc patch도 incremental이 아니므로 rc3에서 rc5로 갈 때는 rc3 patch를 되돌려 base로 만든 뒤 rc5 patch를 적용한다. Stable x.(y-1).z에서 이동한다면 stable patch도 먼저 되돌린다.

RC는 개발 kernel이므로 breakage 가능성이 있지만 다음 stable release가 될 mainline을 폭넓게 test하는 중요한 단계다.

linux-next와 -mm

applying-patches.rst:403-435

Subsystem integration test 역할은 linux-next가 담당한다. Maintainer가 merge window 전에 topic을 linux-next로 보내 다른 subsystem 변경과 함께 daily integration한다. -mm은 subsystem tree 밖의 실험 기능을 검증하는 proving ground 성격을 유지하고 linux-next에 포함된다.

linux-next와 -mm에는 debugging patch와 아직 mainline에 적합하지 않은 실험 변경이 많다. 안정성이 필요한 system에는 쓰지 말고 backup이 있는 test 환경에서 regression, crash, corruption과 build breakage를 찾는 용도로 사용한다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. _applying_patches:
2
3 Applying Patches To The Linux Kernel
4 ++++++++++++++++++++++++++++++++++++
5
6 Original by:
7 Jesper Juhl, August 2005
8
9 .. note::
10
11 This document is obsolete. In most cases, rather than using ``patch``
12 manually, you'll almost certainly want to look at using Git instead.
13
14 A frequently asked question on the Linux Kernel Mailing List is how to apply
15 a patch to the kernel or, more specifically, what base kernel a patch for
16 one of the many trees/branches should be applied to. Hopefully this document
17 will explain this to you.
18
19 In addition to explaining how to apply and revert patches, a brief
20 description of the different kernel trees (and examples of how to apply
21 their specific patches) is also provided.
22
23
24 What is a patch?
25 ================
26
27 A patch is a small text document containing a delta of changes between two
28 different versions of a source tree. Patches are created with the ``diff``
29 program.
30
31 To correctly apply a patch you need to know what base it was generated from
32 and what new version the patch will change the source tree into. These
33 should both be present in the patch file metadata or be possible to deduce
34 from the filename.
35
36
37 How do I apply or revert a patch?
38 =================================
39
40 You apply a patch with the ``patch`` program. The patch program reads a diff
41 (or patch) file and makes the changes to the source tree described in it.
42
43 Patches for the Linux kernel are generated relative to the parent directory
44 holding the kernel source dir.
45
46 This means that paths to files inside the patch file contain the name of the
47 kernel source directories it was generated against (or some other directory
48 names like "a/" and "b/").
49
50 Since this is unlikely to match the name of the kernel source dir on your
51 local machine (but is often useful info to see what version an otherwise
52 unlabeled patch was generated against) you should change into your kernel
53 source directory and then strip the first element of the path from filenames
54 in the patch file when applying it (the ``-p1`` argument to ``patch`` does
55 this).
56
57 To revert a previously applied patch, use the -R argument to patch.
58 So, if you applied a patch like this::
59
60 patch -p1 < ../patch-x.y.z
61
62 You can revert (undo) it like this::
63
64 patch -R -p1 < ../patch-x.y.z
65
66
67 How do I feed a patch/diff file to ``patch``?
68 =============================================
69
70 This (as usual with Linux and other UNIX like operating systems) can be
71 done in several different ways.
72
73 In all the examples below I feed the file (in uncompressed form) to patch
74 via stdin using the following syntax::
75
76 patch -p1 < path/to/patch-x.y.z
77
78 If you just want to be able to follow the examples below and don't want to
79 know of more than one way to use patch, then you can stop reading this
80 section here.
81
82 Patch can also get the name of the file to use via the -i argument, like
83 this::
84
85 patch -p1 -i path/to/patch-x.y.z
86
87 If your patch file is compressed with gzip or xz and you don't want to
88 uncompress it before applying it, then you can feed it to patch like this
89 instead::
90
91 xzcat path/to/patch-x.y.z.xz | patch -p1
92 bzcat path/to/patch-x.y.z.gz | patch -p1
93
94 If you wish to uncompress the patch file by hand first before applying it
95 (what I assume you've done in the examples below), then you simply run
96 gunzip or xz on the file -- like this::
97
98 gunzip patch-x.y.z.gz
99 xz -d patch-x.y.z.xz
100
101 Which will leave you with a plain text patch-x.y.z file that you can feed to
102 patch via stdin or the ``-i`` argument, as you prefer.
103
104 A few other nice arguments for patch are ``-s`` which causes patch to be silent
105 except for errors which is nice to prevent errors from scrolling out of the
106 screen too fast, and ``--dry-run`` which causes patch to just print a listing of
107 what would happen, but doesn't actually make any changes. Finally ``--verbose``
108 tells patch to print more information about the work being done.
109
110
111 Common errors when patching
112 ===========================
113
114 When patch applies a patch file it attempts to verify the sanity of the
115 file in different ways.
116
117 Checking that the file looks like a valid patch file and checking the code
118 around the bits being modified matches the context provided in the patch are
119 just two of the basic sanity checks patch does.
120
121 If patch encounters something that doesn't look quite right it has two
122 options. It can either refuse to apply the changes and abort or it can try
123 to find a way to make the patch apply with a few minor changes.
124
125 One example of something that's not 'quite right' that patch will attempt to
126 fix up is if all the context matches, the lines being changed match, but the
127 line numbers are different. This can happen, for example, if the patch makes
128 a change in the middle of the file but for some reasons a few lines have
129 been added or removed near the beginning of the file. In that case
130 everything looks good it has just moved up or down a bit, and patch will
131 usually adjust the line numbers and apply the patch.
132
133 Whenever patch applies a patch that it had to modify a bit to make it fit
134 it'll tell you about it by saying the patch applied with **fuzz**.
135 You should be wary of such changes since even though patch probably got it
136 right it doesn't /always/ get it right, and the result will sometimes be
137 wrong.
138
139 When patch encounters a change that it can't fix up with fuzz it rejects it
140 outright and leaves a file with a ``.rej`` extension (a reject file). You can
141 read this file to see exactly what change couldn't be applied, so you can
142 go fix it up by hand if you wish.
143
144 If you don't have any third-party patches applied to your kernel source, but
145 only patches from kernel.org and you apply the patches in the correct order,
146 and have made no modifications yourself to the source files, then you should
147 never see a fuzz or reject message from patch. If you do see such messages
148 anyway, then there's a high risk that either your local source tree or the
149 patch file is corrupted in some way. In that case you should probably try
150 re-downloading the patch and if things are still not OK then you'd be advised
151 to start with a fresh tree downloaded in full from kernel.org.
152
153 Let's look a bit more at some of the messages patch can produce.
154
155 If patch stops and presents a ``File to patch:`` prompt, then patch could not
156 find a file to be patched. Most likely you forgot to specify -p1 or you are
157 in the wrong directory. Less often, you'll find patches that need to be
158 applied with ``-p0`` instead of ``-p1`` (reading the patch file should reveal if
159 this is the case -- if so, then this is an error by the person who created
160 the patch but is not fatal).
161
162 If you get ``Hunk #2 succeeded at 1887 with fuzz 2 (offset 7 lines).`` or a
163 message similar to that, then it means that patch had to adjust the location
164 of the change (in this example it needed to move 7 lines from where it
165 expected to make the change to make it fit).
166
167 The resulting file may or may not be OK, depending on the reason the file
168 was different than expected.
169
170 This often happens if you try to apply a patch that was generated against a
171 different kernel version than the one you are trying to patch.
172
173 If you get a message like ``Hunk #3 FAILED at 2387.``, then it means that the
174 patch could not be applied correctly and the patch program was unable to
175 fuzz its way through. This will generate a ``.rej`` file with the change that
176 caused the patch to fail and also a ``.orig`` file showing you the original
177 content that couldn't be changed.
178
179 If you get ``Reversed (or previously applied) patch detected! Assume -R? [n]``
180 then patch detected that the change contained in the patch seems to have
181 already been made.
182
183 If you actually did apply this patch previously and you just re-applied it
184 in error, then just say [n]o and abort this patch. If you applied this patch
185 previously and actually intended to revert it, but forgot to specify -R,
186 then you can say [**y**]es here to make patch revert it for you.
187
188 This can also happen if the creator of the patch reversed the source and
189 destination directories when creating the patch, and in that case reverting
190 the patch will in fact apply it.
191
192 A message similar to ``patch: **** unexpected end of file in patch`` or
193 ``patch unexpectedly ends in middle of line`` means that patch could make no
194 sense of the file you fed to it. Either your download is broken, you tried to
195 feed patch a compressed patch file without uncompressing it first, or the patch
196 file that you are using has been mangled by a mail client or mail transfer
197 agent along the way somewhere, e.g., by splitting a long line into two lines.
198 Often these warnings can easily be fixed by joining (concatenating) the
199 two lines that had been split.
200
201 As I already mentioned above, these errors should never happen if you apply
202 a patch from kernel.org to the correct version of an unmodified source tree.
203 So if you get these errors with kernel.org patches then you should probably
204 assume that either your patch file or your tree is broken and I'd advise you
205 to start over with a fresh download of a full kernel tree and the patch you
206 wish to apply.
207
208
209 Are there any alternatives to ``patch``?
210 ========================================
211
212
213 Yes there are alternatives.
214
215 You can use the ``interdiff`` program (http://cyberelk.net/tim/patchutils/) to
216 generate a patch representing the differences between two patches and then
217 apply the result.
218
219 This will let you move from something like 5.7.2 to 5.7.3 in a single
220 step. The -z flag to interdiff will even let you feed it patches in gzip or
221 bzip2 compressed form directly without the use of zcat or bzcat or manual
222 decompression.
223
224 Here's how you'd go from 5.7.2 to 5.7.3 in a single step::
225
226 interdiff -z ../patch-5.7.2.gz ../patch-5.7.3.gz | patch -p1
227
228 Although interdiff may save you a step or two you are generally advised to
229 do the additional steps since interdiff can get things wrong in some cases.
230
231 Another alternative is ``ketchup``, which is a python script for automatic
232 downloading and applying of patches (https://www.selenic.com/ketchup/).
233
234 Other nice tools are diffstat, which shows a summary of changes made by a
235 patch; lsdiff, which displays a short listing of affected files in a patch
236 file, along with (optionally) the line numbers of the start of each patch;
237 and grepdiff, which displays a list of the files modified by a patch where
238 the patch contains a given regular expression.
239
240
241 Where can I download the patches?
242 =================================
243
244 The patches are available at https://kernel.org/
245 Most recent patches are linked from the front page, but they also have
246 specific homes.
247
248 The 5.x.y (-stable) and 5.x patches live at
249
250 https://www.kernel.org/pub/linux/kernel/v5.x/
251
252 The 5.x.y incremental patches live at
253
254 https://www.kernel.org/pub/linux/kernel/v5.x/incr/
255
256 The -rc patches are not stored on the webserver but are generated on
257 demand from git tags such as
258
259 https://git.kernel.org/torvalds/p/v5.1-rc1/v5.0
260
261 The stable -rc patches live at
262
263 https://www.kernel.org/pub/linux/kernel/v5.x/stable-review/
264
265
266 The 5.x kernels
267 ===============
268
269 These are the base stable releases released by Linus. The highest numbered
270 release is the most recent.
271
272 If regressions or other serious flaws are found, then a -stable fix patch
273 will be released (see below) on top of this base. Once a new 5.x base
274 kernel is released, a patch is made available that is a delta between the
275 previous 5.x kernel and the new one.
276
277 To apply a patch moving from 5.6 to 5.7, you'd do the following (note
278 that such patches do **NOT** apply on top of 5.x.y kernels but on top of the
279 base 5.x kernel -- if you need to move from 5.x.y to 5.x+1 you need to
280 first revert the 5.x.y patch).
281
282 Here are some examples::
283
284 # moving from 5.6 to 5.7
285
286 $ cd ~/linux-5.6 # change to kernel source dir
287 $ patch -p1 < ../patch-5.7 # apply the 5.7 patch
288 $ cd ..
289 $ mv linux-5.6 linux-5.7 # rename source dir
290
291 # moving from 5.6.1 to 5.7
292
293 $ cd ~/linux-5.6.1 # change to kernel source dir
294 $ patch -p1 -R < ../patch-5.6.1 # revert the 5.6.1 patch
295 # source dir is now 5.6
296 $ patch -p1 < ../patch-5.7 # apply new 5.7 patch
297 $ cd ..
298 $ mv linux-5.6.1 linux-5.7 # rename source dir
299
300
301 The 5.x.y kernels
302 =================
303
304 Kernels with 3-digit versions are -stable kernels. They contain small(ish)
305 critical fixes for security problems or significant regressions discovered
306 in a given 5.x kernel.
307
308 This is the recommended branch for users who want the most recent stable
309 kernel and are not interested in helping test development/experimental
310 versions.
311
312 If no 5.x.y kernel is available, then the highest numbered 5.x kernel is
313 the current stable kernel.
314
315 The -stable team provides normal as well as incremental patches. Below is
316 how to apply these patches.
317
318 Normal patches
319 ~~~~~~~~~~~~~~
320
321 These patches are not incremental, meaning that for example the 5.7.3
322 patch does not apply on top of the 5.7.2 kernel source, but rather on top
323 of the base 5.7 kernel source.
324
325 So, in order to apply the 5.7.3 patch to your existing 5.7.2 kernel
326 source you have to first back out the 5.7.2 patch (so you are left with a
327 base 5.7 kernel source) and then apply the new 5.7.3 patch.
328
329 Here's a small example::
330
331 $ cd ~/linux-5.7.2 # change to the kernel source dir
332 $ patch -p1 -R < ../patch-5.7.2 # revert the 5.7.2 patch
333 $ patch -p1 < ../patch-5.7.3 # apply the new 5.7.3 patch
334 $ cd ..
335 $ mv linux-5.7.2 linux-5.7.3 # rename the kernel source dir
336
337 Incremental patches
338 ~~~~~~~~~~~~~~~~~~~
339
340 Incremental patches are different: instead of being applied on top
341 of base 5.x kernel, they are applied on top of previous stable kernel
342 (5.x.y-1).
343
344 Here's the example to apply these::
345
346 $ cd ~/linux-5.7.2 # change to the kernel source dir
347 $ patch -p1 < ../patch-5.7.2-3 # apply the new 5.7.3 patch
348 $ cd ..
349 $ mv linux-5.7.2 linux-5.7.3 # rename the kernel source dir
350
351
352 The -rc kernels
353 ===============
354
355 These are release-candidate kernels. These are development kernels released
356 by Linus whenever he deems the current git (the kernel's source management
357 tool) tree to be in a reasonably sane state adequate for testing.
358
359 These kernels are not stable and you should expect occasional breakage if
360 you intend to run them. This is however the most stable of the main
361 development branches and is also what will eventually turn into the next
362 stable kernel, so it is important that it be tested by as many people as
363 possible.
364
365 This is a good branch to run for people who want to help out testing
366 development kernels but do not want to run some of the really experimental
367 stuff (such people should see the sections about -next and -mm kernels below).
368
369 The -rc patches are not incremental, they apply to a base 5.x kernel, just
370 like the 5.x.y patches described above. The kernel version before the -rcN
371 suffix denotes the version of the kernel that this -rc kernel will eventually
372 turn into.
373
374 So, 5.8-rc5 means that this is the fifth release candidate for the 5.8
375 kernel and the patch should be applied on top of the 5.7 kernel source.
376
377 Here are 3 examples of how to apply these patches::
378
379 # first an example of moving from 5.7 to 5.8-rc3
380
381 $ cd ~/linux-5.7 # change to the 5.7 source dir
382 $ patch -p1 < ../patch-5.8-rc3 # apply the 5.8-rc3 patch
383 $ cd ..
384 $ mv linux-5.7 linux-5.8-rc3 # rename the source dir
385
386 # now let's move from 5.8-rc3 to 5.8-rc5
387
388 $ cd ~/linux-5.8-rc3 # change to the 5.8-rc3 dir
389 $ patch -p1 -R < ../patch-5.8-rc3 # revert the 5.8-rc3 patch
390 $ patch -p1 < ../patch-5.8-rc5 # apply the new 5.8-rc5 patch
391 $ cd ..
392 $ mv linux-5.8-rc3 linux-5.8-rc5 # rename the source dir
393
394 # finally let's try and move from 5.7.3 to 5.8-rc5
395
396 $ cd ~/linux-5.7.3 # change to the kernel source dir
397 $ patch -p1 -R < ../patch-5.7.3 # revert the 5.7.3 patch
398 $ patch -p1 < ../patch-5.8-rc5 # apply new 5.8-rc5 patch
399 $ cd ..
400 $ mv linux-5.7.3 linux-5.8-rc5 # rename the kernel source dir
401
402
403 The -mm patches and the linux-next tree
404 =======================================
405
406 The -mm patches are experimental patches released by Andrew Morton.
407
408 In the past, -mm tree were used to also test subsystem patches, but this
409 function is now done via the
410 `linux-next` (https://www.kernel.org/doc/man-pages/linux-next.html)
411 tree. The Subsystem maintainers push their patches first to linux-next,
412 and, during the merge window, sends them directly to Linus.
413
414 The -mm patches serve as a sort of proving ground for new features and other
415 experimental patches that aren't merged via a subsystem tree.
416 Once such patches has proved its worth in -mm for a while Andrew pushes
417 it on to Linus for inclusion in mainline.
418
419 The linux-next tree is daily updated, and includes the -mm patches.
420 Both are in constant flux and contains many experimental features, a
421 lot of debugging patches not appropriate for mainline etc., and is the most
422 experimental of the branches described in this document.
423
424 These patches are not appropriate for use on systems that are supposed to be
425 stable and they are more risky to run than any of the other branches (make
426 sure you have up-to-date backups -- that goes for any experimental kernel but
427 even more so for -mm patches or using a Kernel from the linux-next tree).
428
429 Testing of -mm patches and linux-next is greatly appreciated since the whole
430 point of those are to weed out regressions, crashes, data corruption bugs,
431 build breakage (and any other bug in general) before changes are merged into
432 the more stable mainline Linus tree.
433
434 But testers of -mm and linux-next should be aware that breakages are
435 more common than in any other tree.
436
437
438 This concludes this list of explanations of the various kernel trees.
439 I hope you are now clear on how to apply the various patches and help testing
440 the kernel.
441
442 Thank you's to Randy Dunlap, Rolf Eike Beer, Linus Torvalds, Bodo Eggert,
443 Johannes Stezenbach, Grant Coady, Pavel Machek and others that I may have
444 forgotten for their reviews and contributions to this document.
445

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

문서의 범위와 patch의 정의

1-34

이 문서는 Jesper Juhl이 2005년 8월 처음 작성했다. 현재는 obsolete 문서이며, 대부분의 경우 patch 명령을 직접 사용하는 대신 Git을 사용하는 방법을 먼저 검토해야 한다.

Linux Kernel Mailing List에서 자주 나오는 질문 중 하나는 kernel에 patch를 어떻게 적용하는지, 더 구체적으로는 여러 tree와 branch 중 어느 base kernel에 patch를 적용해야 하는지다. 이 문서는 patch 적용·revert 방법과 여러 kernel tree의 성격, 각 tree용 patch를 적용하는 예를 설명한다.

Patch는 source tree의 서로 다른 두 version 사이 변경 delta를 담은 작은 text document이며 diff program으로 만든다. Patch를 올바르게 적용하려면 어느 base에서 생성되었는지와 적용 후 source tree가 어느 version이 되는지를 알아야 한다. 두 정보는 patch metadata에 들어 있거나 filename으로 추론할 수 있어야 한다.

Patch 적용과 revert, -p1의 의미

37-65

patch program은 diff 또는 patch file을 읽고 그 안에 기술된 변경을 source tree에 적용한다. Linux kernel patch는 kernel source directory를 포함하는 parent directory를 기준으로 생성된다.

따라서 patch 안의 file path에는 patch를 만들 때 사용한 kernel source directory 이름이 포함되며, Git 형식 patch라면 a/와 b/ 같은 directory 이름이 들어갈 수 있다. 이 이름은 local kernel source directory 이름과 일치하지 않을 가능성이 크다. 다만 label이 없는 patch가 어느 version에서 만들어졌는지 추정하는 정보가 되기도 한다.

적용할 때는 kernel source directory로 이동한 다음 patch file path의 첫 번째 component를 제거한다. patch의 -p1 option이 이 동작을 수행한다.

patch -p1 < ../patch-x.y.z

patch -R -p1 < ../patch-x.y.z

첫 번째 명령은 patch를 적용한다. 앞서 적용한 patch를 되돌릴 때는 -R option을 추가한 두 번째 명령을 사용한다.

Patch file을 입력하는 여러 방법

67-108

UNIX 계열 system에서는 patch file을 여러 방식으로 patch program에 전달할 수 있다. 이 문서의 이후 예제는 uncompressed file을 stdin redirection으로 전달한다.

patch -p1 < path/to/patch-x.y.z

patch -p1 -i path/to/patch-x.y.z

첫 번째 형태만 알아도 이후 예제를 따라갈 수 있다. 두 번째 형태처럼 -i argument로 input filename을 직접 지정할 수도 있다.

gzip 또는 xz로 압축된 patch를 미리 풀지 않고 decompressor의 stdout을 pipe로 연결할 수도 있다.

xzcat path/to/patch-x.y.z.xz | patch -p1
bzcat path/to/patch-x.y.z.gz | patch -p1

두 번째 명령은 Linux v6.18.37 원문에 적힌 형태를 그대로 보존했다. Filename은 .gz인데 command는 bzip2용 bzcat이므로 실제 file compression 형식에 맞는 decompressor를 사용해야 한다.

먼저 수동으로 압축을 해제하려면 다음과 같이 실행한다. 결과로 생긴 plain-text patch-x.y.z file은 stdin 또는 -i 중 원하는 방식으로 전달할 수 있다.

gunzip patch-x.y.z.gz
xz -d patch-x.y.z.xz
  • -s: error를 제외한 일반 출력을 숨긴다. Error message가 빠르게 scroll되어 사라지는 일을 막는 데 유용하다.
  • --dry-run: 실제 file을 바꾸지 않고 어떤 작업이 수행될지만 출력한다.
  • --verbose: 수행 중인 작업에 대한 정보를 더 자세히 출력한다.

Context, fuzz, reject와 흔한 오류

111-206

Patch program은 patch file을 적용하면서 여러 sanity check를 수행한다. 입력이 유효한 patch 형태인지 확인하고, 수정될 code 주변이 patch에 기록된 context와 일치하는지 검사하는 것이 기본적인 예다.

무언가 정확히 맞지 않으면 patch는 변경 적용을 거부하고 중단하거나, 작은 조정을 통해 적용할 위치를 찾으려고 시도한다. 예를 들어 context와 변경 line 내용은 모두 같지만 file 앞부분에 line이 추가·삭제되어 line number만 달라졌다면, patch는 위치를 위아래로 옮겨 적용할 수 있다.

Patch가 내용을 맞추기 위해 일부 조정했다면 fuzz를 사용해 적용했다고 알린다. 대개 올바른 위치를 찾지만 항상 맞는 것은 아니므로 fuzz가 나온 결과는 주의해서 검토해야 한다.

Fuzz로도 적용할 수 없는 변경은 완전히 reject되며 .rej suffix의 reject file이 남는다. 이 file에는 적용하지 못한 변경이 들어 있어, 내용을 읽고 수동으로 source를 수정할 수 있다.

Third-party patch가 전혀 없고, 수정하지 않은 source에 kernel.org patch를 정확한 순서로 적용했다면 fuzz나 reject message가 나와서는 안 된다. 그런 message가 보이면 local source tree 또는 patch file이 손상되었을 가능성이 높다. Patch를 다시 download하고, 그래도 해결되지 않으면 kernel.org에서 전체 fresh tree를 다시 받는 편이 좋다.

Message뜻과 조치
File to patch:대상 file을 찾지 못했다. -p1 누락 또는 잘못된 working directory가 가장 흔하다. 드물게 -p0 patch일 수 있으며 patch path를 읽어 판단한다.
Hunk #2 succeeded at 1887 with fuzz 2 (offset 7 lines).예상 위치에서 7 line 이동하고 context 일부를 완화해 적용했다. File 차이의 원인에 따라 결과가 맞을 수도 틀릴 수도 있다.
Hunk #3 FAILED at 2387.Fuzz로도 hunk를 적용하지 못했다. 실패 변경은 .rej, 바뀌지 않은 원본 content는 .orig에 남는다.
Reversed (or previously applied) patch detected! Assume -R? [n]변경이 이미 적용된 것처럼 보인다. 중복 적용이면 n으로 중단하고, 실제 revert 목적이지만 -R을 빠뜨렸다면 y를 선택할 수 있다.
unexpected end of file in patch / unexpectedly ends in middle of line입력을 patch로 해석할 수 없다. Download 손상, 압축 file을 그대로 전달함, mail client나 transfer agent가 긴 line을 나눈 경우를 확인한다.

Fuzz와 offset은 다른 kernel version에서 만든 patch를 적용할 때 흔하다. Reverse detection은 patch 작성자가 source와 destination directory를 반대로 넣어 patch를 만들었을 때도 발생할 수 있으며, 이 경우 patch를 reverse하는 것이 실제로는 변경을 적용하는 결과가 된다.

Mail 전송 중 line 하나가 둘로 나뉘어 end-of-file warning이 발생했다면 갈라진 두 line을 다시 이어서 고칠 수 있는 경우가 많다. 그러나 정확한 version의 unmodified tree에 kernel.org patch를 적용했는데 이런 오류가 나오면 patch 또는 tree가 손상되었다고 보고 전체 source와 patch를 새로 받는 것이 권장된다.

interdiff, ketchup과 patchutils

209-239

patch program 외에도 대안이 있다. interdiff는 두 patch 사이 차이를 나타내는 새 patch를 생성하며 그 결과를 바로 적용할 수 있다. 예를 들어 5.7.2에서 5.7.3으로 한 단계에 이동할 수 있고, -z flag를 사용하면 zcat·bzcat 또는 수동 해제 없이 gzip·bzip2 압축 patch를 직접 입력할 수 있다.

interdiff -z ../patch-5.7.2.gz ../patch-5.7.3.gz | patch -p1

Interdiff는 한두 단계를 줄여 주지만 일부 경우 잘못된 결과를 낼 수 있으므로 일반적으로는 생략된 추가 단계를 직접 수행하는 것이 권장된다.

Ketchup은 patch를 자동 download하고 적용하는 Python script다. 그 밖의 도구로 diffstat은 patch 변경 summary를 보여 주고, lsdiff는 patch가 영향을 주는 file과 선택적으로 각 patch 시작 line number를 짧게 나열하며, grepdiff는 지정 regular expression이 포함된 변경 대상 file 목록을 보여 준다.

Patch download 위치

241-264

Patch는 https://kernel.org/ 에서 받을 수 있다. 최신 patch는 첫 화면에서 link되며 종류별 고정 위치도 있다.

일반 -rc patch는 webserver에 file로 저장하지 않고 Git tag 사이 차이에서 필요할 때 생성한다.

Base 5.x release 사이 이동

266-299

5.x kernel은 Linus가 release하는 base stable release이며 가장 높은 번호가 최신이다. Regression이나 심각한 결함이 발견되면 이 base 위에 -stable fix patch가 나온다. 새 5.x base kernel이 release되면 이전 5.x와 새 version 사이 delta patch도 제공된다.

5.6에서 5.7로 이동하는 patch는 base 5.6 위에 적용해야 하며 5.6.y 위에 직접 적용해서는 안 된다. 5.x.y에서 다음 5.x+1로 이동하려면 먼저 5.x.y patch를 revert해 base 5.x로 돌아가야 한다.

# moving from 5.6 to 5.7

$ cd ~/linux-5.6
$ patch -p1 < ../patch-5.7
$ cd ..
$ mv linux-5.6 linux-5.7

# moving from 5.6.1 to 5.7

$ cd ~/linux-5.6.1
$ patch -p1 -R < ../patch-5.6.1
# source dir is now 5.6
$ patch -p1 < ../patch-5.7
$ cd ..
$ mv linux-5.6.1 linux-5.7

5.x.y stable의 normal patch와 incremental patch

301-349

세 자리 version의 kernel은 -stable kernel이다. 특정 5.x kernel에서 발견된 security 문제나 중대한 regression을 위한 비교적 작은 critical fix를 포함한다. 최신 stable을 원하지만 development·experimental version test에는 참여하지 않으려는 사용자에게 권장되는 branch다. 5.x.y가 아직 없다면 번호가 가장 높은 5.x가 current stable이다.

Normal stable patch

Normal patch는 incremental하지 않다. 예를 들어 patch-5.7.3은 5.7.2 source 위가 아니라 base 5.7 source 위에 적용한다. 기존 5.7.2 tree를 5.7.3으로 만들려면 5.7.2 patch를 먼저 되돌려 base 5.7로 만든 뒤 5.7.3 patch를 적용한다.

$ cd ~/linux-5.7.2
$ patch -p1 -R < ../patch-5.7.2
$ patch -p1 < ../patch-5.7.3
$ cd ..
$ mv linux-5.7.2 linux-5.7.3

Incremental stable patch

Incremental patch는 base 5.x가 아니라 바로 이전 stable kernel 5.x.y-1 위에 적용한다. 5.7.2에서 5.7.3으로 이동하는 incremental patch filename은 예제에서 patch-5.7.2-3이다.

$ cd ~/linux-5.7.2
$ patch -p1 < ../patch-5.7.2-3
$ cd ..
$ mv linux-5.7.2 linux-5.7.3

Release candidate kernel patch

352-400

-rc는 release-candidate kernel이다. Linus가 현재 Git tree를 test하기에 충분히 정상적인 상태라고 판단할 때 release하는 development kernel이다. Stable하지 않아 때때로 깨질 것을 예상해야 하지만 주요 development branch 중에서는 가장 안정적이며 결국 다음 stable kernel이 될 code이므로 가능한 많은 사람이 test하는 것이 중요하다.

Development kernel test에는 참여하고 싶지만 매우 experimental한 code까지 실행하고 싶지는 않은 사람에게 적합하다. 더 실험적인 대상은 -next와 -mm 절에서 설명한다.

-rc patch는 incremental하지 않으며 5.x.y patch처럼 base 5.x kernel 위에 적용한다. -rcN 앞의 version은 이 release candidate가 최종적으로 될 kernel version이다. 따라서 5.8-rc5는 5.8의 다섯 번째 release candidate이고 patch는 5.7 base source 위에 적용한다.

# 5.7 -> 5.8-rc3
$ cd ~/linux-5.7
$ patch -p1 < ../patch-5.8-rc3
$ cd ..
$ mv linux-5.7 linux-5.8-rc3

# 5.8-rc3 -> 5.8-rc5
$ cd ~/linux-5.8-rc3
$ patch -p1 -R < ../patch-5.8-rc3
$ patch -p1 < ../patch-5.8-rc5
$ cd ..
$ mv linux-5.8-rc3 linux-5.8-rc5

# 5.7.3 -> 5.8-rc5
$ cd ~/linux-5.7.3
$ patch -p1 -R < ../patch-5.7.3
$ patch -p1 < ../patch-5.8-rc5
$ cd ..
$ mv linux-5.7.3 linux-5.8-rc5

-mm patch와 linux-next

403-444

-mm은 Andrew Morton이 release하는 experimental patch다. 과거에는 subsystem patch test에도 -mm tree를 사용했지만 현재 그 역할은 linux-next tree가 담당한다. Subsystem maintainer는 자신의 patch를 먼저 linux-next에 push하고 merge window 동안 Linus에게 직접 보낸다.

-mm patch는 subsystem tree를 거쳐 merge되지 않는 새 기능과 experimental patch의 시험장 역할을 한다. Patch가 -mm에서 일정 기간 가치를 증명하면 Andrew가 mainline 포함을 위해 Linus에게 보낸다.

Linux-next tree는 매일 갱신되며 -mm patch도 포함한다. 두 대상 모두 계속 변하고, mainline에 적합하지 않은 많은 experimental feature와 debugging patch를 포함하므로 이 문서에서 설명한 branch 중 가장 실험적이다.

안정적으로 동작해야 하는 system에는 적합하지 않으며 다른 branch보다 실행 위험이 크다. 모든 experimental kernel에 최신 backup이 필요하지만 -mm patch나 linux-next kernel에서는 특히 중요하다.

-mm과 linux-next의 목적은 변경이 더 안정적인 Linus mainline tree에 merge되기 전에 regression, crash, data corruption, build breakage와 기타 bug를 찾아 제거하는 것이다. 따라서 test는 크게 환영받지만 tester는 다른 tree보다 breakage가 흔하다는 점을 알아야 한다.

이것으로 여러 kernel tree에 대한 설명을 마친다. 원문은 review와 기여를 제공한 Randy Dunlap, Rolf Eike Beer, Linus Torvalds, Bodo Eggert, Johannes Stezenbach, Grant Coady, Pavel Machek 및 미처 이름을 적지 못한 이들에게 감사를 전한다.