← Documents Documentation/process/maintainer-tip.rst GitHub 원문 ↗

Linux 6.18.37 · Maintainer

tip tree handbook

x86, scheduler, locking, timer와 irq 변경을 다루는 tip branch 선택, changelog와 tag, testing, locking comment와 local coding rule을 설명합니다.

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

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

1. 요약·해설

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

Tip tree 범위와 branch 선택

maintainer-tip.rst:3-114

Tip tree는 x86 architecture와 scheduler, locking, timers, irq, RCU 연관 핵심 변경을 topic branch별로 관리한다. Patch는 subsystem prefix와 영향 code에 맞는 branch를 선택하고 urgent fix와 next-cycle feature를 구분한다.

Subject, changelog와 architecture 근거

maintainer-tip.rst:115-266

Subject는 영역과 변경 결과를 간결히 쓰고 changelog는 symptom, root cause, before·after state와 concurrency 영향을 설명한다. 단순 code narration이나 'cleanup'만으로 목적을 대신하지 않는다.

그림 1. 두 CPU에서 free_irq()와 interrupt thread가 겹치는 순서
CPU0CPU1
01 free_irq(X)interrupt X
02 spin_lock(desc->lock)
03 wake irq thread()
04 spin_unlock(desc->lock)
05 spin_lock(desc->lock)
06 remove action()
07 shutdown_irq()
08 release_resources()thread_handler()
09 spin_unlock(desc->lock)released resource 접근
10 synchronize_irq()

시간은 위에서 아래로 흐릅니다. CPU0이 action과 resource를 제거했는데 CPU1에서 이미 깨워 둔 interrupt thread가 뒤늦게 실행되면 해제된 자원에 접근할 수 있습니다. Changelog에는 함수 이름만 나열하지 말고 synchronize_irq()가 어느 시점보다 앞서야 하는지 이런 시간축으로 보여 주는 편이 race를 정확히 전달합니다.

그림 2. lockdep이 보고하는 CPU 간 lock 순서 역전
CPU0CPU1
01 rtmutex_lock(&rcu->rt_mutex)local_irq_disable()
02 hold: rcu wait_lockhold: timer lock
03 spin_lock(rcu wait_lock)
04 interrupt 진입CPU0 대기
05 spin_lock(timer lock)
06 CPU1 대기closed dependency cycle

CPU0은 rcu wait_lock을 보유한 채 interrupt에서 timer lock을 원하고, CPU1은 timer lock을 보유한 채 rcu wait_lock을 원합니다. 두 화살표가 닫힌 순환을 만들기 때문에 어느 CPU도 진행할 수 없습니다. 이처럼 동시성 결함은 CPU별 열과 아래 방향 시간축으로 적으면 lock ordering 근거가 드러납니다.

Function reference에는 ()를 붙이고 backtrace는 relevant call chain으로 줄인다. Hardware manual과 prior discussion은 stable public Link로 연결한다.

Commit tag 순서와 permission

maintainer-tip.rst:267-417

Reported, Suggested, Fixes, Closes·Link, Co-developed, Signed-off, Reviewed, Acked, Tested와 Cc tag는 의미와 시간 흐름에 맞게 정렬한다. 다른 사람의 tag는 permission rule을 지키고 patch가 크게 바뀌면 효력이 남는지 다시 확인한다.

Documentation link는 version이 사라지지 않는 canonical URL을 사용한다. Resend와 reminder는 최소 review 시간을 주고 수정된 patch를 RESEND로 표시하지 않는다.

Merge window, Git와 test

maintainer-tip.rst:418-475

Feature는 merge window 직전이 아니라 tip integration과 linux-next test 시간을 확보해 제출한다. Rebase로 public commit identity를 불필요하게 바꾸지 않고 dependency branch를 명확히 한다.

관련 config, architecture와 toolchain을 build하고 boot·selftest·performance regression을 확인한다. Core code는 PREEMPT, SMP, lockdep와 sanitizer configuration의 영향을 특히 검증한다.

Comment와 locking requirement

maintainer-tip.rst:476-646

Comment는 문장과 block 형식을 일관되게 쓰고 obvious code가 아니라 ordering과 invariant를 설명한다. Function이 특정 lock held, interrupts disabled, preemption disabled 또는 RCU read-side context를 요구한다면 declaration·kernel-doc 가까이에 명시한다.

Lockless code의 barrier는 paired operation과 관찰 순서를 설명한다. 단순히 'serialize'라고 쓰지 말고 어떤 load·store가 어느 CPU에서 먼저 보여야 하는지 적는다.

Tip code의 local style

maintainer-tip.rst:647-834

Variable declaration은 scope를 좁히고 type과 초기화를 읽기 쉽게 배치한다. Architecture width가 필요한 값은 정확한 type을 쓰고 magic number 대신 named constant와 BIT·GENMASK helper를 사용한다.

Struct initializer와 brace, line break는 주변 tip code의 compact convention을 따른다. Generic symbol은 namespace collision을 피할 prefix를 쓰고 x86 전용 helper는 architecture scope를 명확히 한다.

Commit notification

maintainer-tip.rst:835-849

Patch가 tip tree에 적용·변경·제외되면 automated notification을 확인한다. 적용된 branch와 commit을 test하고 metadata 오류나 잘못된 resolution을 발견하면 즉시 maintainer에게 답한다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 The tip tree handbook
4 =====================
5
6 What is the tip tree?
7 ---------------------
8
9 The tip tree is a collection of several subsystems and areas of
10 development. The tip tree is both a direct development tree and an
11 aggregation tree for several sub-maintainer trees. The tip tree gitweb URL
12 is: https://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git
13
14 The tip tree contains the following subsystems:
15
16 - **x86 architecture**
17
18 The x86 architecture development takes place in the tip tree except
19 for the x86 KVM and XEN specific parts which are maintained in the
20 corresponding subsystems and routed directly to mainline from
21 there. It's still good practice to Cc the x86 maintainers on
22 x86-specific KVM and XEN patches.
23
24 Some x86 subsystems have their own maintainers in addition to the
25 overall x86 maintainers. Please Cc the overall x86 maintainers on
26 patches touching files in arch/x86 even when they are not called out
27 by the MAINTAINER file.
28
29 Note, that ``[email protected]`` is not a mailing list. It is merely a
30 mail alias which distributes mails to the x86 top-level maintainer
31 team. Please always Cc the Linux Kernel mailing list (LKML)
32 ``[email protected]``, otherwise your mail ends up only in
33 the private inboxes of the maintainers.
34
35 - **Scheduler**
36
37 Scheduler development takes place in the -tip tree, in the
38 sched/core branch - with occasional sub-topic trees for
39 work-in-progress patch-sets.
40
41 - **Locking and atomics**
42
43 Locking development (including atomics and other synchronization
44 primitives that are connected to locking) takes place in the -tip
45 tree, in the locking/core branch - with occasional sub-topic trees
46 for work-in-progress patch-sets.
47
48 - **Generic interrupt subsystem and interrupt chip drivers**:
49
50 - interrupt core development happens in the irq/core branch
51
52 - interrupt chip driver development also happens in the irq/core
53 branch, but the patches are usually applied in a separate maintainer
54 tree and then aggregated into irq/core
55
56 - **Time, timers, timekeeping, NOHZ and related chip drivers**:
57
58 - timekeeping, clocksource core, NTP and alarmtimer development
59 happens in the timers/core branch, but patches are usually applied in
60 a separate maintainer tree and then aggregated into timers/core
61
62 - clocksource/event driver development happens in the timers/core
63 branch, but patches are mostly applied in a separate maintainer tree
64 and then aggregated into timers/core
65
66 - **Performance counters core, architecture support and tooling**:
67
68 - perf core and architecture support development happens in the
69 perf/core branch
70
71 - perf tooling development happens in the perf tools maintainer
72 tree and is aggregated into the tip tree.
73
74 - **CPU hotplug core**
75
76 - **RAS core**
77
78 Mostly x86-specific RAS patches are collected in the tip ras/core
79 branch.
80
81 - **EFI core**
82
83 EFI development in the efi git tree. The collected patches are
84 aggregated in the tip efi/core branch.
85
86 - **RCU**
87
88 RCU development happens in the linux-rcu tree. The resulting changes
89 are aggregated into the tip core/rcu branch.
90
91 - **Various core code components**:
92
93 - debugobjects
94
95 - objtool
96
97 - random bits and pieces
98
99
100 Patch submission notes
101 ----------------------
102
103 Selecting the tree/branch
104 ^^^^^^^^^^^^^^^^^^^^^^^^^
105
106 In general, development against the head of the tip tree master branch is
107 fine, but for the subsystems which are maintained separately, have their
108 own git tree and are only aggregated into the tip tree, development should
109 take place against the relevant subsystem tree or branch.
110
111 Bug fixes which target mainline should always be applicable against the
112 mainline kernel tree. Potential conflicts against changes which are already
113 queued in the tip tree are handled by the maintainers.
114
115 Patch subject
116 ^^^^^^^^^^^^^
117
118 The tip tree preferred format for patch subject prefixes is
119 'subsys/component:', e.g. 'x86/apic:', 'x86/mm/fault:', 'sched/fair:',
120 'genirq/core:'. Please do not use file names or complete file paths as
121 prefix. 'git log path/to/file' should give you a reasonable hint in most
122 cases.
123
124 The condensed patch description in the subject line should start with an
125 uppercase letter and should be written in imperative tone.
126
127
128 Changelog
129 ^^^^^^^^^
130
131 The general rules about changelogs in the :ref:`Submitting patches guide
132 <describe_changes>`, apply.
133
134 The tip tree maintainers set value on following these rules, especially on
135 the request to write changelogs in imperative mood and not impersonating
136 code or the execution of it. This is not just a whim of the
137 maintainers. Changelogs written in abstract words are more precise and
138 tend to be less confusing than those written in the form of novels.
139
140 It's also useful to structure the changelog into several paragraphs and not
141 lump everything together into a single one. A good structure is to explain
142 the context, the problem and the solution in separate paragraphs and this
143 order.
144
145 Examples for illustration:
146
147 Example 1::
148
149 x86/intel_rdt/mbm: Fix MBM overflow handler during hot cpu
150
151 When a CPU is dying, we cancel the worker and schedule a new worker on a
152 different CPU on the same domain. But if the timer is already about to
153 expire (say 0.99s) then we essentially double the interval.
154
155 We modify the hot cpu handling to cancel the delayed work on the dying
156 cpu and run the worker immediately on a different cpu in same domain. We
157 do not flush the worker because the MBM overflow worker reschedules the
158 worker on same CPU and scans the domain->cpu_mask to get the domain
159 pointer.
160
161 Improved version::
162
163 x86/intel_rdt/mbm: Fix MBM overflow handler during CPU hotplug
164
165 When a CPU is dying, the overflow worker is canceled and rescheduled on a
166 different CPU in the same domain. But if the timer is already about to
167 expire this essentially doubles the interval which might result in a non
168 detected overflow.
169
170 Cancel the overflow worker and reschedule it immediately on a different CPU
171 in the same domain. The work could be flushed as well, but that would
172 reschedule it on the same CPU.
173
174 Example 2::
175
176 time: POSIX CPU timers: Ensure that variable is initialized
177
178 If cpu_timer_sample_group returns -EINVAL, it will not have written into
179 *sample. Checking for cpu_timer_sample_group's return value precludes the
180 potential use of an uninitialized value of now in the following block.
181 Given an invalid clock_idx, the previous code could otherwise overwrite
182 *oldval in an undefined manner. This is now prevented. We also exploit
183 short-circuiting of && to sample the timer only if the result will
184 actually be used to update *oldval.
185
186 Improved version::
187
188 posix-cpu-timers: Make set_process_cpu_timer() more robust
189
190 Because the return value of cpu_timer_sample_group() is not checked,
191 compilers and static checkers can legitimately warn about a potential use
192 of the uninitialized variable 'now'. This is not a runtime issue as all
193 call sites hand in valid clock ids.
194
195 Also cpu_timer_sample_group() is invoked unconditionally even when the
196 result is not used because *oldval is NULL.
197
198 Make the invocation conditional and check the return value.
199
200 Example 3::
201
202 The entity can also be used for other purposes.
203
204 Let's rename it to be more generic.
205
206 Improved version::
207
208 The entity can also be used for other purposes.
209
210 Rename it to be more generic.
211
212
213 For complex scenarios, especially race conditions and memory ordering
214 issues, it is valuable to depict the scenario with a table which shows
215 the parallelism and the temporal order of events. Here is an example::
216
217 CPU0 CPU1
218 free_irq(X) interrupt X
219 spin_lock(desc->lock)
220 wake irq thread()
221 spin_unlock(desc->lock)
222 spin_lock(desc->lock)
223 remove action()
224 shutdown_irq()
225 release_resources() thread_handler()
226 spin_unlock(desc->lock) access released resources.
227 ^^^^^^^^^^^^^^^^^^^^^^^^^
228 synchronize_irq()
229
230 Lockdep provides similar useful output to depict a possible deadlock
231 scenario::
232
233 CPU0 CPU1
234 rtmutex_lock(&rcu->rt_mutex)
235 spin_lock(&rcu->rt_mutex.wait_lock)
236 local_irq_disable()
237 spin_lock(&timer->it_lock)
238 spin_lock(&rcu->mutex.wait_lock)
239 --> Interrupt
240 spin_lock(&timer->it_lock)
241
242
243 Function references in changelogs
244 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
245
246 When a function is mentioned in the changelog, either the text body or the
247 subject line, please use the format 'function_name()'. Omitting the
248 brackets after the function name can be ambiguous::
249
250 Subject: subsys/component: Make reservation_count static
251
252 reservation_count is only used in reservation_stats. Make it static.
253
254 The variant with brackets is more precise::
255
256 Subject: subsys/component: Make reservation_count() static
257
258 reservation_count() is only called from reservation_stats(). Make it
259 static.
260
261
262 Backtraces in changelogs
263 ^^^^^^^^^^^^^^^^^^^^^^^^
264
265 See :ref:`backtraces`.
266
267 Ordering of commit tags
268 ^^^^^^^^^^^^^^^^^^^^^^^
269
270 To have a uniform view of the commit tags, the tip maintainers use the
271 following tag ordering scheme:
272
273 - Fixes: 12+char-SHA1 ("sub/sys: Original subject line")
274
275 A Fixes tag should be added even for changes which do not need to be
276 backported to stable kernels, i.e. when addressing a recently introduced
277 issue which only affects tip or the current head of mainline. These tags
278 are helpful to identify the original commit and are much more valuable
279 than prominently mentioning the commit which introduced a problem in the
280 text of the changelog itself because they can be automatically
281 extracted.
282
283 The following example illustrates the difference::
284
285 Commit
286
287 abcdef012345678 ("x86/xxx: Replace foo with bar")
288
289 left an unused instance of variable foo around. Remove it.
290
291 Signed-off-by: J.Dev <j.dev@mail>
292
293 Please say instead::
294
295 The recent replacement of foo with bar left an unused instance of
296 variable foo around. Remove it.
297
298 Fixes: abcdef012345678 ("x86/xxx: Replace foo with bar")
299 Signed-off-by: J.Dev <j.dev@mail>
300
301 The latter puts the information about the patch into the focus and
302 amends it with the reference to the commit which introduced the issue
303 rather than putting the focus on the original commit in the first place.
304
305 - Reported-by: ``Reporter <reporter@mail>``
306
307 - Closes: ``URL or Message-ID of the bug report this is fixing``
308
309 - Originally-by: ``Original author <original-author@mail>``
310
311 - Suggested-by: ``Suggester <suggester@mail>``
312
313 - Co-developed-by: ``Co-author <co-author@mail>``
314
315 Signed-off-by: ``Co-author <co-author@mail>``
316
317 Note, that Co-developed-by and Signed-off-by of the co-author(s) must
318 come in pairs.
319
320 - Signed-off-by: ``Author <author@mail>``
321
322 The first Signed-off-by (SOB) after the last Co-developed-by/SOB pair is the
323 author SOB, i.e. the person flagged as author by git.
324
325 - Signed-off-by: ``Patch handler <handler@mail>``
326
327 SOBs after the author SOB are from people handling and transporting
328 the patch, but were not involved in development. SOB chains should
329 reflect the **real** route a patch took as it was propagated to us,
330 with the first SOB entry signalling primary authorship of a single
331 author. Acks should be given as Acked-by lines and review approvals
332 as Reviewed-by lines.
333
334 If the handler made modifications to the patch or the changelog, then
335 this should be mentioned **after** the changelog text and **above**
336 all commit tags in the following format::
337
338 ... changelog text ends.
339
340 [ handler: Replaced foo by bar and updated changelog ]
341
342 First-tag: .....
343
344 Note the two empty new lines which separate the changelog text and the
345 commit tags from that notice.
346
347 If a patch is sent to the mailing list by a handler then the author has
348 to be noted in the first line of the changelog with::
349
350 From: Author <author@mail>
351
352 Changelog text starts here....
353
354 so the authorship is preserved. The 'From:' line has to be followed
355 by a empty newline. If that 'From:' line is missing, then the patch
356 would be attributed to the person who sent (transported, handled) it.
357 The 'From:' line is automatically removed when the patch is applied
358 and does not show up in the final git changelog. It merely affects
359 the authorship information of the resulting Git commit.
360
361 - Tested-by: ``Tester <tester@mail>``
362
363 - Reviewed-by: ``Reviewer <reviewer@mail>``
364
365 - Acked-by: ``Acker <acker@mail>``
366
367 - Cc: ``cc-ed-person <person@mail>``
368
369 If the patch should be backported to stable, then please add a '``Cc:
370 [email protected]``' tag, but do not Cc stable when sending your
371 mail.
372
373 - Link: ``https://link/to/information``
374
375 For referring to an email posted to the kernel mailing lists, please
376 use the lore.kernel.org redirector URL::
377
378 Link: https://lore.kernel.org/email-message-id@here
379
380 This URL should be used when referring to relevant mailing list
381 topics, related patch sets, or other notable discussion threads.
382 A convenient way to associate ``Link:`` trailers with the commit
383 message is to use markdown-like bracketed notation, for example::
384
385 A similar approach was attempted before as part of a different
386 effort [1], but the initial implementation caused too many
387 regressions [2], so it was backed out and reimplemented.
388
389 Link: https://lore.kernel.org/some-msgid@here # [1]
390 Link: https://bugzilla.example.org/bug/12345 # [2]
391
392 You can also use ``Link:`` trailers to indicate the origin of the
393 patch when applying it to your git tree. In that case, please use the
394 dedicated ``patch.msgid.link`` domain instead of ``lore.kernel.org``.
395 This practice makes it possible for automated tooling to identify
396 which link to use to retrieve the original patch submission. For
397 example::
398
399 Link: https://patch.msgid.link/patch-source-message-id@here
400
401 Please do not use combined tags, e.g. ``Reported-and-tested-by``, as
402 they just complicate automated extraction of tags.
403
404
405 Links to documentation
406 ^^^^^^^^^^^^^^^^^^^^^^
407
408 Providing links to documentation in the changelog is a great help to later
409 debugging and analysis. Unfortunately, URLs often break very quickly
410 because companies restructure their websites frequently. Non-'volatile'
411 exceptions include the Intel SDM and the AMD APM.
412
413 Therefore, for 'volatile' documents, please create an entry in the kernel
414 bugzilla https://bugzilla.kernel.org and attach a copy of these documents
415 to the bugzilla entry. Finally, provide the URL of the bugzilla entry in
416 the changelog.
417
418 Patch resend or reminders
419 ^^^^^^^^^^^^^^^^^^^^^^^^^
420
421 See :ref:`resend_reminders`.
422
423 Merge window
424 ^^^^^^^^^^^^
425
426 Please do not expect patches to be reviewed or merged by tip
427 maintainers around or during the merge window. The trees are closed
428 to all but urgent fixes during this time. They reopen once the merge
429 window closes and a new -rc1 kernel has been released.
430
431 Large series should be submitted in mergeable state *at* *least* a week
432 before the merge window opens. Exceptions are made for bug fixes and
433 *sometimes* for small standalone drivers for new hardware or minimally
434 invasive patches for hardware enablement.
435
436 During the merge window, the maintainers instead focus on following the
437 upstream changes, fixing merge window fallout, collecting bug fixes, and
438 allowing themselves a breath. Please respect that.
439
440 So called _urgent_ branches will be merged into mainline during the
441 stabilization phase of each release.
442
443
444 Git
445 ^^^
446
447 The tip maintainers accept git pull requests from maintainers who provide
448 subsystem changes for aggregation in the tip tree.
449
450 Pull requests for new patch submissions are usually not accepted and do not
451 replace proper patch submission to the mailing list. The main reason for
452 this is that the review workflow is email based.
453
454 If you submit a larger patch series it is helpful to provide a git branch
455 in a private repository which allows interested people to easily pull the
456 series for testing. The usual way to offer this is a git URL in the cover
457 letter of the patch series.
458
459 Testing
460 ^^^^^^^
461
462 Code should be tested before submitting to the tip maintainers. Anything
463 other than minor changes should be built, booted and tested with
464 comprehensive (and heavyweight) kernel debugging options enabled.
465
466 These debugging options can be found in kernel/configs/x86_debug.config
467 and can be added to an existing kernel config by running:
468
469 make x86_debug.config
470
471 Some of these options are x86-specific and can be left out when testing
472 on other architectures.
473
474 .. _maintainer-tip-coding-style:
475
476 Coding style notes
477 ------------------
478
479 Comment style
480 ^^^^^^^^^^^^^
481
482 Sentences in comments start with an uppercase letter.
483
484 Single line comments::
485
486 /* This is a single line comment */
487
488 Multi-line comments::
489
490 /*
491 * This is a properly formatted
492 * multi-line comment.
493 *
494 * Larger multi-line comments should be split into paragraphs.
495 */
496
497 No tail comments (see below):
498
499 Please refrain from using tail comments. Tail comments disturb the
500 reading flow in almost all contexts, but especially in code::
501
502 if (somecondition_is_true) /* Don't put a comment here */
503 dostuff(); /* Neither here */
504
505 seed = MAGIC_CONSTANT; /* Nor here */
506
507 Use freestanding comments instead::
508
509 /* This condition is not obvious without a comment */
510 if (somecondition_is_true) {
511 /* This really needs to be documented */
512 dostuff();
513 }
514
515 /* This magic initialization needs a comment. Maybe not? */
516 seed = MAGIC_CONSTANT;
517
518 Use C++ style, tail comments when documenting structs in headers to
519 achieve a more compact layout and better readability::
520
521 // eax
522 u32 x2apic_shift : 5, // Number of bits to shift APIC ID right
523 // for the topology ID at the next level
524 : 27; // Reserved
525 // ebx
526 u32 num_processors : 16, // Number of processors at current level
527 : 16; // Reserved
528
529 versus::
530
531 /* eax */
532 /*
533 * Number of bits to shift APIC ID right for the topology ID
534 * at the next level
535 */
536 u32 x2apic_shift : 5,
537 /* Reserved */
538 : 27;
539
540 /* ebx */
541 /* Number of processors at current level */
542 u32 num_processors : 16,
543 /* Reserved */
544 : 16;
545
546 Comment the important things:
547
548 Comments should be added where the operation is not obvious. Documenting
549 the obvious is just a distraction::
550
551 /* Decrement refcount and check for zero */
552 if (refcount_dec_and_test(&p->refcnt)) {
553 do;
554 lots;
555 of;
556 magic;
557 things;
558 }
559
560 Instead, comments should explain the non-obvious details and document
561 constraints::
562
563 if (refcount_dec_and_test(&p->refcnt)) {
564 /*
565 * Really good explanation why the magic things below
566 * need to be done, ordering and locking constraints,
567 * etc..
568 */
569 do;
570 lots;
571 of;
572 magic;
573 /* Needs to be the last operation because ... */
574 things;
575 }
576
577 Function documentation comments:
578
579 To document functions and their arguments please use kernel-doc format
580 and not free form comments::
581
582 /**
583 * magic_function - Do lots of magic stuff
584 * @magic: Pointer to the magic data to operate on
585 * @offset: Offset in the data array of @magic
586 *
587 * Deep explanation of mysterious things done with @magic along
588 * with documentation of the return values.
589 *
590 * Note, that the argument descriptors above are arranged
591 * in a tabular fashion.
592 */
593
594 This applies especially to globally visible functions and inline
595 functions in public header files. It might be overkill to use kernel-doc
596 format for every (static) function which needs a tiny explanation. The
597 usage of descriptive function names often replaces these tiny comments.
598 Apply common sense as always.
599
600
601 Documenting locking requirements
602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
603 Documenting locking requirements is a good thing, but comments are not
604 necessarily the best choice. Instead of writing::
605
606 /* Caller must hold foo->lock */
607 void func(struct foo *foo)
608 {
609 ...
610 }
611
612 Please use::
613
614 void func(struct foo *foo)
615 {
616 lockdep_assert_held(&foo->lock);
617 ...
618 }
619
620 In PROVE_LOCKING kernels, lockdep_assert_held() emits a warning
621 if the caller doesn't hold the lock. Comments can't do that.
622
623 Bracket rules
624 ^^^^^^^^^^^^^
625
626 Brackets should be omitted only if the statement which follows 'if', 'for',
627 'while' etc. is truly a single line::
628
629 if (foo)
630 do_something();
631
632 The following is not considered to be a single line statement even
633 though C does not require brackets::
634
635 for (i = 0; i < end; i++)
636 if (foo[i])
637 do_something(foo[i]);
638
639 Adding brackets around the outer loop enhances the reading flow::
640
641 for (i = 0; i < end; i++) {
642 if (foo[i])
643 do_something(foo[i]);
644 }
645
646
647 Variable declarations
648 ^^^^^^^^^^^^^^^^^^^^^
649
650 The preferred ordering of variable declarations at the beginning of a
651 function is reverse fir tree order::
652
653 struct long_struct_name *descriptive_name;
654 unsigned long foo, bar;
655 unsigned int tmp;
656 int ret;
657
658 The above is faster to parse than the reverse ordering::
659
660 int ret;
661 unsigned int tmp;
662 unsigned long foo, bar;
663 struct long_struct_name *descriptive_name;
664
665 And even more so than random ordering::
666
667 unsigned long foo, bar;
668 int ret;
669 struct long_struct_name *descriptive_name;
670 unsigned int tmp;
671
672 Also please try to aggregate variables of the same type into a single
673 line. There is no point in wasting screen space::
674
675 unsigned long a;
676 unsigned long b;
677 unsigned long c;
678 unsigned long d;
679
680 It's really sufficient to do::
681
682 unsigned long a, b, c, d;
683
684 Please also refrain from introducing line splits in variable declarations::
685
686 struct long_struct_name *descriptive_name = container_of(bar,
687 struct long_struct_name,
688 member);
689 struct foobar foo;
690
691 It's way better to move the initialization to a separate line after the
692 declarations::
693
694 struct long_struct_name *descriptive_name;
695 struct foobar foo;
696
697 descriptive_name = container_of(bar, struct long_struct_name, member);
698
699
700 Variable types
701 ^^^^^^^^^^^^^^
702
703 Please use the proper u8, u16, u32, u64 types for variables which are meant
704 to describe hardware or are used as arguments for functions which access
705 hardware. These types are clearly defining the bit width and avoid
706 truncation, expansion and 32/64-bit confusion.
707
708 u64 is also recommended in code which would become ambiguous for 32-bit
709 kernels when 'unsigned long' would be used instead. While in such
710 situations 'unsigned long long' could be used as well, u64 is shorter
711 and also clearly shows that the operation is required to be 64 bits wide
712 independent of the target CPU.
713
714 Please use 'unsigned int' instead of 'unsigned'.
715
716
717 Constants
718 ^^^^^^^^^
719
720 Please do not use literal (hexa)decimal numbers in code or initializers.
721 Either use proper defines which have descriptive names or consider using
722 an enum.
723
724
725 Struct declarations and initializers
726 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
727
728 Struct declarations should align the struct member names in a tabular
729 fashion::
730
731 struct bar_order {
732 unsigned int guest_id;
733 int ordered_item;
734 struct menu *menu;
735 };
736
737 Please avoid documenting struct members within the declaration, because
738 this often results in strangely formatted comments and the struct members
739 become obfuscated::
740
741 struct bar_order {
742 unsigned int guest_id; /* Unique guest id */
743 int ordered_item;
744 /* Pointer to a menu instance which contains all the drinks */
745 struct menu *menu;
746 };
747
748 Instead, please consider using the kernel-doc format in a comment preceding
749 the struct declaration, which is easier to read and has the added advantage
750 of including the information in the kernel documentation, for example, as
751 follows::
752
753
754 /**
755 * struct bar_order - Description of a bar order
756 * @guest_id: Unique guest id
757 * @ordered_item: The item number from the menu
758 * @menu: Pointer to the menu from which the item
759 * was ordered
760 *
761 * Supplementary information for using the struct.
762 *
763 * Note, that the struct member descriptors above are arranged
764 * in a tabular fashion.
765 */
766 struct bar_order {
767 unsigned int guest_id;
768 int ordered_item;
769 struct menu *menu;
770 };
771
772 Static struct initializers must use C99 initializers and should also be
773 aligned in a tabular fashion::
774
775 static struct foo statfoo = {
776 .a = 0,
777 .plain_integer = CONSTANT_DEFINE_OR_ENUM,
778 .bar = &statbar,
779 };
780
781 Note that while C99 syntax allows the omission of the final comma,
782 we recommend the use of a comma on the last line because it makes
783 reordering and addition of new lines easier, and makes such future
784 patches slightly easier to read as well.
785
786 Line breaks
787 ^^^^^^^^^^^
788
789 Restricting line length to 80 characters makes deeply indented code hard to
790 read. Consider breaking out code into helper functions to avoid excessive
791 line breaking.
792
793 The 80 character rule is not a strict rule, so please use common sense when
794 breaking lines. Especially format strings should never be broken up.
795
796 When splitting function declarations or function calls, then please align
797 the first argument in the second line with the first argument in the first
798 line::
799
800 static int long_function_name(struct foobar *barfoo, unsigned int id,
801 unsigned int offset)
802 {
803
804 if (!id) {
805 ret = longer_function_name(barfoo, DEFAULT_BARFOO_ID,
806 offset);
807 ...
808
809 Namespaces
810 ^^^^^^^^^^
811
812 Function/variable namespaces improve readability and allow easy
813 grepping. These namespaces are string prefixes for globally visible
814 function and variable names, including inlines. These prefixes should
815 combine the subsystem and the component name such as 'x86_comp\_',
816 'sched\_', 'irq\_', and 'mutex\_'.
817
818 This also includes static file scope functions that are immediately put
819 into globally visible driver templates - it's useful for those symbols
820 to carry a good prefix as well, for backtrace readability.
821
822 Namespace prefixes may be omitted for local static functions and
823 variables. Truly local functions, only called by other local functions,
824 can have shorter descriptive names - our primary concern is greppability
825 and backtrace readability.
826
827 Please note that 'xxx_vendor\_' and 'vendor_xxx_` prefixes are not
828 helpful for static functions in vendor-specific files. After all, it
829 is already clear that the code is vendor-specific. In addition, vendor
830 names should only be for truly vendor-specific functionality.
831
832 As always apply common sense and aim for consistency and readability.
833
834
835 Commit notifications
836 --------------------
837
838 The tip tree is monitored by a bot for new commits. The bot sends an email
839 for each new commit to a dedicated mailing list
840 (``[email protected]``) and Cc's all people who are
841 mentioned in one of the commit tags. It uses the email message ID from the
842 Link tag at the end of the tag list to set the In-Reply-To email header so
843 the message is properly threaded with the patch submission email.
844
845 The tip maintainers and submaintainers try to reply to the submitter
846 when merging a patch, but they sometimes forget or it does not fit the
847 workflow of the moment. While the bot message is purely mechanical, it
848 also implies a 'Thank you! Applied.'.
849

3. 한국어 전문 번역

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

Tip tree의 역할과 subsystem

1-98

Tip tree는 여러 subsystem과 development area의 집합이다. 직접 개발하는 tree인 동시에 여러 sub-maintainer tree를 모으는 aggregation tree다.

x86 architecture

x86 KVM과 XEN 전용 부분을 제외한 x86 architecture development는 tip tree에서 이루어진다. KVM과 XEN 부분은 각 subsystem이 관리해 mainline으로 직접 보낸다. 그래도 x86-specific KVM·XEN patch에는 x86 maintainer를 CC하는 것이 좋은 practice다.

일부 x86 subsystem에는 전체 x86 maintainer 외에 별도 maintainer가 있다. MAINTAINERS가 전체 x86 maintainer를 표시하지 않더라도 arch/x86 file을 건드리는 patch에는 이들을 CC한다.

[email protected]는 mailing list가 아니라 x86 top-level maintainer team으로 전달하는 mail alias다. LKML [email protected]를 항상 CC해야 한다. 그렇지 않으면 mail이 maintainer의 private inbox에만 들어간다.

Core subsystem branch

영역Tip branch와 흐름
Schedulersched/core에서 개발하며 WIP patchset에는 가끔 sub-topic tree를 쓴다.
Locking·atomicslocking/core에서 개발하며 관련 synchronization primitive도 포함한다.
Generic interrupt·irqchipCore는 irq/core, chip driver도 irq/core로 모이지만 보통 별도 maintainer tree에 먼저 적용한다.
Time·timer·timekeeping·NOHZtimekeeping, clocksource core, NTP, alarmtimer와 driver를 별도 maintainer tree에서 받아 timers/core로 모은다.
Performance counterCore와 architecture support는 perf/core, perf tool은 별도 tool maintainer tree에서 받아 모은다.
CPU hotplugCPU hotplug core
RAS주로 x86-specific RAS patch를 ras/core에 모은다.
EFIEFI git tree에서 개발하고 결과를 efi/core에 모은다.
RCUlinux-rcu tree에서 개발하고 core/rcu에 모은다.
기타 core componentdebugobjects, objtool, 기타 작은 core 변경

대상 tree·branch와 patch subject

100-126

일반적으로 tip tree master head를 기준으로 개발해도 된다. 그러나 별도로 관리되고 자체 git tree를 가지며 tip에는 aggregation만 되는 subsystem은 해당 subsystem tree 또는 branch를 기준으로 개발한다.

Mainline을 대상으로 하는 bug fix는 항상 mainline kernel tree에 적용 가능해야 한다. Tip tree에 이미 queue된 change와의 conflict는 maintainer가 처리한다.

Tip tree가 선호하는 subject prefix는 subsys/component: 형식이다. 예를 들면 x86/apic:, x86/mm/fault:, sched/fair:, genirq/core:다. File name이나 전체 path를 prefix로 쓰지 않는다. 대부분 git log path/to/file에서 적절한 hint를 찾을 수 있다.

Subject line의 압축된 patch description은 uppercase letter로 시작하고 imperative tone으로 쓴다.

Changelog 구조와 표현

128-212

Submitting patches guide의 changelog 일반 규칙을 따른다. Tip maintainer는 imperative mood로 쓰고 code나 code execution을 의인화하지 말라는 규칙을 특히 중시한다. 추상적이고 직접적인 표현은 소설처럼 쓴 문장보다 정확하고 덜 혼란스럽다.

모든 내용을 한 paragraph에 몰지 말고 context, problem, solution을 각각 분리해 이 순서로 쓴다.

예 1: CPU hotplug의 MBM overflow

원래 subject “x86/intel_rdt/mbm: Fix MBM overflow handler during hot cpu”는 dying CPU에서 worker를 cancel하고 같은 domain의 다른 CPU에 새 worker를 schedule하지만 timer가 0.99초처럼 expire 직전이면 interval이 사실상 두 배가 된다고 설명한다. 해결 문장은 dying CPU의 delayed work를 cancel하고 다른 CPU에서 즉시 worker를 실행하며, worker가 같은 CPU에 자신을 reschedule하고 domain->cpu_mask를 scan하므로 flush하지 않는다고 길게 서술한다.

개선본 subject는 “x86/intel_rdt/mbm: Fix MBM overflow handler during CPU hotplug”다. Context와 problem을 나눠 expire 직전 reschedule이 interval을 두 배로 만들어 overflow를 놓칠 수 있다고 분명히 한다. Solution은 worker를 cancel하고 같은 domain의 다른 CPU에 즉시 reschedule한다고 명령형으로 쓴다. Flush도 가능하지만 같은 CPU에 reschedule된다는 tradeoff를 덧붙인다.

예 2: POSIX CPU timer

원문은 cpu_timer_sample_group이 -EINVAL을 반환하면 *sample을 쓰지 않으므로 return value를 검사해 now의 uninitialized use를 막고 invalid clock_idx가 *oldval을 undefined하게 덮어쓰는 일을 예방한다고 서술한다. && short-circuit로 결과가 실제 사용될 때만 timer를 sample한다고도 말한다.

개선본 subject는 “posix-cpu-timers: Make set_process_cpu_timer() more robust”다. Return value를 검사하지 않아 compiler와 static checker가 now의 uninitialized use를 정당하게 경고하지만 모든 call site가 valid clock ID를 넘겨 runtime issue는 아니라고 context를 바로잡는다. *oldval이 NULL이라 결과를 쓰지 않을 때도 cpu_timer_sample_group()을 무조건 호출한다는 별도 문제를 적고, invocation을 conditional하게 만들고 return value를 검사하라고 solution을 간결히 제시한다.

예 3: imperative mood

“The entity can also be used for other purposes. Let's rename it to be more generic.”보다 “The entity can also be used for other purposes. Rename it to be more generic.”처럼 직접적인 명령형을 사용한다.

Race와 deadlock을 changelog에서 시각화하기

213-242

복잡한 race condition과 memory ordering issue는 CPU별 parallelism과 event의 시간 순서를 table로 보여 주면 가치가 크다.

그림 1. free_irq()와 interrupt thread 사이의 use-after-free
CPU0CPU1
01 free_irq(X)interrupt X
02 spin_lock(desc->lock)
03 wake irq thread()
04 spin_unlock(desc->lock)
05 spin_lock(desc->lock)
06 remove action()
07 shutdown_irq()
08 release_resources()thread_handler()
09 spin_unlock(desc->lock)released resource 접근
10 synchronize_irq()

CPU0가 desc lock 아래에서 action을 제거하고 resource를 release하지만 synchronize_irq()가 뒤에 있다. CPU1의 이미 깨어난 thread_handler()가 해제된 resource에 접근할 수 있다.

Lockdep output도 possible deadlock scenario를 같은 방식으로 유용하게 보여 준다.

그림 2. rtmutex wait_lock과 timer lock의 inversion
CPU0CPU1
01 rtmutex_lock(&rcu->rt_mutex)
02 spin_lock(&rcu->rt_mutex.wait_lock)
03 local_irq_disable()
04 spin_lock(&timer->it_lock)
05 spin_lock(&rcu->mutex.wait_lock)
06 Interrupt 진입
07 spin_lock(&timer->it_lock)

CPU0은 rcu rt_mutex의 wait_lock을 잡은 상태에서 interrupt되어 timer->it_lock을 기다린다. CPU1은 timer->it_lock 뒤 rcu wait_lock을 기다린다.

Function 표기와 commit tag 순서

243-403

Function reference

Subject나 changelog 본문에서 function을 언급할 때는 function_name() 형식을 사용한다. 괄호를 생략하면 variable인지 function인지 모호하다. “Make reservation_count static”보다 “Make reservation_count() static”, “reservation_count is only used in reservation_stats”보다 “reservation_count() is only called from reservation_stats()”가 정확하다. Backtrace는 backtraces 지침을 따른다.

Fixes tag

첫 tag는 Fixes: 12+char-SHA1 ("sub/sys: Original subject line") 형식이다. Stable backport가 필요 없는 tip 또는 current mainline head의 최근 issue에도 붙인다. Machine이 자동 추출할 수 있어 culprit commit을 changelog 본문 첫머리에서 강조하는 것보다 유용하다.

The recent replacement of foo with bar left an unused instance of
variable foo around. Remove it.

Fixes: abcdef012345678 ("x86/xxx: Replace foo with bar")
Signed-off-by: J.Dev <j.dev@mail>

이 형식은 original commit이 아니라 현재 patch의 문제와 해결을 중심에 두고, culprit reference를 metadata로 보충한다.

전체 tag ordering

  • Fixes: 12+char-SHA1 ("subject")
  • Reported-by: Reporter <reporter@mail>
  • Closes: bug report URL 또는 Message-ID
  • Originally-by: Original author <original-author@mail>
  • Suggested-by: Suggester <suggester@mail>
  • Co-developed-by: Co-author <co-author@mail>와 바로 이어지는 같은 사람의 Signed-off-by pair
  • Signed-off-by: Author <author@mail>
  • Signed-off-by: Patch handler <handler@mail>
  • Tested-by: Tester <tester@mail>
  • Reviewed-by: Reviewer <reviewer@mail>
  • Acked-by: Acker <acker@mail>
  • Cc: cc-ed-person <person@mail>
  • Link: 관련 정보 URL

마지막 Co-developed-by/SOB pair 뒤의 첫 Signed-off-by가 git author의 SOB다. 이후 SOB는 개발에 참여하지 않고 patch를 운반한 handler의 실제 경로를 나타낸다. Single author라면 첫 SOB가 primary authorship을 뜻한다. Ack는 Acked-by, review approval은 Reviewed-by로 쓴다.

Handler가 patch 또는 changelog를 수정했다면 changelog 본문 뒤, 모든 tag 앞에 다음 notice를 넣는다. Changelog와 notice 사이, notice와 tag 사이에 empty line이 각각 있어야 한다.

... changelog text ends.

[ handler: Replaced foo by bar and updated changelog ]

First-tag: .....

Handler가 author 대신 mailing list에 patch를 보낸다면 changelog 첫 line에 From: Author <author@mail>를 쓰고 empty line 뒤 본문을 시작한다. 누락하면 sender가 author로 기록된다. Apply 시 From: line은 final git changelog에서 제거되고 resulting commit의 authorship만 설정한다.

From: Author <author@mail>

Changelog text starts here....

Stable backport 대상은 Cc: [email protected] tag를 넣되 mail 발송 때 stable address를 실제 CC하지 않는다.

Mailing list email reference는 lore.kernel.org redirector URL을 사용한다. 관련 topic, patchset, discussion을 가리킨다. 본문에 [1], [2]를 두고 대응 Link trailer 뒤 comment로 번호를 붙일 수 있다.

A similar approach was attempted before as part of a different
effort [1], but the initial implementation caused too many
regressions [2], so it was backed out and reimplemented.

Link: https://lore.kernel.org/some-msgid@here # [1]
Link: https://bugzilla.example.org/bug/12345  # [2]

Git tree에 apply한 original patch submission을 가리킬 때는 automated tool이 retrieval link를 식별하도록 lore.kernel.org 대신 patch.msgid.link domain을 쓴다.

Link: https://patch.msgid.link/patch-source-message-id@here

Reported-and-tested-by 같은 combined tag는 automated extraction을 복잡하게 하므로 사용하지 않는다.

Documentation link, resend와 merge window

405-442

Changelog에 documentation link를 제공하면 나중 debug와 analysis에 큰 도움이 된다. 하지만 company website가 재구성되며 URL이 빨리 깨지는 경우가 많다. Intel SDM과 AMD APM은 상대적으로 non-volatile한 예외다.

변동 가능성이 큰 document는 kernel Bugzilla에 entry를 만들고 document copy를 attachment로 올린 뒤 changelog에 그 Bugzilla URL을 제공한다. Patch resend와 reminder는 resend_reminders 지침을 따른다.

Merge window 전후에는 tip maintainer가 patch를 review하거나 merge할 것이라고 기대하지 않는다. Urgent fix를 제외하고 tree가 닫히며 merge window 종료와 새 -rc1 release 뒤 다시 열린다.

Large series는 merge window 시작 최소 1주 전에 merge 가능한 상태로 제출한다. Bug fix, 새 hardware의 작은 standalone driver, minimally invasive hardware enablement patch는 때때로 예외가 된다.

Merge window 동안 maintainer는 upstream change 추적, merge fallout 수정, bug fix 수집과 휴식에 집중한다. Urgent branch는 각 release stabilization phase에 mainline으로 merge된다.

Git pull request와 test 기준

444-472

Tip maintainer는 tip tree aggregation용 subsystem change를 제공하는 maintainer의 git pull request를 받는다.

새 patch submission을 pull request로 보내는 것은 보통 받지 않으며 mailing list의 올바른 patch submission을 대체하지 않는다. Review workflow가 email 기반이기 때문이다.

큰 patch series라면 test하려는 사람이 쉽게 pull할 수 있도록 private repository의 git branch를 제공하면 좋다. 보통 cover letter에 git URL을 적는다.

Tip maintainer에게 보내기 전에 code를 test한다. 사소한 change가 아니라면 comprehensive하고 무거운 kernel debugging option을 켜서 build, boot, test해야 한다.

Debug option은 kernel/configs/x86_debug.config에 있으며 기존 kernel config에 다음 명령으로 추가한다. 일부 option은 x86-specific이므로 다른 architecture test에서는 뺄 수 있다.

make x86_debug.config

Comment style과 kernel-doc

474-599

Comment 문장은 uppercase letter로 시작한다. Single-line comment는 /* This is a single line comment */ 형식이다. Multi-line comment는 opening과 closing delimiter를 독립 line에 두고 각 line 앞에 *를 맞춘다. 긴 comment는 paragraph로 나눈다.

/* This is a single line comment */

/*
 * This is a properly formatted
 * multi-line comment.
 *
 * Larger multi-line comments should be split into paragraphs.
 */

Tail comment는 거의 모든 context, 특히 code의 reading flow를 방해하므로 피한다.

/* This condition is not obvious without a comment */
if (somecondition_is_true) {
        /* This really needs to be documented */
        dostuff();
}

/* This magic initialization needs a comment. Maybe not? */
seed = MAGIC_CONSTANT;

Header의 struct를 compact하고 읽기 좋게 문서화할 때는 예외적으로 C++ style tail comment를 사용할 수 있다. Bitfield 옆에 의미와 reserved field를 정렬하면 각 member 위에 긴 C comment를 두는 것보다 읽기 쉽다.

// eax
u32     x2apic_shift    :  5, // Number of bits to shift APIC ID right
                                  // for the topology ID at the next level
                            : 27; // Reserved
// ebx
u32     num_processors  : 16, // Number of processors at current level
                            : 16; // Reserved

Obvious operation을 comment로 다시 설명하면 distraction이 된다. refcount_dec_and_test()가 refcount를 감소시키고 zero를 검사한다는 말 대신, zero 뒤 수행되는 비직관적 magic의 이유, ordering·locking constraint와 마지막이어야 하는 operation의 이유를 설명한다.

Function과 argument는 free-form comment가 아니라 kernel-doc format으로 문서화한다.

/**
 * magic_function - Do lots of magic stuff
 * @magic:      Pointer to the magic data to operate on
 * @offset:     Offset in the data array of @magic
 *
 * Deep explanation of mysterious things done with @magic along
 * with documentation of the return values.
 */

특히 globally visible function과 public header의 inline function에 적용한다. 짧은 설명만 필요한 모든 static function에 kernel-doc을 쓰면 과할 수 있고 descriptive function name이 tiny comment를 대신하기도 한다. 상황에 맞게 판단한다.

Locking annotation과 bracket rule

601-645

Locking requirement 문서화는 좋지만 comment가 최선은 아니다. “Caller must hold foo->lock”이라고만 쓰지 말고 function 안에 lockdep_assert_held(&foo->lock)을 둔다. PROVE_LOCKING kernel은 caller가 lock을 보유하지 않으면 warning을 내지만 comment는 그렇게 할 수 없다.

void func(struct foo *foo)
{
        lockdep_assert_held(&foo->lock);
        ...
}

if, for, while 뒤 statement가 정말 single line일 때만 bracket을 생략한다.

if (foo)
        do_something();

C grammar상 bracket이 없어도 되는 nested control flow는 single-line statement로 보지 않는다. Outer loop에 bracket을 추가하면 reading flow가 좋아진다.

for (i = 0; i < end; i++) {
        if (foo[i])
                do_something(foo[i]);
}

Variable declaration 배치

647-699

Function 시작의 variable declaration은 reverse fir tree order, 즉 긴 type·declaration에서 짧은 것으로 내려가는 순서를 선호한다. 반대 순서나 random ordering보다 빠르게 읽힌다.

struct long_struct_name *descriptive_name;
unsigned long foo, bar;
unsigned int tmp;
int ret;

같은 type의 variable은 screen space를 낭비하지 않도록 한 line에 모은다.

unsigned long a, b, c, d;

Variable declaration 자체를 여러 line으로 split하지 않는다. 긴 initialization은 declaration block 뒤 별도 statement로 옮긴다.

struct long_struct_name *descriptive_name;
struct foobar foo;

descriptive_name = container_of(bar, struct long_struct_name, member);

Hardware type과 constant

700-723

Hardware를 묘사하거나 hardware access function argument인 variable에는 올바른 u8, u16, u32, u64 type을 사용한다. Bit width가 명확해 truncation, expansion, 32/64-bit 혼동을 피한다.

unsigned long을 쓰면 32-bit kernel에서 모호한 code에도 u64를 권장한다. unsigned long long도 가능하지만 u64가 짧고 target CPU와 무관하게 64-bit width가 필요함을 명확히 보여 준다. unsigned 대신 unsigned int를 쓴다.

Code와 initializer에 literal hexadecimal 또는 decimal number를 직접 쓰지 않는다. Descriptive name의 define을 만들거나 enum을 검토한다.

Struct declaration·documentation·initializer

725-785

Struct member name은 tabular하게 정렬한다.

struct bar_order {
        unsigned int    guest_id;
        int             ordered_item;
        struct menu     *menu;
};

Declaration 안에서 member를 comment로 설명하면 format이 이상해지고 member가 가려지는 일이 많으므로 피한다. 대신 struct 앞 kernel-doc comment를 사용하면 읽기 쉽고 kernel documentation에도 포함된다.

/**
 * struct bar_order - Description of a bar order
 * @guest_id:          Unique guest id
 * @ordered_item:      The item number from the menu
 * @menu:              Pointer to the menu from which the item was ordered
 *
 * Supplementary information for using the struct.
 */
struct bar_order {
        unsigned int    guest_id;
        int             ordered_item;
        struct menu     *menu;
};

Static struct initializer는 C99 designated initializer를 쓰고 tabular하게 정렬한다.

static struct foo statfoo = {
        .a              = 0,
        .plain_integer  = CONSTANT_DEFINE_OR_ENUM,
        .bar            = &statbar,
};

C99는 마지막 comma 생략을 허용하지만 마지막 line에도 comma를 권장한다. 나중에 reorder하거나 line을 추가하기 쉽고 future patch도 조금 더 읽기 좋아진다.

Line break와 symbol namespace

786-833

Line length를 무조건 80 character로 제한하면 깊게 indent된 code가 읽기 어려워진다. Excessive line break 대신 helper function으로 code를 분리할 수 있는지 검토한다.

80-character rule은 엄격한 규칙이 아니므로 line을 나눌 때 상식을 적용한다. Format string은 절대로 split하지 않는다.

Function declaration이나 call을 나누면 둘째 line의 첫 argument를 첫 line의 첫 argument 위치에 맞춘다.

static int long_function_name(struct foobar *barfoo, unsigned int id,
                              unsigned int offset)
{
        if (!id) {
                ret = longer_function_name(barfoo, DEFAULT_BARFOO_ID,
                                           offset);

Function과 variable namespace는 readability와 grep 가능성을 높인다. Globally visible function·variable과 inline 이름에 subsystem과 component를 합친 x86_comp_, sched_, irq_, mutex_ 같은 string prefix를 붙인다.

Globally visible driver template에 즉시 들어가는 static file-scope function도 backtrace readability를 위해 좋은 prefix를 쓴다. Local static function과 variable은 생략할 수 있다. 다른 local function만 호출하는 진짜 local function은 짧고 descriptive한 이름을 쓸 수 있다.

Vendor-specific file의 static function에 xxx_vendor_나 vendor_xxx_ prefix를 붙이는 것은 도움이 되지 않는다. File 자체로 vendor-specific임이 분명하고 vendor name은 진짜 vendor-specific functionality에만 써야 한다. 일관성과 readability를 목표로 판단한다.

Commit notification bot

835-848

Bot이 tip tree의 새 commit을 감시한다. 새 commit마다 [email protected] 전용 list로 email을 보내고 commit tag에 언급된 모든 사람을 CC한다.

Tag list 끝의 Link tag에서 email Message-ID를 가져와 In-Reply-To header를 설정하므로 notification이 original patch submission thread에 올바르게 연결된다.

Tip maintainer와 submaintainer는 merge할 때 submitter에게 답하려 하지만 잊거나 당시 workflow에 맞지 않을 수 있다. Bot message는 기계적으로 생성되지만 “감사합니다. 적용했습니다”라는 의미도 담는다.