요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. 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.
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
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
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.
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;
};
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;
};
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);
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
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.
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.
=======================================
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.
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
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` 판단에 맡깁니다. 이 기준은 공개 계약을 먼저 완성하고 내부 구현 설명은 유지보수 비용과 효용을 따져 추가하라는 뜻입니다.
원문 후반은 이 정책을 다시 강조합니다. 내보낸 함수는 필수, 다른 파일에서 보이는 함수와 헤더에 공개된 자료구조는 강한 권장, 정적 함수는 유지관리자 재량이라는 세 단계로 읽으면 됩니다.
심볼의 노출 범위에 따라 문서화 요구 수준을 구분합니다.
소스 주석이 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-89kernel-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
주석을 어디에 두고 어떤 검사로 확인하는지 정리합니다.
짧은 진단과 빌드 검사를 차례로 적용합니다.
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
한 함수 주석의 구성 요소와 종료 조건입니다.
지원되는 정렬 방식과 가변 인수 표기입니다.
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
호출 가능성뿐 아니라 동기화 계약까지 함께 기록합니다.
단순 줄바꿈은 합쳐지므로 목록 구조를 명시해야 합니다.
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;
};
대상 종류만 바꾸고 이름·짧은 설명 구조는 유지합니다.
소스의 레이블이 최종 문서 포함 여부를 전환합니다.
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;
};
익명 여부에 따라 문서 이름의 경로가 달라집니다.
멤버 설명 길이에 맞춰 한 줄 또는 여러 줄 형식을 선택합니다.
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);
단순 별칭과 함수 원형 별칭의 문서 요소를 비교합니다.
형식 정의가 호출 규약까지 전달하도록 구성합니다.
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
이름 뒤 괄호와 매개변수 유무로 문서 형식을 결정합니다.
값만 반복하지 않고 의미와 효과를 함께 기록합니다.
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-465kernel-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 참조를 우선합니다.
각 패턴의 표시와 링크 생성 여부를 구분합니다.
가능한 한 대상 종류를 명시해 정확한 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).
*/
기본 링크와 사용자 표시 문구가 필요한 링크를 구분합니다.
고유 제목이 자유 형식 설명을 선택하는 키가 됩니다.
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-600kernel-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
포함 대상을 선택하는 기준을 비교합니다.
같은 소스와 패턴을 기준으로 내보내기 여부를 반대로 선택합니다.
지시문이 확장과 추출기를 거쳐 문서 조각을 만듭니다.
=======================================
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-607Sphinx 문서가 아니라 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 출력으로 변환한 뒤 파일별로 나눕니다.
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
요약·해설
kernel-doc.rst:1-607kernel-doc은 커널 C 소스의 `/**` 주석에서 함수, 자료형, 매크로와 설계 개요를 추출해 Sphinx C domain 문서로 연결합니다. 공개 심볼과 헤더 인터페이스를 우선 문서화하고, 인자·호출 문맥·반환값·멤버 공개 범위를 정해진 문법으로 기록해야 합니다.
이 페이지는 중첩 멤버 이름, 객체형 매크로, kernel-doc 전용 참조 표식, `DOC:` 개요, `export`·`internal`·`identifiers`·`doc` 지시문까지 실제 예제로 다룹니다. 마지막에는 같은 주석으로 man 페이지를 생성하는 명령 파이프라인을 제시합니다.