← Documents Documentation/translations/it_IT/doc-guide/kernel-doc.rst GitHub 원문 ↗

Linux 6.18.37 · Translations

kernel-doc 주석 작성과 문서 통합

kernel-doc 주석의 형식, 함수·형식·매크로 문서화, 참조 마크업, Sphinx 포함 지시문과 man 페이지 생성 절차를 설명합니다.

Source pathDocumentation/translations/it_IT/doc-guide/kernel-doc.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

kernel-doc.rst:1-607

kernel-doc은 커널 C 소스의 `/**` 주석에서 함수, 자료형, 매크로와 설계 개요를 추출해 Sphinx C domain 문서로 연결합니다. 공개 심볼과 헤더 인터페이스를 우선 문서화하고, 인자·호출 문맥·반환값·멤버 공개 범위를 정해진 문법으로 기록해야 합니다.

이 페이지는 중첩 멤버 이름, 객체형 매크로, kernel-doc 전용 참조 표식, `DOC:` 개요, `export`·`internal`·`identifiers`·`doc` 지시문까지 실제 예제로 다룹니다. 마지막에는 같은 주석으로 man 페이지를 생성하는 명령 파이프라인을 제시합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. include:: ../disclaimer-ita.rst
2
3 .. note:: Per leggere la documentazione originale in inglese:
4 :ref:`Documentation/doc-guide/index.rst <doc_guide>`
5
6 .. title:: Commenti in kernel-doc
7
8 .. _it_kernel_doc:
9
10 =================================
11 Scrivere i commenti in kernel-doc
12 =================================
13
14 Nei file sorgenti del kernel Linux potrete trovare commenti di documentazione
15 strutturanti secondo il formato kernel-doc. Essi possono descrivere funzioni,
16 tipi di dati, e l'architettura del codice.
17
18 .. note:: Il formato kernel-doc può sembrare simile a gtk-doc o Doxygen ma
19 in realtà è molto differente per ragioni storiche. I sorgenti del kernel
20 contengono decine di migliaia di commenti kernel-doc. Siete pregati
21 d'attenervi allo stile qui descritto.
22
23 La struttura kernel-doc è estratta a partire dai commenti; da questi viene
24 generato il `dominio Sphinx per il C`_ con un'adeguata descrizione per le
25 funzioni ed i tipi di dato con i loro relativi collegamenti. Le descrizioni
26 vengono filtrare per cercare i riferimenti ed i marcatori.
27
28 Vedere di seguito per maggiori dettagli.
29
30 .. _`dominio Sphinx per il C`: http://www.sphinx-doc.org/en/stable/domains.html
31
32 Tutte le funzioni esportate verso i moduli esterni utilizzando
33 ``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL`` dovrebbero avere un commento
34 kernel-doc. Quando l'intenzione è di utilizzarle nei moduli, anche le funzioni
35 e le strutture dati nei file d'intestazione dovrebbero avere dei commenti
36 kernel-doc.
37
38 È considerata una buona pratica quella di fornire una documentazione formattata
39 secondo kernel-doc per le funzioni che sono visibili da altri file del kernel
40 (ovvero, che non siano dichiarate utilizzando ``static``). Raccomandiamo,
41 inoltre, di fornire una documentazione kernel-doc anche per procedure private
42 (ovvero, dichiarate "static") al fine di fornire una struttura più coerente
43 dei sorgenti. Quest'ultima raccomandazione ha una priorità più bassa ed è a
44 discrezione dal manutentore (MAINTAINER) del file sorgente.
45
46
47
48 Sicuramente la documentazione formattata con kernel-doc è necessaria per
49 le funzioni che sono esportate verso i moduli esterni utilizzando
50 ``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL``.
51
52 Cerchiamo anche di fornire una documentazione formattata secondo kernel-doc
53 per le funzioni che sono visibili da altri file del kernel (ovvero, che non
54 siano dichiarate utilizzando "static")
55
56 Raccomandiamo, inoltre, di fornire una documentazione formattata con kernel-doc
57 anche per procedure private (ovvero, dichiarate "static") al fine di fornire
58 una struttura più coerente dei sorgenti. Questa raccomandazione ha una priorità
59 più bassa ed è a discrezione dal manutentore (MAINTAINER) del file sorgente.
60
61 Le strutture dati visibili nei file di intestazione dovrebbero essere anch'esse
62 documentate utilizzando commenti formattati con kernel-doc.
63
64 Come formattare i commenti kernel-doc
65 -------------------------------------
66
67 I commenti kernel-doc iniziano con il marcatore ``/**``. Il programma
68 ``kernel-doc`` estrarrà i commenti marchiati in questo modo. Il resto
69 del commento è formattato come un normale commento multilinea, ovvero
70 con un asterisco all'inizio d'ogni riga e che si conclude con ``*/``
71 su una riga separata.
72
73 I commenti kernel-doc di funzioni e tipi dovrebbero essere posizionati
74 appena sopra la funzione od il tipo che descrivono. Questo allo scopo di
75 aumentare la probabilità che chi cambia il codice si ricordi di aggiornare
76 anche la documentazione. I commenti kernel-doc di tipo più generale possono
77 essere posizionati ovunque nel file.
78
79 Al fine di verificare che i commenti siano formattati correttamente, potete
80 eseguire il programma ``kernel-doc`` con un livello di verbosità alto e senza
81 che questo produca alcuna documentazione. Per esempio::
82
83 scripts/kernel-doc -v -none drivers/foo/bar.c
84
85 Il formato della documentazione è verificato della procedura di generazione
86 del kernel quando viene richiesto di effettuare dei controlli extra con GCC::
87
88 make W=n
89
90 Documentare le funzioni
91 ------------------------
92
93 Generalmente il formato di un commento kernel-doc per funzioni e
94 macro simil-funzioni è il seguente::
95
96 /**
97 * function_name() - Brief description of function.
98 * @arg1: Describe the first argument.
99 * @arg2: Describe the second argument.
100 * One can provide multiple line descriptions
101 * for arguments.
102 *
103 * A longer description, with more discussion of the function function_name()
104 * that might be useful to those using or modifying it. Begins with an
105 * empty comment line, and may include additional embedded empty
106 * comment lines.
107 *
108 * The longer description may have multiple paragraphs.
109 *
110 * Context: Describes whether the function can sleep, what locks it takes,
111 * releases, or expects to be held. It can extend over multiple
112 * lines.
113 * Return: Describe the return value of function_name.
114 *
115 * The return value description can also have multiple paragraphs, and should
116 * be placed at the end of the comment block.
117 */
118
119 La descrizione introduttiva (*brief description*) che segue il nome della
120 funzione può continuare su righe successive e termina con la descrizione di
121 un argomento, una linea di commento vuota, oppure la fine del commento.
122
123 Parametri delle funzioni
124 ~~~~~~~~~~~~~~~~~~~~~~~~
125
126 Ogni argomento di una funzione dovrebbe essere descritto in ordine, subito
127 dopo la descrizione introduttiva. Non lasciare righe vuote né fra la
128 descrizione introduttiva e quella degli argomenti, né fra gli argomenti.
129
130 Ogni ``@argument:`` può estendersi su più righe.
131
132 .. note::
133
134 Se la descrizione di ``@argument:`` si estende su più righe,
135 la continuazione dovrebbe iniziare alla stessa colonna della riga
136 precedente::
137
138 * @argument: some long description
139 * that continues on next lines
140
141 or::
142
143 * @argument:
144 * some long description
145 * that continues on next lines
146
147 Se una funzione ha un numero variabile di argomento, la sua descrizione
148 dovrebbe essere scritta con la notazione kernel-doc::
149
150 * @...: description
151
152 Contesto delle funzioni
153 ~~~~~~~~~~~~~~~~~~~~~~~
154
155 Il contesto in cui le funzioni vengono chiamate viene descritto in una
156 sezione chiamata ``Context``. Questo dovrebbe informare sulla possibilità
157 che una funzione dorma (*sleep*) o che possa essere chiamata in un contesto
158 d'interruzione, così come i *lock* che prende, rilascia e che si aspetta che
159 vengano presi dal chiamante.
160
161 Esempi::
162
163 * Context: Any context.
164 * Context: Any context. Takes and releases the RCU lock.
165 * Context: Any context. Expects <lock> to be held by caller.
166 * Context: Process context. May sleep if @gfp flags permit.
167 * Context: Process context. Takes and releases <mutex>.
168 * Context: Softirq or process context. Takes and releases <lock>, BH-safe.
169 * Context: Interrupt context.
170
171 Valore di ritorno
172 ~~~~~~~~~~~~~~~~~
173
174 Il valore di ritorno, se c'è, viene descritto in una sezione dedicata di nome
175 ``Return``.
176
177 .. note::
178
179 #) La descrizione multiriga non riconosce il termine d'una riga, per cui
180 se provate a formattare bene il vostro testo come nel seguente esempio::
181
182 * Return:
183 * %0 - OK
184 * %-EINVAL - invalid argument
185 * %-ENOMEM - out of memory
186
187 le righe verranno unite e il risultato sarà::
188
189 Return: 0 - OK -EINVAL - invalid argument -ENOMEM - out of memory
190
191 Quindi, se volete che le righe vengano effettivamente generate, dovete
192 utilizzare una lista ReST, ad esempio::
193
194 * Return:
195 * * %0 - OK to runtime suspend the device
196 * * %-EBUSY - Device should not be runtime suspended
197
198 #) Se il vostro testo ha delle righe che iniziano con una frase seguita dai
199 due punti, allora ognuna di queste frasi verrà considerata come il nome
200 di una nuova sezione, e probabilmente non produrrà gli effetti desiderati.
201
202 Documentare strutture, unioni ed enumerazioni
203 ---------------------------------------------
204
205 Generalmente il formato di un commento kernel-doc per struct, union ed enum è::
206
207 /**
208 * struct struct_name - Brief description.
209 * @member1: Description of member1.
210 * @member2: Description of member2.
211 * One can provide multiple line descriptions
212 * for members.
213 *
214 * Description of the structure.
215 */
216
217 Nell'esempio qui sopra, potete sostituire ``struct`` con ``union`` o ``enum``
218 per descrivere unioni ed enumerati. ``member`` viene usato per indicare i
219 membri di strutture ed unioni, ma anche i valori di un tipo enumerato.
220
221 La descrizione introduttiva (*brief description*) che segue il nome della
222 funzione può continuare su righe successive e termina con la descrizione di
223 un argomento, una linea di commento vuota, oppure la fine del commento.
224
225 Membri
226 ~~~~~~
227
228 I membri di strutture, unioni ed enumerati devo essere documentati come i
229 parametri delle funzioni; seguono la descrizione introduttiva e possono
230 estendersi su più righe.
231
232 All'interno d'una struttura o d'un unione, potete utilizzare le etichette
233 ``private:`` e ``public:``. I campi che sono nell'area ``private:`` non
234 verranno inclusi nella documentazione finale.
235
236 Le etichette ``private:`` e ``public:`` devono essere messe subito dopo
237 il marcatore di un commento ``/*``. Opzionalmente, possono includere commenti
238 fra ``:`` e il marcatore di fine commento ``*/``.
239
240 Esempio::
241
242 /**
243 * struct my_struct - short description
244 * @a: first member
245 * @b: second member
246 * @d: fourth member
247 *
248 * Longer description
249 */
250 struct my_struct {
251 int a;
252 int b;
253 /* private: internal use only */
254 int c;
255 /* public: the next one is public */
256 int d;
257 };
258
259 Strutture ed unioni annidate
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261
262 È possibile documentare strutture ed unioni annidate, ad esempio::
263
264 /**
265 * struct nested_foobar - a struct with nested unions and structs
266 * @memb1: first member of anonymous union/anonymous struct
267 * @memb2: second member of anonymous union/anonymous struct
268 * @memb3: third member of anonymous union/anonymous struct
269 * @memb4: fourth member of anonymous union/anonymous struct
270 * @bar: non-anonymous union
271 * @bar.st1: struct st1 inside @bar
272 * @bar.st2: struct st2 inside @bar
273 * @bar.st1.memb1: first member of struct st1 on union bar
274 * @bar.st1.memb2: second member of struct st1 on union bar
275 * @bar.st2.memb1: first member of struct st2 on union bar
276 * @bar.st2.memb2: second member of struct st2 on union bar
277 */
278 struct nested_foobar {
279 /* Anonymous union/struct*/
280 union {
281 struct {
282 int memb1;
283 int memb2;
284 }
285 struct {
286 void *memb3;
287 int memb4;
288 }
289 }
290 union {
291 struct {
292 int memb1;
293 int memb2;
294 } st1;
295 struct {
296 void *memb1;
297 int memb2;
298 } st2;
299 } bar;
300 };
301
302 .. note::
303
304 #) Quando documentate una struttura od unione annidata, ad esempio
305 di nome ``foo``, il suo campo ``bar`` dev'essere documentato
306 usando ``@foo.bar:``
307 #) Quando la struttura od unione annidata è anonima, il suo campo
308 ``bar`` dev'essere documentato usando ``@bar:``
309
310 Commenti in linea per la documentazione dei membri
311 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
312
313 I membri d'una struttura possono essere documentati in linea all'interno
314 della definizione stessa. Ci sono due stili: una singola riga di commento
315 che inizia con ``/**`` e finisce con ``*/``; commenti multi riga come
316 qualsiasi altro commento kernel-doc::
317
318 /**
319 * struct foo - Brief description.
320 * @foo: The Foo member.
321 */
322 struct foo {
323 int foo;
324 /**
325 * @bar: The Bar member.
326 */
327 int bar;
328 /**
329 * @baz: The Baz member.
330 *
331 * Here, the member description may contain several paragraphs.
332 */
333 int baz;
334 union {
335 /** @foobar: Single line description. */
336 int foobar;
337 };
338 /** @bar2: Description for struct @bar2 inside @foo */
339 struct {
340 /**
341 * @bar2.barbar: Description for @barbar inside @foo.bar2
342 */
343 int barbar;
344 } bar2;
345 };
346
347
348 Documentazione dei tipi di dato
349 -------------------------------
350 Generalmente il formato di un commento kernel-doc per typedef è
351 il seguente::
352
353 /**
354 * typedef type_name - Brief description.
355 *
356 * Description of the type.
357 */
358
359 Anche i tipi di dato per prototipi di funzione possono essere documentati::
360
361 /**
362 * typedef type_name - Brief description.
363 * @arg1: description of arg1
364 * @arg2: description of arg2
365 *
366 * Description of the type.
367 *
368 * Context: Locking context.
369 * Return: Meaning of the return value.
370 */
371 typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);
372
373 Documentazione di macro simili a oggetti
374 ----------------------------------------
375
376 Le macro simili a oggetti si distinguono dalle macro simili a funzione. Esse si
377 distinguono in base al fatto che il nome della macro simile a funzione sia
378 immediatamente seguito da una parentesi sinistra ('(') mentre in quelle simili a
379 oggetti no.
380
381 Le macro simili a funzioni sono gestite come funzioni da ``scripts/kernel-doc``.
382 Possono avere un elenco di parametri. Le macro simili a oggetti non hanno un
383 elenco di parametri.
384
385 Il formato generale di un commento kernel-doc per una macro simile a oggetti è::
386
387 /**
388 * define object_name - Brief description.
389 *
390 * Description of the object.
391 */
392
393 Esempio::
394
395 /**
396 * define MAX_ERRNO - maximum errno value that is supported
397 *
398 * Kernel pointers have redundant information, so we can use a
399 * scheme where we can return either an error code or a normal
400 * pointer with the same return value.
401 */
402 #define MAX_ERRNO 4095
403
404 Esempio::
405
406 /**
407 * define DRM_GEM_VRAM_PLANE_HELPER_FUNCS - \
408 * Initializes struct drm_plane_helper_funcs for VRAM handling
409 *
410 * This macro initializes struct drm_plane_helper_funcs to use the
411 * respective helper functions.
412 */
413 #define DRM_GEM_VRAM_PLANE_HELPER_FUNCS \
414 .prepare_fb = drm_gem_vram_plane_helper_prepare_fb, \
415 .cleanup_fb = drm_gem_vram_plane_helper_cleanup_fb
416
417 Marcatori e riferimenti
418 -----------------------
419
420 All'interno dei commenti di tipo kernel-doc vengono riconosciuti i seguenti
421 *pattern* che vengono convertiti in marcatori reStructuredText ed in riferimenti
422 del `dominio Sphinx per il C`_.
423
424 .. attention:: Questi sono riconosciuti **solo** all'interno di commenti
425 kernel-doc, e **non** all'interno di documenti reStructuredText.
426
427 ``funcname()``
428 Riferimento ad una funzione.
429
430 ``@parameter``
431 Nome di un parametro di una funzione (nessun riferimento, solo formattazione).
432
433 ``%CONST``
434 Il nome di una costante (nessun riferimento, solo formattazione)
435
436 ````literal````
437 Un blocco di testo che deve essere riportato così com'è. La rappresentazione
438 finale utilizzerà caratteri a ``spaziatura fissa``.
439
440 Questo è utile se dovete utilizzare caratteri speciali che altrimenti
441 potrebbero assumere un significato diverso in kernel-doc o in reStructuredText
442
443 Questo è particolarmente utile se dovete scrivere qualcosa come ``%ph``
444 all'interno della descrizione di una funzione.
445
446 ``$ENVVAR``
447 Il nome di una variabile d'ambiente (nessun riferimento, solo formattazione).
448
449 ``&struct name``
450 Riferimento ad una struttura.
451
452 ``&enum name``
453 Riferimento ad un'enumerazione.
454
455 ``&typedef name``
456 Riferimento ad un tipo di dato.
457
458 ``&struct_name->member`` or ``&struct_name.member``
459 Riferimento ad un membro di una struttura o di un'unione. Il riferimento sarà
460 la struttura o l'unione, non il memembro.
461
462 ``&name``
463 Un generico riferimento ad un tipo. Usate, preferibilmente, il riferimento
464 completo come descritto sopra. Questo è dedicato ai commenti obsoleti.
465
466 Riferimenti usando reStructuredText
467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
468
469 Nei documenti reStructuredText non serve alcuna sintassi speciale per
470 fare riferimento a funzioni e tipi definiti nei commenti
471 kernel-doc. Sarà sufficiente terminare i nomi di funzione con ``()``,
472 e scrivere ``struct``, ``union``, ``enum``, o ``typedef`` prima di un
473 tipo. Per esempio::
474
475 See foo()
476 See struct foo.
477 See union bar.
478 See enum baz.
479 See typedef meh.
480
481 Tuttavia, la personalizzazione dei collegamenti è possibile solo con
482 la seguente sintassi::
483
484 See :c:func:`my custom link text for function foo <foo>`.
485 See :c:type:`my custom link text for struct bar <bar>`.
486
487
488 Commenti per una documentazione generale
489 ----------------------------------------
490
491 Al fine d'avere il codice ed i commenti nello stesso file, potete includere
492 dei blocchi di documentazione kernel-doc con un formato libero invece
493 che nel formato specifico per funzioni, strutture, unioni, enumerati o tipi
494 di dato. Per esempio, questo tipo di commento potrebbe essere usato per la
495 spiegazione delle operazioni di un driver o di una libreria
496
497 Questo s'ottiene utilizzando la parola chiave ``DOC:`` a cui viene associato
498 un titolo.
499
500 Generalmente il formato di un commento generico o di visione d'insieme è
501 il seguente::
502
503 /**
504 * DOC: Theory of Operation
505 *
506 * The whizbang foobar is a dilly of a gizmo. It can do whatever you
507 * want it to do, at any time. It reads your mind. Here's how it works.
508 *
509 * foo bar splat
510 *
511 * The only drawback to this gizmo is that is can sometimes damage
512 * hardware, software, or its subject(s).
513 */
514
515 Il titolo che segue ``DOC:`` funziona da intestazione all'interno del file
516 sorgente, ma anche come identificatore per l'estrazione di questi commenti di
517 documentazione. Quindi, il titolo dev'essere unico all'interno del file.
518
519 =======================================
520 Includere i commenti di tipo kernel-doc
521 =======================================
522
523 I commenti di documentazione possono essere inclusi in un qualsiasi documento
524 di tipo reStructuredText mediante l'apposita direttiva nell'estensione
525 kernel-doc per Sphinx.
526
527 Le direttive kernel-doc sono nel formato::
528
529 .. kernel-doc:: source
530 :option:
531
532 Il campo *source* è il percorso ad un file sorgente, relativo alla cartella
533 principale dei sorgenti del kernel. La direttiva supporta le seguenti opzioni:
534
535 export: *[source-pattern ...]*
536 Include la documentazione per tutte le funzioni presenti nel file sorgente
537 (*source*) che sono state esportate utilizzando ``EXPORT_SYMBOL`` o
538 ``EXPORT_SYMBOL_GPL`` in *source* o in qualsiasi altro *source-pattern*
539 specificato.
540
541 Il campo *source-patter* è utile quando i commenti kernel-doc sono stati
542 scritti nei file d'intestazione, mentre ``EXPORT_SYMBOL`` e
543 ``EXPORT_SYMBOL_GPL`` si trovano vicino alla definizione delle funzioni.
544
545 Esempi::
546
547 .. kernel-doc:: lib/bitmap.c
548 :export:
549
550 .. kernel-doc:: include/net/mac80211.h
551 :export: net/mac80211/*.c
552
553 internal: *[source-pattern ...]*
554 Include la documentazione per tutte le funzioni ed i tipi presenti nel file
555 sorgente (*source*) che **non** sono stati esportati utilizzando
556 ``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL`` né in *source* né in qualsiasi
557 altro *source-pattern* specificato.
558
559 Esempio::
560
561 .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
562 :internal:
563
564 identifiers: *[ function/type ...]*
565 Include la documentazione per ogni *function* e *type* in *source*.
566 Se non vengono esplicitamente specificate le funzioni da includere, allora
567 verranno incluse tutte quelle disponibili in *source*.
568
569 Esempi::
570
571 .. kernel-doc:: lib/bitmap.c
572 :identifiers: bitmap_parselist bitmap_parselist_user
573
574 .. kernel-doc:: lib/idr.c
575 :identifiers:
576
577 functions: *[ function ...]*
578 Questo è uno pseudonimo, deprecato, per la direttiva 'identifiers'.
579
580 doc: *title*
581 Include la documentazione del paragrafo ``DOC:`` identificato dal titolo
582 (*title*) all'interno del file sorgente (*source*). Gli spazi in *title* sono
583 permessi; non virgolettate *title*. Il campo *title* è utilizzato per
584 identificare un paragrafo e per questo non viene incluso nella documentazione
585 finale. Verificate d'avere l'intestazione appropriata nei documenti
586 reStructuredText.
587
588 Esempio::
589
590 .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
591 :doc: High Definition Audio over HDMI and Display Port
592
593 Senza alcuna opzione, la direttiva kernel-doc include tutti i commenti di
594 documentazione presenti nel file sorgente (*source*).
595
596 L'estensione kernel-doc fa parte dei sorgenti del kernel, la si può trovare
597 in ``Documentation/sphinx/kerneldoc.py``. Internamente, viene utilizzato
598 lo script ``scripts/kernel-doc`` per estrarre i commenti di documentazione
599 dai file sorgenti.
600
601 Come utilizzare kernel-doc per generare pagine man
602 --------------------------------------------------
603
604 Se volete utilizzare kernel-doc solo per generare delle pagine man, potete
605 farlo direttamente dai sorgenti del kernel::
606
607 $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man
608

3. 한국어 전문 번역

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

kernel-doc의 역할과 문서화 대상

1-63

이 문서는 이탈리아어 번역 공통 고지인 `../disclaimer-ita.rst`를 포함하며, 원래 영어 문서를 확인할 때는 `Documentation/doc-guide/index.rst <doc_guide>`를 기준으로 삼으라고 안내합니다. 페이지 내부 식별자는 `it_kernel_doc`이고 제목은 kernel-doc 주석 작성법입니다.

리눅스 커널 소스 파일에는 kernel-doc 형식의 구조화된 문서 주석이 있습니다. 이 주석은 함수와 데이터 형식을 설명할 뿐 아니라, 코드 전체의 설계와 구성 원리도 기록할 수 있습니다.

겉모양이 `gtk-doc`이나 `Doxygen`과 비슷해 보여도 kernel-doc은 역사적 이유로 동작과 문법이 크게 다릅니다. 커널 소스에 이미 수만 개의 kernel-doc 주석이 있으므로, 새 문서도 이 페이지에서 정의한 기존 스타일을 따라야 합니다.

도구는 주석에서 kernel-doc 구조를 추출하고 이를 `Sphinx C domain` 객체로 바꿉니다. 함수와 데이터 형식 설명에는 서로 연결되는 참조가 생성되며, 본문은 참조 표현과 마크업을 찾도록 필터링됩니다.

외부 모듈에 `EXPORT_SYMBOL` 또는 `EXPORT_SYMBOL_GPL`로 공개하는 함수는 kernel-doc 주석을 갖추어야 합니다. 모듈에서 사용할 의도로 헤더에 노출한 함수와 자료구조도 같은 기준으로 문서화하는 것이 원칙입니다.

다른 커널 소스 파일에서 볼 수 있는 비정적 함수, 즉 `static`으로 선언하지 않은 함수도 kernel-doc 문서를 제공하는 것이 좋은 관행입니다. 소스 파일 내부에서만 쓰는 정적 함수도 코드 구조를 일관되게 이해할 수 있도록 문서화하는 편이 권장됩니다.

다만 정적·비공개 절차의 문서화는 공개 API보다 우선순위가 낮고 해당 파일의 `MAINTAINER` 판단에 맡깁니다. 이 기준은 공개 계약을 먼저 완성하고 내부 구현 설명은 유지보수 비용과 효용을 따져 추가하라는 뜻입니다.

원문 후반은 이 정책을 다시 강조합니다. 내보낸 함수는 필수, 다른 파일에서 보이는 함수와 헤더에 공개된 자료구조는 강한 권장, 정적 함수는 유지관리자 재량이라는 세 단계로 읽으면 됩니다.

kernel-doc 문서화 우선순위
대상판정이유
EXPORT_SYMBOL / EXPORT_SYMBOL_GPL 함수필수외부 모듈이 사용하는 공개 계약
헤더의 함수와 자료구조권장여러 소스와 모듈에서 보이는 인터페이스
비-static 함수좋은 관행다른 커널 파일에서 호출 가능
static 함수낮은 우선순위내부 구조 설명, MAINTAINER 재량

심볼의 노출 범위에 따라 문서화 요구 수준을 구분합니다.

kernel-doc 처리 흐름
소스의 /** 주석kernel-doc 구조 추출
함수·형식 설명참조와 마크업 필터링
Sphinx C domain상호 연결된 문서 출력

소스 주석이 Sphinx의 탐색 가능한 C API 문서가 되는 과정입니다.

.. include:: ../disclaimer-ita.rst

.. note:: Per leggere la documentazione originale in inglese:
	  :ref:`Documentation/doc-guide/index.rst <doc_guide>`

.. title:: Commenti in kernel-doc

.. _it_kernel_doc:

=================================
Scrivere i commenti in kernel-doc
=================================

Nei file sorgenti del kernel Linux potrete trovare commenti di documentazione
strutturanti secondo il formato kernel-doc. Essi possono descrivere funzioni,
tipi di dati, e l'architettura del codice.

.. note:: Il formato kernel-doc può sembrare simile a gtk-doc o Doxygen ma
   in realtà è molto differente per ragioni storiche. I sorgenti del kernel
   contengono decine di migliaia di commenti kernel-doc. Siete pregati
   d'attenervi allo stile qui descritto.

La struttura kernel-doc è estratta a partire dai commenti; da questi viene
generato il `dominio Sphinx per il C`_ con un'adeguata descrizione per le
funzioni ed i tipi di dato con i loro relativi collegamenti. Le descrizioni
vengono filtrare per cercare i riferimenti ed i marcatori.

Vedere di seguito per maggiori dettagli.

.. _`dominio Sphinx per il C`: http://www.sphinx-doc.org/en/stable/domains.html

Tutte le funzioni esportate verso i moduli esterni utilizzando
``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL`` dovrebbero avere un commento
kernel-doc. Quando l'intenzione è di utilizzarle nei moduli, anche le funzioni
e le strutture dati nei file d'intestazione dovrebbero avere dei commenti
kernel-doc.

È considerata una buona pratica quella di fornire una documentazione formattata
secondo kernel-doc per le funzioni che sono visibili da altri file del kernel
(ovvero, che non siano dichiarate utilizzando ``static``). Raccomandiamo,
inoltre, di fornire una documentazione kernel-doc anche per procedure private
(ovvero, dichiarate "static") al fine di fornire una struttura più coerente
dei sorgenti. Quest'ultima raccomandazione ha una priorità più bassa ed è a
discrezione dal manutentore (MAINTAINER) del file sorgente.



Sicuramente la documentazione formattata con kernel-doc è necessaria per
le funzioni che sono esportate verso i moduli esterni utilizzando
``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL``.

Cerchiamo anche di fornire una documentazione formattata secondo kernel-doc
per le funzioni che sono visibili da altri file del kernel (ovvero, che non
siano dichiarate utilizzando "static")

Raccomandiamo, inoltre, di fornire una documentazione formattata con kernel-doc
anche per procedure private (ovvero, dichiarate "static") al fine di fornire
una struttura più coerente dei sorgenti. Questa raccomandazione ha una priorità
più bassa ed è a discrezione dal manutentore (MAINTAINER) del file sorgente.

Le strutture dati visibili nei file di intestazione dovrebbero essere anch'esse
documentate utilizzando commenti formattati con kernel-doc.

기본 주석 형식과 사전 검사

64-89

kernel-doc 주석은 정확히 `/**`로 시작합니다. `kernel-doc` 프로그램은 이 표식을 가진 주석만 문서 후보로 추출합니다.

나머지는 일반적인 여러 줄 C 주석처럼 각 줄 앞에 별표를 두고, 별도 줄의 `*/`로 닫습니다. 시작 표식의 별표 수와 종료 표식의 위치가 추출 여부를 좌우하므로 임의로 바꾸면 안 됩니다.

함수와 형식을 설명하는 주석은 해당 선언이나 정의 바로 위에 배치합니다. 코드를 고칠 때 바로 붙어 있는 설명도 함께 갱신하도록 유도하기 위한 위치 규칙입니다.

파일이나 하위 시스템의 개요처럼 특정 선언에 속하지 않는 일반 문서는 파일 안의 다른 위치에 둘 수 있습니다. 이런 자유 형식 문서는 뒤에서 설명하는 `DOC:` 표식을 사용합니다.

형식을 빠르게 검사하려면 `scripts/kernel-doc`를 높은 상세도로 실행하되 문서는 생성하지 않게 합니다. 예시의 `-v -none` 조합은 진단만 확인할 때 유용합니다.

커널 빌드의 추가 GCC 검사도 문서 형식을 점검합니다. `make W=n`에서 `n`은 원하는 경고 수준이며, 변경을 제출하기 전에 적절한 수준으로 실행해 경고를 확인해야 합니다.

	scripts/kernel-doc -v -none drivers/foo/bar.c

Il formato della documentazione è verificato della procedura di generazione
del kernel quando viene richiesto di effettuare dei controlli extra con GCC::

	make W=n
배치와 검사 규칙
항목규칙
시작과 종료`/**`로 시작하고 별도 줄의 `*/`로 종료
함수·형식 주석대상 선언 또는 정의 바로 위
일반 설명파일 안의 적절한 위치
단일 파일 검사scripts/kernel-doc -v -none
빌드 검사make W=n

주석을 어디에 두고 어떤 검사로 확인하는지 정리합니다.

작성 직후 검증
kernel-doc 주석 작성대상 바로 위에 배치
scripts/kernel-doc -v -none구문 진단
make W=n통합 빌드 경고 확인

짧은 진단과 빌드 검사를 차례로 적용합니다.

Come formattare i commenti kernel-doc
-------------------------------------

I commenti kernel-doc iniziano con il marcatore ``/**``. Il programma
``kernel-doc`` estrarrà i commenti marchiati in questo modo. Il resto
del commento è formattato come un normale commento multilinea, ovvero
con un asterisco all'inizio d'ogni riga e che si conclude con ``*/``
su una riga separata.

I commenti kernel-doc di funzioni e tipi dovrebbero essere posizionati
appena sopra la funzione od il tipo che descrivono. Questo allo scopo di
aumentare la probabilità che chi cambia il codice si ricordi di aggiornare
anche la documentazione. I commenti kernel-doc di tipo più generale possono
essere posizionati ovunque nel file.

Al fine di verificare che i commenti siano formattati correttamente, potete
eseguire il programma ``kernel-doc`` con un livello di verbosità alto e senza
che questo produca alcuna documentazione. Per esempio::

	scripts/kernel-doc -v -none drivers/foo/bar.c

Il formato della documentazione è verificato della procedura di generazione
del kernel quando viene richiesto di effettuare dei controlli extra con GCC::

	make W=n

함수 주석과 매개변수

90-151

함수와 함수처럼 호출되는 매크로의 주석은 함수 이름, 짧은 설명, 매개변수, 긴 설명, 호출 문맥, 반환값 순서로 구성합니다. 각 요소의 순서는 파서가 의미를 정확히 분리하는 데 중요합니다.

첫 줄은 `function_name() - Brief description` 형식입니다. 함수 이름에는 괄호를 붙이고 하이픈 뒤에 짧은 설명을 적습니다.

짧은 설명은 다음 줄로 이어질 수 있습니다. 그러나 첫 매개변수 설명, 빈 주석 줄, 또는 주석 끝을 만나면 짧은 설명이 종료됩니다.

각 매개변수는 실제 함수 서명과 같은 순서로 `@arg: 설명` 형식으로 기록합니다. 짧은 설명과 첫 매개변수 사이, 그리고 매개변수 설명들 사이에는 빈 줄을 넣지 않습니다.

매개변수 설명은 여러 줄이 될 수 있습니다. 이어지는 줄은 앞 줄 설명의 시작 열에 맞춰 정렬하거나, `@argument:` 다음 줄에서 탭으로 들여써 의미 범위를 분명히 합니다.

가변 인수를 받는 함수는 생략 부호 자체를 매개변수 이름처럼 다뤄 `@...: description`으로 설명합니다. 가변 인수가 있다는 사실만 적지 말고 그 인수들이 어떤 규약과 형식을 따르는지도 설명해야 합니다.

모든 매개변수 뒤의 빈 주석 줄부터 긴 설명이 시작됩니다. 긴 설명은 여러 문단을 포함할 수 있으며, API 사용자와 구현 변경자 모두에게 필요한 동작·제약·부작용을 기록합니다.

  /**
   * function_name() - Brief description of function.
   * @arg1: Describe the first argument.
   * @arg2: Describe the second argument.
   *        One can provide multiple line descriptions
   *        for arguments.
   *
   * A longer description, with more discussion of the function function_name()
   * that might be useful to those using or modifying it. Begins with an
   * empty comment line, and may include additional embedded empty
   * comment lines.
   *
   * The longer description may have multiple paragraphs.
   *
   * Context: Describes whether the function can sleep, what locks it takes,
   *          releases, or expects to be held. It can extend over multiple
   *          lines.
   * Return: Describe the return value of function_name.
   *
   * The return value description can also have multiple paragraphs, and should
   * be placed at the end of the comment block.
   */
      * @argument: some long description
      *            that continues on next lines

   or::

      * @argument:
      *		some long description
      *		that continues on next lines

Se una funzione ha un numero variabile di argomento, la sua descrizione
dovrebbe essere scritta con la notazione kernel-doc::

      * @...: description
함수 주석 해부
부분형식핵심 규칙
이름과 요약name() - brief매개변수·빈 줄·끝에서 종료
매개변수@arg: description서명 순서, 빈 줄 금지
긴 설명빈 주석 줄 뒤여러 문단 허용
호출 문맥Context:잠들기·락·인터럽트 조건
반환값Return:블록 끝에 배치

한 함수 주석의 구성 요소와 종료 조건입니다.

여러 줄 매개변수 설명
상황표기
같은 줄에서 시작다음 줄을 설명 시작 열에 정렬
다음 줄에서 시작@argument: 뒤 줄을 들여쓰기
가변 인수@...: description

지원되는 정렬 방식과 가변 인수 표기입니다.

Documentare le funzioni
------------------------

Generalmente il formato di un commento kernel-doc per funzioni e
macro simil-funzioni è il seguente::

  /**
   * function_name() - Brief description of function.
   * @arg1: Describe the first argument.
   * @arg2: Describe the second argument.
   *        One can provide multiple line descriptions
   *        for arguments.
   *
   * A longer description, with more discussion of the function function_name()
   * that might be useful to those using or modifying it. Begins with an
   * empty comment line, and may include additional embedded empty
   * comment lines.
   *
   * The longer description may have multiple paragraphs.
   *
   * Context: Describes whether the function can sleep, what locks it takes,
   *          releases, or expects to be held. It can extend over multiple
   *          lines.
   * Return: Describe the return value of function_name.
   *
   * The return value description can also have multiple paragraphs, and should
   * be placed at the end of the comment block.
   */

La descrizione introduttiva (*brief description*) che segue il nome della
funzione può continuare su righe successive e termina con la descrizione di
un argomento, una linea di commento vuota, oppure la fine del commento.

Parametri delle funzioni
~~~~~~~~~~~~~~~~~~~~~~~~

Ogni argomento di una funzione dovrebbe essere descritto in ordine, subito
dopo la descrizione introduttiva.  Non lasciare righe vuote né fra la
descrizione introduttiva e quella degli argomenti, né fra gli argomenti.

Ogni ``@argument:`` può estendersi su più righe.

.. note::

   Se la descrizione di ``@argument:`` si estende su più righe,
   la continuazione dovrebbe iniziare alla stessa colonna della riga
   precedente::

      * @argument: some long description
      *            that continues on next lines

   or::

      * @argument:
      *		some long description
      *		that continues on next lines

Se una funzione ha un numero variabile di argomento, la sua descrizione
dovrebbe essere scritta con la notazione kernel-doc::

      * @...: description

호출 문맥과 반환값

152-201

함수가 호출될 수 있는 실행 환경은 `Context` 절에서 설명합니다. 함수가 잠들 수 있는지, 인터럽트 문맥에서 호출 가능한지, 어떤 락을 획득하거나 해제하는지, 호출자가 어떤 락을 미리 잡아야 하는지를 빠짐없이 적습니다.

`Any context`는 실행 문맥의 제한이 없다는 뜻이지만 락 조건이 없다는 뜻은 아닙니다. RCU 락을 함수가 직접 잡고 놓는지, 특정 락을 호출자가 보유해야 하는지 같은 조건을 같은 문장에 덧붙일 수 있습니다.

`Process context`는 프로세스 문맥을 요구합니다. `@gfp` 플래그가 허용할 때 잠들 수 있다는 조건이나, 뮤텍스를 획득·해제한다는 사실도 문서 계약에 포함됩니다.

softirq와 프로세스 문맥을 모두 허용하는 함수는 BH 안전성까지 명시할 수 있습니다. 인터럽트 문맥 전용 또는 허용 함수도 단순히 빠르다고 표현하지 말고 `Interrupt context`라고 정확히 기록합니다.

반환값이 있는 함수는 `Return` 절에서 그 의미를 설명합니다. 반환 설명은 여러 문단일 수 있으며 함수 주석 블록의 마지막에 두는 것이 원칙입니다.

일반 여러 줄 텍스트는 줄바꿈을 보존하지 않습니다. 따라서 `%0 - OK`, `%-EINVAL - invalid argument`, `%-ENOMEM - out of memory`를 각각 새 줄에 놓기만 하면 출력에서는 한 줄로 합쳐집니다.

반환값별 줄 구분이 필요하면 reStructuredText 목록을 사용합니다. 각 항목 앞에 목록 별표를 하나 더 두면 `%0`과 `%-EBUSY` 설명이 독립된 항목으로 출력됩니다.

본문 줄이 `이름:` 같은 구문으로 시작하면 kernel-doc이 새 절의 이름으로 해석할 수 있습니다. 의도하지 않은 절 분리를 피하려면 문장 구조를 바꾸거나 적절한 목록·리터럴 마크업을 사용합니다.

  * Context: Any context.
  * Context: Any context. Takes and releases the RCU lock.
  * Context: Any context. Expects <lock> to be held by caller.
  * Context: Process context. May sleep if @gfp flags permit.
  * Context: Process context. Takes and releases <mutex>.
  * Context: Softirq or process context. Takes and releases <lock>, BH-safe.
  * Context: Interrupt context.
	* Return:
	* %0 - OK
	* %-EINVAL - invalid argument
	* %-ENOMEM - out of memory

     le righe verranno unite e il risultato sarà::

	Return: 0 - OK -EINVAL - invalid argument -ENOMEM - out of memory

     Quindi, se volete che le righe vengano effettivamente generate, dovete
     utilizzare una lista ReST, ad esempio::

      * Return:
      * * %0		- OK to runtime suspend the device
      * * %-EBUSY	- Device should not be runtime suspended
Context에 기록할 조건
범주예시
실행 문맥Any, Process, Softirq, Interrupt
수면 가능성May sleep if @gfp flags permit
함수가 다루는 락takes and releases RCU lock / mutex
호출자 전제expects lock to be held
하단부 안전성BH-safe

호출 가능성뿐 아니라 동기화 계약까지 함께 기록합니다.

Return 줄바꿈 보존
일반 여러 줄 반환 설명한 문단으로 병합
ReST 목록 표식 추가반환값별 항목 유지

단순 줄바꿈은 합쳐지므로 목록 구조를 명시해야 합니다.

Contesto delle funzioni
~~~~~~~~~~~~~~~~~~~~~~~

Il contesto in cui le funzioni vengono chiamate viene descritto in una
sezione chiamata ``Context``. Questo dovrebbe informare sulla possibilità
che una funzione dorma (*sleep*) o che possa essere chiamata in un contesto
d'interruzione, così come i *lock* che prende, rilascia e che si aspetta che
vengano presi dal chiamante.

Esempi::

  * Context: Any context.
  * Context: Any context. Takes and releases the RCU lock.
  * Context: Any context. Expects <lock> to be held by caller.
  * Context: Process context. May sleep if @gfp flags permit.
  * Context: Process context. Takes and releases <mutex>.
  * Context: Softirq or process context. Takes and releases <lock>, BH-safe.
  * Context: Interrupt context.

Valore di ritorno
~~~~~~~~~~~~~~~~~

Il valore di ritorno, se c'è, viene descritto in una sezione dedicata di nome
``Return``.

.. note::

  #) La descrizione multiriga non riconosce il termine d'una riga, per cui
     se provate a formattare bene il vostro testo come nel seguente esempio::

	* Return:
	* %0 - OK
	* %-EINVAL - invalid argument
	* %-ENOMEM - out of memory

     le righe verranno unite e il risultato sarà::

	Return: 0 - OK -EINVAL - invalid argument -ENOMEM - out of memory

     Quindi, se volete che le righe vengano effettivamente generate, dovete
     utilizzare una lista ReST, ad esempio::

      * Return:
      * * %0		- OK to runtime suspend the device
      * * %-EBUSY	- Device should not be runtime suspended

  #) Se il vostro testo ha delle righe che iniziano con una frase seguita dai
     due punti, allora ognuna di queste frasi verrà considerata come il nome
     di una nuova sezione, e probabilmente non produrrà gli effetti desiderati.

구조체·공용체·열거형과 공개 범위

202-258

구조체, 공용체, 열거형 주석은 함수 주석과 비슷하지만 첫 줄이 `struct struct_name - Brief description.` 형식입니다. 대상에 따라 `struct`를 `union` 또는 `enum`으로 바꿉니다.

`@member` 표기는 구조체와 공용체의 필드뿐 아니라 열거형의 값도 가리킵니다. 각 멤버는 선언 순서에 맞춰 설명하고 여러 줄 설명도 허용됩니다.

짧은 설명 뒤에 빈 줄을 두고 형식 전체의 긴 설명을 작성할 수 있습니다. 원문에서 이 종료 규칙을 함수 이름이라고 표현하지만, 문맥상 여기서는 형식 이름 뒤의 짧은 설명에 같은 규칙이 적용된다는 뜻입니다.

구조체·공용체 내부에서는 `private:`와 `public:` 레이블로 최종 문서에 포함할 영역을 전환할 수 있습니다. `private:` 영역의 필드는 추출된 공개 문서에서 제외됩니다.

두 레이블은 반드시 `/*` 주석 시작 표식 바로 뒤에 둡니다. 콜론과 `*/` 사이에는 해당 영역의 목적을 설명하는 선택적 문구를 넣을 수 있습니다.

예제의 `my_struct`는 `a`, `b`, `d`만 공개 문서에 기술합니다. `c`는 `/* private: internal use only */` 뒤에 있어 숨겨지고, 다음 `public:` 표식부터 `d`가 다시 공개됩니다.

  /**
   * struct struct_name - Brief description.
   * @member1: Description of member1.
   * @member2: Description of member2.
   *           One can provide multiple line descriptions
   *           for members.
   *
   * Description of the structure.
   */
  /**
   * struct my_struct - short description
   * @a: first member
   * @b: second member
   * @d: fourth member
   *
   * Longer description
   */
  struct my_struct {
      int a;
      int b;
  /* private: internal use only */
      int c;
  /* public: the next one is public */
      int d;
  };
형식별 첫 줄
대상첫 줄
구조체struct name - brief
공용체union name - brief
열거형enum name - brief

대상 종류만 바꾸고 이름·짧은 설명 구조는 유지합니다.

멤버 공개 범위
기본 / public:멤버 문서 포함
private:후속 멤버 문서 제외
다음 public:후속 멤버 다시 포함

소스의 레이블이 최종 문서 포함 여부를 전환합니다.

Documentare strutture, unioni ed enumerazioni
---------------------------------------------

Generalmente il formato di un commento kernel-doc per struct, union ed enum è::

  /**
   * struct struct_name - Brief description.
   * @member1: Description of member1.
   * @member2: Description of member2.
   *           One can provide multiple line descriptions
   *           for members.
   *
   * Description of the structure.
   */

Nell'esempio qui sopra, potete sostituire ``struct`` con ``union`` o ``enum``
per descrivere unioni ed enumerati. ``member`` viene usato per indicare i
membri di strutture ed unioni, ma anche i valori di un tipo enumerato.

La descrizione introduttiva (*brief description*) che segue il nome della
funzione può continuare su righe successive e termina con la descrizione di
un argomento, una linea di commento vuota, oppure la fine del commento.

Membri
~~~~~~

I membri di strutture, unioni ed enumerati devo essere documentati come i
parametri delle funzioni; seguono la descrizione introduttiva e possono
estendersi su più righe.

All'interno d'una struttura o d'un unione, potete utilizzare le etichette
``private:`` e ``public:``. I campi che sono nell'area ``private:`` non
verranno inclusi nella documentazione finale.

Le etichette ``private:`` e ``public:`` devono essere messe subito dopo
il marcatore di un commento ``/*``. Opzionalmente, possono includere commenti
fra ``:`` e il marcatore di fine commento ``*/``.

Esempio::

  /**
   * struct my_struct - short description
   * @a: first member
   * @b: second member
   * @d: fourth member
   *
   * Longer description
   */
  struct my_struct {
      int a;
      int b;
  /* private: internal use only */
      int c;
  /* public: the next one is public */
      int d;
  };

중첩 형식과 인라인 멤버 주석

259-347

중첩 구조체와 공용체도 kernel-doc으로 문서화할 수 있습니다. 이름이 있는 중첩 객체는 바깥 필드부터 점으로 이어지는 전체 경로를 사용합니다.

예제에서 이름 있는 공용체 `bar` 안의 구조체 `st1`은 `@bar.st1:`로 설명합니다. 그 안의 `memb1`은 `@bar.st1.memb1:`처럼 계층 전체를 표시합니다.

익명 구조체나 익명 공용체의 멤버는 익명 컨테이너 이름을 만들지 않습니다. 바깥 형식에 직접 노출된 것처럼 `@memb1:` 또는 일반 규칙의 `@bar:`로 기록합니다.

이름 있는 중첩 형식 `foo`의 멤버 `bar`는 `@foo.bar:`를 사용하고, 중첩 형식 자체가 익명이면 그 멤버를 `@bar:`로 사용한다는 두 규칙을 구분해야 합니다.

멤버 설명은 형식 주석의 머리 부분에만 둘 필요가 없습니다. 구조체 정의 안에서 해당 멤버 선언 바로 위에 인라인 kernel-doc 주석을 배치할 수 있습니다.

인라인 주석에는 두 가지 스타일이 있습니다. `/**`로 시작하고 `*/`로 끝나는 한 줄 형식과, 다른 kernel-doc 주석처럼 여러 문단을 담는 여러 줄 형식입니다.

인라인 주석에서도 중첩 경로 규칙은 그대로 적용됩니다. 예제의 `bar2`는 `@bar2`, 그 내부 `barbar`는 `@bar2.barbar`로 설명합니다.

      /**
       * struct nested_foobar - a struct with nested unions and structs
       * @memb1: first member of anonymous union/anonymous struct
       * @memb2: second member of anonymous union/anonymous struct
       * @memb3: third member of anonymous union/anonymous struct
       * @memb4: fourth member of anonymous union/anonymous struct
       * @bar: non-anonymous union
       * @bar.st1: struct st1 inside @bar
       * @bar.st2: struct st2 inside @bar
       * @bar.st1.memb1: first member of struct st1 on union bar
       * @bar.st1.memb2: second member of struct st1 on union bar
       * @bar.st2.memb1: first member of struct st2 on union bar
       * @bar.st2.memb2: second member of struct st2 on union bar
       */
      struct nested_foobar {
        /* Anonymous union/struct*/
        union {
          struct {
            int memb1;
            int memb2;
        }
          struct {
            void *memb3;
            int memb4;
          }
        }
        union {
          struct {
            int memb1;
            int memb2;
          } st1;
          struct {
            void *memb1;
            int memb2;
          } st2;
        } bar;
      };
  /**
   * struct foo - Brief description.
   * @foo: The Foo member.
   */
  struct foo {
        int foo;
        /**
         * @bar: The Bar member.
         */
        int bar;
        /**
         * @baz: The Baz member.
         *
         * Here, the member description may contain several paragraphs.
         */
        int baz;
        union {
                /** @foobar: Single line description. */
                int foobar;
        };
        /** @bar2: Description for struct @bar2 inside @foo */
        struct {
                /**
                 * @bar2.barbar: Description for @barbar inside @foo.bar2
                 */
                int barbar;
        } bar2;
  };
중첩 멤버 이름 규칙
구조표기
이름 있는 중첩 형식전체 점 경로@bar.st1.memb1:
익명 중첩 형식노출된 멤버 이름@bar:
인라인 중첩 멤버바깥 필드부터 전체 경로@bar2.barbar:

익명 여부에 따라 문서 이름의 경로가 달라집니다.

인라인 주석 스타일
스타일용도
/** @member: 설명. */짧은 단일 문장
여러 줄 /** ... */여러 문단 또는 상세 제약

멤버 설명 길이에 맞춰 한 줄 또는 여러 줄 형식을 선택합니다.

Strutture ed unioni annidate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

È possibile documentare strutture ed unioni annidate, ad esempio::

      /**
       * struct nested_foobar - a struct with nested unions and structs
       * @memb1: first member of anonymous union/anonymous struct
       * @memb2: second member of anonymous union/anonymous struct
       * @memb3: third member of anonymous union/anonymous struct
       * @memb4: fourth member of anonymous union/anonymous struct
       * @bar: non-anonymous union
       * @bar.st1: struct st1 inside @bar
       * @bar.st2: struct st2 inside @bar
       * @bar.st1.memb1: first member of struct st1 on union bar
       * @bar.st1.memb2: second member of struct st1 on union bar
       * @bar.st2.memb1: first member of struct st2 on union bar
       * @bar.st2.memb2: second member of struct st2 on union bar
       */
      struct nested_foobar {
        /* Anonymous union/struct*/
        union {
          struct {
            int memb1;
            int memb2;
        }
          struct {
            void *memb3;
            int memb4;
          }
        }
        union {
          struct {
            int memb1;
            int memb2;
          } st1;
          struct {
            void *memb1;
            int memb2;
          } st2;
        } bar;
      };

.. note::

   #) Quando documentate una struttura od unione annidata, ad esempio
      di nome ``foo``, il suo campo ``bar`` dev'essere documentato
      usando ``@foo.bar:``
   #) Quando la struttura od unione annidata è anonima, il suo campo
      ``bar`` dev'essere documentato usando ``@bar:``

Commenti in linea per la documentazione dei membri
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I membri d'una struttura possono essere documentati in linea all'interno
della definizione stessa. Ci sono due stili: una singola riga di commento
che inizia con ``/**`` e finisce con ``*/``; commenti multi riga come
qualsiasi altro commento kernel-doc::

  /**
   * struct foo - Brief description.
   * @foo: The Foo member.
   */
  struct foo {
        int foo;
        /**
         * @bar: The Bar member.
         */
        int bar;
        /**
         * @baz: The Baz member.
         *
         * Here, the member description may contain several paragraphs.
         */
        int baz;
        union {
                /** @foobar: Single line description. */
                int foobar;
        };
        /** @bar2: Description for struct @bar2 inside @foo */
        struct {
                /**
                 * @bar2.barbar: Description for @barbar inside @foo.bar2
                 */
                int barbar;
        } bar2;
  };

typedef 문서화

348-372

일반 `typedef`는 `typedef type_name - Brief description.`으로 시작합니다. 빈 줄 뒤에는 해당 형식의 의미와 사용 목적을 길게 설명할 수 있습니다.

함수 포인터 원형을 정의하는 `typedef`도 문서화할 수 있습니다. 이 경우 함수 주석처럼 각 인자를 `@arg1`, `@arg2`로 설명합니다.

함수형 typedef에는 `Context`와 `Return` 절도 사용할 수 있습니다. 호출 때 필요한 락 문맥과 반환값의 의미를 형식 자체의 계약으로 기록합니다.

예제의 실제 선언 `typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);`처럼, 주석의 인자 이름은 함수 포인터 선언의 인자 이름과 일치해야 합니다.

  /**
   * typedef type_name - Brief description.
   *
   * Description of the type.
   */

Anche i tipi di dato per prototipi di funzione possono essere documentati::

  /**
   * typedef type_name - Brief description.
   * @arg1: description of arg1
   * @arg2: description of arg2
   *
   * Description of the type.
   *
   * Context: Locking context.
   * Return: Meaning of the return value.
   */
   typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);
typedef 두 형식
종류필수 요소추가 요소
일반 typedef이름, 짧은 설명긴 형식 설명
함수 원형 typedef이름, 인자 설명Context, Return

단순 별칭과 함수 원형 별칭의 문서 요소를 비교합니다.

함수형 typedef 계약
typedef 이름인자별 의미
Context호출·락 조건
Return반환값 의미

형식 정의가 호출 규약까지 전달하도록 구성합니다.

Documentazione dei tipi di dato
-------------------------------
Generalmente il formato di un commento kernel-doc per typedef è
il seguente::

  /**
   * typedef type_name - Brief description.
   *
   * Description of the type.
   */

Anche i tipi di dato per prototipi di funzione possono essere documentati::

  /**
   * typedef type_name - Brief description.
   * @arg1: description of arg1
   * @arg2: description of arg2
   *
   * Description of the type.
   *
   * Context: Locking context.
   * Return: Meaning of the return value.
   */
   typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2);

객체형 매크로 문서화

373-416

객체형 매크로와 함수형 매크로는 이름 바로 뒤에 왼쪽 괄호 `(`가 있는지로 구별합니다. 공백 없이 괄호가 이어지면 함수형이고, 그렇지 않으면 객체형입니다.

`scripts/kernel-doc`는 함수형 매크로를 함수처럼 처리하므로 매개변수 목록을 문서화할 수 있습니다. 객체형 매크로에는 매개변수 목록이 없습니다.

객체형 매크로의 첫 줄은 `define object_name - Brief description.`입니다. 빈 줄 뒤에는 상수가 표현하는 범위, 초기화 조각의 효과, 사용상의 제약 등을 설명합니다.

`MAX_ERRNO` 예제는 커널 포인터의 중복 표현을 활용해 오류 코드와 정상 포인터를 같은 반환 형식에 담는 배경을 설명하고 값 `4095`를 정의합니다.

`DRM_GEM_VRAM_PLANE_HELPER_FUNCS` 예제처럼 여러 줄로 확장되는 초기화 매크로도 객체형으로 문서화할 수 있습니다. 첫 줄 설명의 역슬래시와 실제 매크로 정의의 줄 연속 문자는 그대로 보존해야 합니다.

  /**
   * define object_name - Brief description.
   *
   * Description of the object.
   */

Esempio::

  /**
   * define MAX_ERRNO - maximum errno value that is supported
   *
   * Kernel pointers have redundant information, so we can use a
   * scheme where we can return either an error code or a normal
   * pointer with the same return value.
   */
  #define MAX_ERRNO	4095

Esempio::

  /**
   * define DRM_GEM_VRAM_PLANE_HELPER_FUNCS - \
   *	Initializes struct drm_plane_helper_funcs for VRAM handling
   *
   * This macro initializes struct drm_plane_helper_funcs to use the
   * respective helper functions.
   */
  #define DRM_GEM_VRAM_PLANE_HELPER_FUNCS \
	.prepare_fb = drm_gem_vram_plane_helper_prepare_fb, \
	.cleanup_fb = drm_gem_vram_plane_helper_cleanup_fb
매크로 분류
종류구분kernel-doc 처리
함수형이름 직후 `(`함수처럼 처리, 매개변수 가능
객체형이름 직후 `(` 없음define 형식, 매개변수 없음

이름 뒤 괄호와 매개변수 유무로 문서 형식을 결정합니다.

객체형 매크로 설명
define 이름과 요약값·초기화 목적
긴 설명배경과 사용 제약
실제 #define구현과 문서 인접

값만 반복하지 않고 의미와 효과를 함께 기록합니다.

Documentazione di macro simili a oggetti
----------------------------------------

Le macro simili a oggetti si distinguono dalle macro simili a funzione. Esse si
distinguono in base al fatto che il nome della macro simile a funzione sia
immediatamente seguito da una parentesi sinistra ('(') mentre in quelle simili a
oggetti no.

Le macro simili a funzioni sono gestite come funzioni da ``scripts/kernel-doc``.
Possono avere un elenco di parametri. Le macro simili a oggetti non hanno un
elenco di parametri.

Il formato generale di un commento kernel-doc per una macro simile a oggetti è::

  /**
   * define object_name - Brief description.
   *
   * Description of the object.
   */

Esempio::

  /**
   * define MAX_ERRNO - maximum errno value that is supported
   *
   * Kernel pointers have redundant information, so we can use a
   * scheme where we can return either an error code or a normal
   * pointer with the same return value.
   */
  #define MAX_ERRNO	4095

Esempio::

  /**
   * define DRM_GEM_VRAM_PLANE_HELPER_FUNCS - \
   *	Initializes struct drm_plane_helper_funcs for VRAM handling
   *
   * This macro initializes struct drm_plane_helper_funcs to use the
   * respective helper functions.
   */
  #define DRM_GEM_VRAM_PLANE_HELPER_FUNCS \
	.prepare_fb = drm_gem_vram_plane_helper_prepare_fb, \
	.cleanup_fb = drm_gem_vram_plane_helper_cleanup_fb

kernel-doc 마크업과 참조

417-465

kernel-doc 주석 안에서는 정해진 패턴을 reStructuredText 마크업과 `Sphinx C domain` 참조로 변환합니다. 이 패턴들은 오직 kernel-doc 주석 안에서만 인식되며 일반 reStructuredText 문서에서는 같은 의미를 갖지 않습니다.

`funcname()`은 함수 참조를 만듭니다. 괄호가 함수라는 의미를 전달하므로 이름만 쓰는 것과 구별됩니다.

`@parameter`는 함수 매개변수 이름을 서식화하고 `%CONST`는 상수 이름을 서식화합니다. 둘은 모양을 구분할 뿐 별도의 대상 링크를 생성하지 않습니다.

이중 백틱으로 감싼 리터럴은 내용을 그대로 표시하고 최종 출력에서 고정폭 글꼴을 사용합니다. `%ph`처럼 kernel-doc이나 reStructuredText에서 특수 의미를 가질 수 있는 문자열을 문자 그대로 적을 때 특히 유용합니다.

`$ENVVAR`는 환경 변수 이름을 서식화하며 링크는 만들지 않습니다. 환경 변수와 C 심볼을 눈으로 구분할 수 있게 하는 표기입니다.

`&struct name`, `&enum name`, `&typedef name`은 각각 구조체, 열거형, typedef를 정확한 종류로 참조합니다. 가능한 한 이 완전한 형식을 사용해야 링크 대상과 의미가 명확합니다.

`&struct_name->member`와 `&struct_name.member`는 구조체 또는 공용체 멤버를 표현하지만 실제 참조 대상은 멤버가 아니라 컨테이너 형식입니다.

`&name`은 오래된 주석을 위한 일반 형식 참조입니다. 종류 정보를 잃으므로 새 주석에서는 위의 완전한 구조체·열거형·typedef 참조를 우선합니다.

kernel-doc 전용 마크업
패턴의미참조 생성
funcname()함수
@parameter매개변수아니요
%CONST상수아니요
``literal``리터럴아니요
$ENVVAR환경 변수아니요
&struct / &enum / &typedef nameC 형식
&struct_name->member컨테이너의 멤버컨테이너 참조
&name구형 일반 형식

각 패턴의 표시와 링크 생성 여부를 구분합니다.

참조 표기 선택
함수name()
형식 종류를 앎&struct / &enum / &typedef
구형 주석 호환&name

가능한 한 대상 종류를 명시해 정확한 C domain 링크를 만듭니다.

Marcatori e riferimenti
-----------------------

All'interno dei commenti di tipo kernel-doc vengono riconosciuti i seguenti
*pattern* che vengono convertiti in marcatori reStructuredText ed in riferimenti
del `dominio Sphinx per il C`_.

.. attention:: Questi sono riconosciuti **solo** all'interno di commenti
               kernel-doc, e **non** all'interno di documenti reStructuredText.

``funcname()``
  Riferimento ad una funzione.

``@parameter``
  Nome di un parametro di una funzione (nessun riferimento, solo formattazione).

``%CONST``
  Il nome di una costante (nessun riferimento, solo formattazione)

````literal````
  Un blocco di testo che deve essere riportato così com'è. La rappresentazione
  finale utilizzerà caratteri a ``spaziatura fissa``.

  Questo è utile se dovete utilizzare caratteri speciali che altrimenti
  potrebbero assumere un significato diverso in kernel-doc o in reStructuredText

  Questo è particolarmente utile se dovete scrivere qualcosa come ``%ph``
  all'interno della descrizione di una funzione.

``$ENVVAR``
  Il nome di una variabile d'ambiente (nessun riferimento, solo formattazione).

``&struct name``
  Riferimento ad una struttura.

``&enum name``
  Riferimento ad un'enumerazione.

``&typedef name``
  Riferimento ad un tipo di dato.

``&struct_name->member`` or ``&struct_name.member``
  Riferimento ad un membro di una struttura o di un'unione. Il riferimento sarà
  la struttura o l'unione, non il memembro.

``&name``
  Un generico riferimento ad un tipo. Usate, preferibilmente, il riferimento
  completo come descritto sopra. Questo è dedicato ai commenti obsoleti.

reStructuredText 참조와 DOC 개요

466-518

일반 reStructuredText 문서에서 kernel-doc으로 정의된 함수와 형식을 참조할 때는 kernel-doc 전용 특수 구문이 필요하지 않습니다. 함수 이름에는 `()`를 붙이고 형식 앞에는 `struct`, `union`, `enum`, `typedef`를 적으면 됩니다.

기본 표기는 `See foo()`, `See struct foo.`, `See union bar.`, `See enum baz.`, `See typedef meh.`처럼 작성합니다. Sphinx C domain이 이름과 종류를 이용해 대상 문서를 연결합니다.

링크에 표시할 문구를 바꾸려면 C domain 역할을 직접 사용합니다. 함수는 `:c:func:`, 형식은 `:c:type:` 역할에 사용자 문구와 실제 대상 이름을 함께 넣습니다.

코드와 개요 설명을 같은 소스 파일에 두려면 특정 함수나 형식에 묶이지 않는 자유 형식 kernel-doc 블록을 사용할 수 있습니다. 드라이버나 라이브러리의 동작 원리를 설명할 때 적합합니다.

자유 형식 블록은 `DOC:` 키워드와 제목으로 시작합니다. 뒤의 본문은 여러 문단을 포함할 수 있고 특정 C 선언 바로 위에 놓을 필요가 없습니다.

`DOC:` 뒤 제목은 소스 안의 머리말이면서 추출할 블록을 찾는 식별자입니다. 따라서 한 소스 파일 안에서 중복되지 않는 고유한 제목을 사용해야 합니다.

예제의 `DOC: Theory of Operation`은 가상의 장치가 어떻게 작동하는지 설명합니다. 실제 문서에서는 구현을 되풀이하기보다 구성 요소 관계, 데이터 흐름, 중요한 한계와 고장 조건을 기록하는 편이 유용합니다.

  See foo()
  See struct foo.
  See union bar.
  See enum baz.
  See typedef meh.

Tuttavia, la personalizzazione dei collegamenti è possibile solo con
la seguente sintassi::

  See :c:func:`my custom link text for function foo <foo>`.
  See :c:type:`my custom link text for struct bar <bar>`.
  /**
   * DOC: Theory of Operation
   *
   * The whizbang foobar is a dilly of a gizmo. It can do whatever you
   * want it to do, at any time. It reads your mind. Here's how it works.
   *
   * foo bar splat
   *
   * The only drawback to this gizmo is that is can sometimes damage
   * hardware, software, or its subject(s).
   */
reStructuredText의 C 참조
대상기본 표기사용자 문구
함수foo():c:func:
구조체·공용체·열거형·typedef종류 + 이름:c:type:

기본 링크와 사용자 표시 문구가 필요한 링크를 구분합니다.

DOC 개요 추출
/** DOC: 고유 제목여러 문단 개요
kernel-doc :doc: 옵션제목으로 블록 선택
Sphinx 문서개요 본문 포함

고유 제목이 자유 형식 설명을 선택하는 키가 됩니다.

Riferimenti usando reStructuredText
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Nei documenti reStructuredText non serve alcuna sintassi speciale per
fare riferimento a funzioni e tipi definiti nei commenti
kernel-doc. Sarà sufficiente terminare i nomi di funzione con ``()``,
e scrivere ``struct``, ``union``, ``enum``, o ``typedef`` prima di un
tipo. Per esempio::

  See foo()
  See struct foo.
  See union bar.
  See enum baz.
  See typedef meh.

Tuttavia, la personalizzazione dei collegamenti è possibile solo con
la seguente sintassi::

  See :c:func:`my custom link text for function foo <foo>`.
  See :c:type:`my custom link text for struct bar <bar>`.


Commenti per una documentazione generale
----------------------------------------

Al fine d'avere il codice ed i commenti nello stesso file, potete includere
dei blocchi di documentazione kernel-doc con un formato libero invece
che nel formato specifico per funzioni, strutture, unioni, enumerati o tipi
di dato. Per esempio, questo tipo di commento potrebbe essere usato per la
spiegazione delle operazioni di un driver o di una libreria

Questo s'ottiene utilizzando la parola chiave ``DOC:`` a cui viene associato
un titolo.

Generalmente il formato di un commento generico o di visione d'insieme è
il seguente::

  /**
   * DOC: Theory of Operation
   *
   * The whizbang foobar is a dilly of a gizmo. It can do whatever you
   * want it to do, at any time. It reads your mind. Here's how it works.
   *
   * foo bar splat
   *
   * The only drawback to this gizmo is that is can sometimes damage
   * hardware, software, or its subject(s).
   */

Il titolo che segue ``DOC:`` funziona da intestazione all'interno del file
sorgente, ma anche come identificatore per l'estrazione di questi commenti di
documentazione. Quindi, il titolo dev'essere unico all'interno del file.

Sphinx kernel-doc 지시문과 옵션

519-600

kernel-doc 문서 주석은 Sphinx의 kernel-doc 확장이 제공하는 지시문으로 어느 reStructuredText 문서에서나 포함할 수 있습니다. 지시문은 `.. kernel-doc:: source`와 들여쓴 옵션으로 구성합니다.

`source`는 커널 소스 트리의 최상위 디렉터리를 기준으로 한 소스 파일 경로입니다. 문서를 쓰는 `.rst` 파일의 위치를 기준으로 한 상대 경로가 아닙니다.

`:export:`는 `source`와 선택적인 `source-pattern`에서 `EXPORT_SYMBOL` 또는 `EXPORT_SYMBOL_GPL`로 내보낸 함수 문서만 포함합니다. 헤더에 주석이 있고 실제 내보내기 선언은 구현 파일에 있을 때 패턴을 함께 지정할 수 있습니다.

예를 들어 `include/net/mac80211.h`의 문서를 읽으면서 `net/mac80211/*.c`에서 내보내기 여부를 찾도록 지정할 수 있습니다. 이렇게 하면 선언·주석과 심볼 내보내기 위치가 달라도 공개 API를 정확히 선택합니다.

`:internal:`은 반대로 `source`와 패턴 어디에서도 내보내지 않은 함수와 형식만 포함합니다. 공개 API 문서와 내부 구현 문서를 별도 장으로 구성할 때 사용합니다.

`:identifiers:`는 지정한 함수나 형식만 선택합니다. 이름 목록을 비우면 해당 `source`에서 사용할 수 있는 모든 식별자를 포함합니다.

`:functions:`는 `identifiers`의 더 이상 권장되지 않는 별칭입니다. 기존 문서와 호환되지만 새 문서에서는 함수와 형식을 모두 일관되게 다루는 `identifiers`를 사용합니다.

`:doc: title`은 소스의 `DOC:` 자유 형식 절을 제목으로 선택합니다. 제목에는 공백을 쓸 수 있지만 따옴표로 감싸지 않으며, 선택에 사용한 제목 자체는 최종 본문에 출력되지 않습니다.

`:doc:` 제목은 출력 머리말이 아니므로 reStructuredText 문서 쪽에 적절한 절 제목을 따로 마련해야 합니다. 소스의 고유 식별자와 독자에게 보이는 문서 구조를 분리하는 규칙입니다.

아무 옵션도 주지 않으면 `source` 안의 모든 문서 주석을 포함합니다. 범위를 제한해야 하는 공개 API 장에서는 `export`, 특정 목록에서는 `identifiers`, 개요에서는 `doc`을 명시하는 편이 의도가 분명합니다.

Sphinx 확장 구현은 `Documentation/sphinx/kerneldoc.py`에 있습니다. 이 확장은 내부적으로 `scripts/kernel-doc`를 실행해 소스 파일에서 문서 주석을 추출합니다.

Le direttive kernel-doc sono nel formato::

  .. kernel-doc:: source
     :option:

Il campo *source* è il percorso ad un file sorgente, relativo alla cartella
principale dei sorgenti del kernel. La direttiva supporta le seguenti opzioni:

export: *[source-pattern ...]*
  Include la documentazione per tutte le funzioni presenti nel file sorgente
  (*source*) che sono state esportate utilizzando ``EXPORT_SYMBOL`` o
  ``EXPORT_SYMBOL_GPL`` in *source* o in qualsiasi altro *source-pattern*
  specificato.

  Il campo *source-patter* è utile quando i commenti kernel-doc sono stati
  scritti nei file d'intestazione, mentre ``EXPORT_SYMBOL`` e
  ``EXPORT_SYMBOL_GPL`` si trovano vicino alla definizione delle funzioni.

  Esempi::

    .. kernel-doc:: lib/bitmap.c
       :export:

    .. kernel-doc:: include/net/mac80211.h
       :export: net/mac80211/*.c
internal: *[source-pattern ...]*
  Include la documentazione per tutte le funzioni ed i tipi presenti nel file
  sorgente (*source*) che **non** sono stati esportati utilizzando
  ``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL`` né in *source* né in qualsiasi
  altro *source-pattern* specificato.

  Esempio::

    .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
       :internal:

identifiers: *[ function/type ...]*
  Include la documentazione per ogni *function* e *type*  in *source*.
  Se non vengono esplicitamente specificate le funzioni da includere, allora
  verranno incluse tutte quelle disponibili in *source*.

  Esempi::

    .. kernel-doc:: lib/bitmap.c
       :identifiers: bitmap_parselist bitmap_parselist_user

    .. kernel-doc:: lib/idr.c
       :identifiers:

functions: *[ function ...]*
  Questo è uno pseudonimo, deprecato, per la direttiva 'identifiers'.

doc: *title*
  Include la documentazione del paragrafo ``DOC:`` identificato dal titolo
  (*title*) all'interno del file sorgente (*source*). Gli spazi in *title* sono
  permessi; non virgolettate *title*. Il campo *title* è utilizzato per
  identificare un paragrafo e per questo non viene incluso nella documentazione
  finale. Verificate d'avere l'intestazione appropriata nei documenti
  reStructuredText.

  Esempio::

    .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
       :doc: High Definition Audio over HDMI and Display Port
kernel-doc 지시문 옵션
옵션포함 대상주요 용도
export내보낸 함수공개 모듈 API
internal내보내지 않은 함수·형식내부 구현
identifiers지정 함수·형식 또는 전체선택 API
functionsidentifiers의 구형 별칭기존 문서 호환
doc제목이 일치하는 DOC 절설계·동작 개요
옵션 없음소스의 모든 문서 주석전체 포함

포함 대상을 선택하는 기준을 비교합니다.

export와 internal
판정exportinternal
EXPORT_SYMBOL 계열에서 발견포함제외
어느 대상에서도 발견되지 않음제외포함

같은 소스와 패턴을 기준으로 내보내기 여부를 반대로 선택합니다.

Sphinx 포함 경로
.. kernel-doc:: sourceDocumentation/sphinx/kerneldoc.py
옵션으로 범위 선택scripts/kernel-doc 실행
추출된 주석reStructuredText 문서에 포함

지시문이 확장과 추출기를 거쳐 문서 조각을 만듭니다.

=======================================
Includere i commenti di tipo kernel-doc
=======================================

I commenti di documentazione possono essere inclusi in un qualsiasi documento
di tipo reStructuredText mediante l'apposita direttiva nell'estensione
kernel-doc per Sphinx.

Le direttive kernel-doc sono nel formato::

  .. kernel-doc:: source
     :option:

Il campo *source* è il percorso ad un file sorgente, relativo alla cartella
principale dei sorgenti del kernel. La direttiva supporta le seguenti opzioni:

export: *[source-pattern ...]*
  Include la documentazione per tutte le funzioni presenti nel file sorgente
  (*source*) che sono state esportate utilizzando ``EXPORT_SYMBOL`` o
  ``EXPORT_SYMBOL_GPL`` in *source* o in qualsiasi altro *source-pattern*
  specificato.

  Il campo *source-patter* è utile quando i commenti kernel-doc sono stati
  scritti nei file d'intestazione, mentre ``EXPORT_SYMBOL`` e
  ``EXPORT_SYMBOL_GPL`` si trovano vicino alla definizione delle funzioni.

  Esempi::

    .. kernel-doc:: lib/bitmap.c
       :export:

    .. kernel-doc:: include/net/mac80211.h
       :export: net/mac80211/*.c

internal: *[source-pattern ...]*
  Include la documentazione per tutte le funzioni ed i tipi presenti nel file
  sorgente (*source*) che **non** sono stati esportati utilizzando
  ``EXPORT_SYMBOL`` o ``EXPORT_SYMBOL_GPL`` né in *source* né in qualsiasi
  altro *source-pattern* specificato.

  Esempio::

    .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
       :internal:

identifiers: *[ function/type ...]*
  Include la documentazione per ogni *function* e *type*  in *source*.
  Se non vengono esplicitamente specificate le funzioni da includere, allora
  verranno incluse tutte quelle disponibili in *source*.

  Esempi::

    .. kernel-doc:: lib/bitmap.c
       :identifiers: bitmap_parselist bitmap_parselist_user

    .. kernel-doc:: lib/idr.c
       :identifiers:

functions: *[ function ...]*
  Questo è uno pseudonimo, deprecato, per la direttiva 'identifiers'.

doc: *title*
  Include la documentazione del paragrafo ``DOC:`` identificato dal titolo
  (*title*) all'interno del file sorgente (*source*). Gli spazi in *title* sono
  permessi; non virgolettate *title*. Il campo *title* è utilizzato per
  identificare un paragrafo e per questo non viene incluso nella documentazione
  finale. Verificate d'avere l'intestazione appropriata nei documenti
  reStructuredText.

  Esempio::

    .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c
       :doc: High Definition Audio over HDMI and Display Port

Senza alcuna opzione, la direttiva kernel-doc include tutti i commenti di
documentazione presenti nel file sorgente (*source*).

L'estensione kernel-doc fa parte dei sorgenti del kernel, la si può trovare
in ``Documentation/sphinx/kerneldoc.py``. Internamente, viene utilizzato
lo script ``scripts/kernel-doc`` per estrarre i commenti di documentazione
dai file sorgenti.

kernel-doc으로 man 페이지 생성

601-607

Sphinx 문서가 아니라 man 페이지만 필요하면 커널 소스 트리에서 `scripts/kernel-doc -man`을 직접 실행할 수 있습니다.

예제의 `git grep`은 `/**`가 들어 있는 파일을 찾되 `Documentation`과 `tools` 경로를 제외합니다. 선택된 소스들을 kernel-doc의 man 출력 모드에 전달합니다.

생성된 연속 man 출력은 파이프로 `scripts/split-man.pl /tmp/man`에 전달됩니다. 분할 스크립트는 항목별 man 페이지를 지정 디렉터리에 기록합니다.

  $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man
man 페이지 생성 파이프라인
git grep -l '/**'대상 소스 목록
scripts/kernel-doc -man연속 man 출력
scripts/split-man.pl /tmp/man개별 man 페이지

문서 주석이 있는 소스를 찾고 man 출력으로 변환한 뒤 파일별로 나눕니다.

Come utilizzare kernel-doc per generare pagine man
--------------------------------------------------

Se volete utilizzare kernel-doc solo per generare delle pagine man, potete
farlo direttamente dai sorgenti del kernel::

  $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man