xref: /linux/scripts/kernel-doc (revision a5cdaea525c32e7def563ba07d9fef9bc6edffab)
1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3
4use warnings;
5use strict;
6
7## Copyright (c) 1998 Michael Zucchi, All Rights Reserved        ##
8## Copyright (C) 2000, 1  Tim Waugh <twaugh@redhat.com>          ##
9## Copyright (C) 2001  Simon Huggins                             ##
10## Copyright (C) 2005-2012  Randy Dunlap                         ##
11## Copyright (C) 2012  Dan Luedtke                               ##
12## 								 ##
13## #define enhancements by Armin Kuster <akuster@mvista.com>	 ##
14## Copyright (c) 2000 MontaVista Software, Inc.			 ##
15## 								 ##
16## This software falls under the GNU General Public License.     ##
17## Please read the COPYING file for more information             ##
18
19=head1 NAME
20
21kernel-doc - Print formatted kernel documentation to stdout
22
23=head1 SYNOPSIS
24
25 kernel-doc [-h] [-v] [-Werror]
26   [ -man |
27     -rst [-sphinx-version VERSION] [-enable-lineno] |
28     -none
29   ]
30   [
31     -export |
32     -internal |
33     [-function NAME] ... |
34     [-nosymbol NAME] ...
35   ]
36   [-no-doc-sections]
37   [-export-file FILE] ...
38   FILE ...
39
40Run `kernel-doc -h` for details.
41
42=cut
43
44# 18/01/2001 - 	Cleanups
45# 		Functions prototyped as foo(void) same as foo()
46# 		Stop eval'ing where we don't need to.
47# -- huggie@earth.li
48
49# 27/06/2001 -  Allowed whitespace after initial "/**" and
50#               allowed comments before function declarations.
51# -- Christian Kreibich <ck@whoop.org>
52
53# Still to do:
54# 	- add perldoc documentation
55# 	- Look more closely at some of the scarier bits :)
56
57# 26/05/2001 - 	Support for separate source and object trees.
58#		Return error code.
59# 		Keith Owens <kaos@ocs.com.au>
60
61# 23/09/2001 - Added support for typedefs, structs, enums and unions
62#              Support for Context section; can be terminated using empty line
63#              Small fixes (like spaces vs. \s in regex)
64# -- Tim Jansen <tim@tjansen.de>
65
66# 25/07/2012 - Added support for HTML5
67# -- Dan Luedtke <mail@danrl.de>
68
69sub usage {
70    my $message = <<"EOF";
71Usage: $0 [OPTION ...] FILE ...
72
73Read C language source or header FILEs, extract embedded documentation comments,
74and print formatted documentation to standard output.
75
76The documentation comments are identified by "/**" opening comment mark. See
77Documentation/doc-guide/kernel-doc.rst for the documentation comment syntax.
78
79Output format selection (mutually exclusive):
80  -man			Output troff manual page format. This is the default.
81  -rst			Output reStructuredText format.
82  -none			Do not output documentation, only warnings.
83
84Output format selection modifier (affects only ReST output):
85
86  -sphinx-version	Use the ReST C domain dialect compatible with an
87			specific Sphinx Version.
88			If not specified, kernel-doc will auto-detect using
89			the sphinx-build version found on PATH.
90
91Output selection (mutually exclusive):
92  -export		Only output documentation for symbols that have been
93			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
94                        in any input FILE or -export-file FILE.
95  -internal		Only output documentation for symbols that have NOT been
96			exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()
97                        in any input FILE or -export-file FILE.
98  -function NAME	Only output documentation for the given function(s)
99			or DOC: section title(s). All other functions and DOC:
100			sections are ignored. May be specified multiple times.
101  -nosymbol NAME	Exclude the specified symbols from the output
102		        documentation. May be specified multiple times.
103
104Output selection modifiers:
105  -no-doc-sections	Do not output DOC: sections.
106  -enable-lineno        Enable output of #define LINENO lines. Only works with
107                        reStructuredText format.
108  -export-file FILE     Specify an additional FILE in which to look for
109                        EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL(). To be used with
110                        -export or -internal. May be specified multiple times.
111
112Other parameters:
113  -v			Verbose output, more warnings and other information.
114  -h			Print this help.
115  -Werror		Treat warnings as errors.
116
117EOF
118    print $message;
119    exit 1;
120}
121
122#
123# format of comments.
124# In the following table, (...)? signifies optional structure.
125#                         (...)* signifies 0 or more structure elements
126# /**
127#  * function_name(:)? (- short description)?
128# (* @parameterx: (description of parameter x)?)*
129# (* a blank line)?
130#  * (Description:)? (Description of function)?
131#  * (section header: (section description)? )*
132#  (*)?*/
133#
134# So .. the trivial example would be:
135#
136# /**
137#  * my_function
138#  */
139#
140# If the Description: header tag is omitted, then there must be a blank line
141# after the last parameter specification.
142# e.g.
143# /**
144#  * my_function - does my stuff
145#  * @my_arg: its mine damnit
146#  *
147#  * Does my stuff explained.
148#  */
149#
150#  or, could also use:
151# /**
152#  * my_function - does my stuff
153#  * @my_arg: its mine damnit
154#  * Description: Does my stuff explained.
155#  */
156# etc.
157#
158# Besides functions you can also write documentation for structs, unions,
159# enums and typedefs. Instead of the function name you must write the name
160# of the declaration;  the struct/union/enum/typedef must always precede
161# the name. Nesting of declarations is not supported.
162# Use the argument mechanism to document members or constants.
163# e.g.
164# /**
165#  * struct my_struct - short description
166#  * @a: first member
167#  * @b: second member
168#  *
169#  * Longer description
170#  */
171# struct my_struct {
172#     int a;
173#     int b;
174# /* private: */
175#     int c;
176# };
177#
178# All descriptions can be multiline, except the short function description.
179#
180# For really longs structs, you can also describe arguments inside the
181# body of the struct.
182# eg.
183# /**
184#  * struct my_struct - short description
185#  * @a: first member
186#  * @b: second member
187#  *
188#  * Longer description
189#  */
190# struct my_struct {
191#     int a;
192#     int b;
193#     /**
194#      * @c: This is longer description of C
195#      *
196#      * You can use paragraphs to describe arguments
197#      * using this method.
198#      */
199#     int c;
200# };
201#
202# This should be use only for struct/enum members.
203#
204# You can also add additional sections. When documenting kernel functions you
205# should document the "Context:" of the function, e.g. whether the functions
206# can be called form interrupts. Unlike other sections you can end it with an
207# empty line.
208# A non-void function should have a "Return:" section describing the return
209# value(s).
210# Example-sections should contain the string EXAMPLE so that they are marked
211# appropriately in DocBook.
212#
213# Example:
214# /**
215#  * user_function - function that can only be called in user context
216#  * @a: some argument
217#  * Context: !in_interrupt()
218#  *
219#  * Some description
220#  * Example:
221#  *    user_function(22);
222#  */
223# ...
224#
225#
226# All descriptive text is further processed, scanning for the following special
227# patterns, which are highlighted appropriately.
228#
229# 'funcname()' - function
230# '$ENVVAR' - environmental variable
231# '&struct_name' - name of a structure (up to two words including 'struct')
232# '&struct_name.member' - name of a structure member
233# '@parameter' - name of a parameter
234# '%CONST' - name of a constant.
235# '``LITERAL``' - literal string without any spaces on it.
236
237## init lots of data
238
239my $errors = 0;
240my $warnings = 0;
241my $anon_struct_union = 0;
242
243# match expressions used to find embedded type information
244my $type_constant = '\b``([^\`]+)``\b';
245my $type_constant2 = '\%([-_\w]+)';
246my $type_func = '(\w+)\(\)';
247my $type_param = '\@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)';
248my $type_param_ref = '([\!]?)\@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)';
249my $type_fp_param = '\@(\w+)\(\)';  # Special RST handling for func ptr params
250my $type_fp_param2 = '\@(\w+->\S+)\(\)';  # Special RST handling for structs with func ptr params
251my $type_env = '(\$\w+)';
252my $type_enum = '\&(enum\s*([_\w]+))';
253my $type_struct = '\&(struct\s*([_\w]+))';
254my $type_typedef = '\&(typedef\s*([_\w]+))';
255my $type_union = '\&(union\s*([_\w]+))';
256my $type_member = '\&([_\w]+)(\.|->)([_\w]+)';
257my $type_fallback = '\&([_\w]+)';
258my $type_member_func = $type_member . '\(\)';
259
260# Output conversion substitutions.
261#  One for each output format
262
263# these are pretty rough
264my @highlights_man = (
265                      [$type_constant, "\$1"],
266                      [$type_constant2, "\$1"],
267                      [$type_func, "\\\\fB\$1\\\\fP"],
268                      [$type_enum, "\\\\fI\$1\\\\fP"],
269                      [$type_struct, "\\\\fI\$1\\\\fP"],
270                      [$type_typedef, "\\\\fI\$1\\\\fP"],
271                      [$type_union, "\\\\fI\$1\\\\fP"],
272                      [$type_param, "\\\\fI\$1\\\\fP"],
273                      [$type_param_ref, "\\\\fI\$1\$2\\\\fP"],
274                      [$type_member, "\\\\fI\$1\$2\$3\\\\fP"],
275                      [$type_fallback, "\\\\fI\$1\\\\fP"]
276		     );
277my $blankline_man = "";
278
279# rst-mode
280my @highlights_rst = (
281                       [$type_constant, "``\$1``"],
282                       [$type_constant2, "``\$1``"],
283                       # Note: need to escape () to avoid func matching later
284                       [$type_member_func, "\\:c\\:type\\:`\$1\$2\$3\\\\(\\\\) <\$1>`"],
285                       [$type_member, "\\:c\\:type\\:`\$1\$2\$3 <\$1>`"],
286		       [$type_fp_param, "**\$1\\\\(\\\\)**"],
287		       [$type_fp_param2, "**\$1\\\\(\\\\)**"],
288                       [$type_func, "\$1()"],
289                       [$type_enum, "\\:c\\:type\\:`\$1 <\$2>`"],
290                       [$type_struct, "\\:c\\:type\\:`\$1 <\$2>`"],
291                       [$type_typedef, "\\:c\\:type\\:`\$1 <\$2>`"],
292                       [$type_union, "\\:c\\:type\\:`\$1 <\$2>`"],
293                       # in rst this can refer to any type
294                       [$type_fallback, "\\:c\\:type\\:`\$1`"],
295                       [$type_param_ref, "**\$1\$2**"]
296		      );
297my $blankline_rst = "\n";
298
299# read arguments
300if ($#ARGV == -1) {
301    usage();
302}
303
304my $kernelversion;
305my ($sphinx_major, $sphinx_minor, $sphinx_patch);
306
307my $dohighlight = "";
308
309my $verbose = 0;
310my $Werror = 0;
311my $output_mode = "rst";
312my $output_preformatted = 0;
313my $no_doc_sections = 0;
314my $enable_lineno = 0;
315my @highlights = @highlights_rst;
316my $blankline = $blankline_rst;
317my $modulename = "Kernel API";
318
319use constant {
320    OUTPUT_ALL          => 0, # output all symbols and doc sections
321    OUTPUT_INCLUDE      => 1, # output only specified symbols
322    OUTPUT_EXPORTED     => 2, # output exported symbols
323    OUTPUT_INTERNAL     => 3, # output non-exported symbols
324};
325my $output_selection = OUTPUT_ALL;
326my $show_not_found = 0;	# No longer used
327
328my @export_file_list;
329
330my @build_time;
331if (defined($ENV{'KBUILD_BUILD_TIMESTAMP'}) &&
332    (my $seconds = `date -d"${ENV{'KBUILD_BUILD_TIMESTAMP'}}" +%s`) ne '') {
333    @build_time = gmtime($seconds);
334} else {
335    @build_time = localtime;
336}
337
338my $man_date = ('January', 'February', 'March', 'April', 'May', 'June',
339		'July', 'August', 'September', 'October',
340		'November', 'December')[$build_time[4]] .
341  " " . ($build_time[5]+1900);
342
343# Essentially these are globals.
344# They probably want to be tidied up, made more localised or something.
345# CAVEAT EMPTOR!  Some of the others I localised may not want to be, which
346# could cause "use of undefined value" or other bugs.
347my ($function, %function_table, %parametertypes, $declaration_purpose);
348my %nosymbol_table = ();
349my $declaration_start_line;
350my ($type, $declaration_name, $return_type);
351my ($newsection, $newcontents, $prototype, $brcount, %source_map);
352
353if (defined($ENV{'KBUILD_VERBOSE'})) {
354	$verbose = "$ENV{'KBUILD_VERBOSE'}";
355}
356
357if (defined($ENV{'KCFLAGS'})) {
358	my $kcflags = "$ENV{'KCFLAGS'}";
359
360	if ($kcflags =~ /Werror/) {
361		$Werror = 1;
362	}
363}
364
365if (defined($ENV{'KDOC_WERROR'})) {
366	$Werror = "$ENV{'KDOC_WERROR'}";
367}
368
369# Generated docbook code is inserted in a template at a point where
370# docbook v3.1 requires a non-zero sequence of RefEntry's; see:
371# https://www.oasis-open.org/docbook/documentation/reference/html/refentry.html
372# We keep track of number of generated entries and generate a dummy
373# if needs be to ensure the expanded template can be postprocessed
374# into html.
375my $section_counter = 0;
376
377my $lineprefix="";
378
379# Parser states
380use constant {
381    STATE_NORMAL        => 0,        # normal code
382    STATE_NAME          => 1,        # looking for function name
383    STATE_BODY_MAYBE    => 2,        # body - or maybe more description
384    STATE_BODY          => 3,        # the body of the comment
385    STATE_BODY_WITH_BLANK_LINE => 4, # the body, which has a blank line
386    STATE_PROTO         => 5,        # scanning prototype
387    STATE_DOCBLOCK      => 6,        # documentation block
388    STATE_INLINE        => 7,        # gathering doc outside main block
389};
390my $state;
391my $in_doc_sect;
392my $leading_space;
393
394# Inline documentation state
395use constant {
396    STATE_INLINE_NA     => 0, # not applicable ($state != STATE_INLINE)
397    STATE_INLINE_NAME   => 1, # looking for member name (@foo:)
398    STATE_INLINE_TEXT   => 2, # looking for member documentation
399    STATE_INLINE_END    => 3, # done
400    STATE_INLINE_ERROR  => 4, # error - Comment without header was found.
401                              # Spit a warning as it's not
402                              # proper kernel-doc and ignore the rest.
403};
404my $inline_doc_state;
405
406#declaration types: can be
407# 'function', 'struct', 'union', 'enum', 'typedef'
408my $decl_type;
409
410# Name of the kernel-doc identifier for non-DOC markups
411my $identifier;
412
413my $doc_start = '^/\*\*\s*$'; # Allow whitespace at end of comment start.
414my $doc_end = '\*/';
415my $doc_com = '\s*\*\s*';
416my $doc_com_body = '\s*\* ?';
417my $doc_decl = $doc_com . '(\w+)';
418# @params and a strictly limited set of supported section names
419# Specifically:
420#   Match @word:
421#	  @...:
422#         @{section-name}:
423# while trying to not match literal block starts like "example::"
424#
425my $doc_sect = $doc_com .
426    '\s*(\@[.\w]+|\@\.\.\.|description|context|returns?|notes?|examples?)\s*:([^:].*)?$';
427my $doc_content = $doc_com_body . '(.*)';
428my $doc_block = $doc_com . 'DOC:\s*(.*)?';
429my $doc_inline_start = '^\s*/\*\*\s*$';
430my $doc_inline_sect = '\s*\*\s*(@\s*[\w][\w\.]*\s*):(.*)';
431my $doc_inline_end = '^\s*\*/\s*$';
432my $doc_inline_oneline = '^\s*/\*\*\s*(@[\w\s]+):\s*(.*)\s*\*/\s*$';
433my $export_symbol = '^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*;';
434my $function_pointer = qr{([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)};
435my $attribute = qr{__attribute__\s*\(\([a-z0-9,_\*\s\(\)]*\)\)}i;
436
437my %parameterdescs;
438my %parameterdesc_start_lines;
439my @parameterlist;
440my %sections;
441my @sectionlist;
442my %section_start_lines;
443my $sectcheck;
444my $struct_actual;
445
446my $contents = "";
447my $new_start_line = 0;
448
449# the canonical section names. see also $doc_sect above.
450my $section_default = "Description";	# default section
451my $section_intro = "Introduction";
452my $section = $section_default;
453my $section_context = "Context";
454my $section_return = "Return";
455
456my $undescribed = "-- undescribed --";
457
458reset_state();
459
460while ($ARGV[0] =~ m/^--?(.*)/) {
461    my $cmd = $1;
462    shift @ARGV;
463    if ($cmd eq "man") {
464	$output_mode = "man";
465	@highlights = @highlights_man;
466	$blankline = $blankline_man;
467    } elsif ($cmd eq "rst") {
468	$output_mode = "rst";
469	@highlights = @highlights_rst;
470	$blankline = $blankline_rst;
471    } elsif ($cmd eq "none") {
472	$output_mode = "none";
473    } elsif ($cmd eq "module") { # not needed for XML, inherits from calling document
474	$modulename = shift @ARGV;
475    } elsif ($cmd eq "function") { # to only output specific functions
476	$output_selection = OUTPUT_INCLUDE;
477	$function = shift @ARGV;
478	$function_table{$function} = 1;
479    } elsif ($cmd eq "nosymbol") { # Exclude specific symbols
480	my $symbol = shift @ARGV;
481	$nosymbol_table{$symbol} = 1;
482    } elsif ($cmd eq "export") { # only exported symbols
483	$output_selection = OUTPUT_EXPORTED;
484	%function_table = ();
485    } elsif ($cmd eq "internal") { # only non-exported symbols
486	$output_selection = OUTPUT_INTERNAL;
487	%function_table = ();
488    } elsif ($cmd eq "export-file") {
489	my $file = shift @ARGV;
490	push(@export_file_list, $file);
491    } elsif ($cmd eq "v") {
492	$verbose = 1;
493    } elsif ($cmd eq "Werror") {
494	$Werror = 1;
495    } elsif (($cmd eq "h") || ($cmd eq "help")) {
496	usage();
497    } elsif ($cmd eq 'no-doc-sections') {
498	    $no_doc_sections = 1;
499    } elsif ($cmd eq 'enable-lineno') {
500	    $enable_lineno = 1;
501    } elsif ($cmd eq 'show-not-found') {
502	$show_not_found = 1;  # A no-op but don't fail
503    } elsif ($cmd eq "sphinx-version") {
504	my $ver_string = shift @ARGV;
505	if ($ver_string =~ m/^(\d+)(\.\d+)?(\.\d+)?/) {
506	    $sphinx_major = $1;
507	    if (defined($2)) {
508		$sphinx_minor = substr($2,1);
509	    } else {
510		$sphinx_minor = 0;
511	    }
512	    if (defined($3)) {
513		$sphinx_patch = substr($3,1)
514	    } else {
515		$sphinx_patch = 0;
516	    }
517	} else {
518	    die "Sphinx version should either major.minor or major.minor.patch format\n";
519	}
520    } else {
521	# Unknown argument
522        usage();
523    }
524}
525
526# continue execution near EOF;
527
528# The C domain dialect changed on Sphinx 3. So, we need to check the
529# version in order to produce the right tags.
530sub findprog($)
531{
532	foreach(split(/:/, $ENV{PATH})) {
533		return "$_/$_[0]" if(-x "$_/$_[0]");
534	}
535}
536
537sub get_sphinx_version()
538{
539	my $ver;
540
541	my $cmd = "sphinx-build";
542	if (!findprog($cmd)) {
543		my $cmd = "sphinx-build3";
544		if (!findprog($cmd)) {
545			$sphinx_major = 1;
546			$sphinx_minor = 2;
547			$sphinx_patch = 0;
548			printf STDERR "Warning: Sphinx version not found. Using default (Sphinx version %d.%d.%d)\n",
549			       $sphinx_major, $sphinx_minor, $sphinx_patch;
550			return;
551		}
552	}
553
554	open IN, "$cmd --version 2>&1 |";
555	while (<IN>) {
556		if (m/^\s*sphinx-build\s+([\d]+)\.([\d\.]+)(\+\/[\da-f]+)?$/) {
557			$sphinx_major = $1;
558			$sphinx_minor = $2;
559			$sphinx_patch = $3;
560			last;
561		}
562		# Sphinx 1.2.x uses a different format
563		if (m/^\s*Sphinx.*\s+([\d]+)\.([\d\.]+)$/) {
564			$sphinx_major = $1;
565			$sphinx_minor = $2;
566			$sphinx_patch = $3;
567			last;
568		}
569	}
570	close IN;
571}
572
573# get kernel version from env
574sub get_kernel_version() {
575    my $version = 'unknown kernel version';
576
577    if (defined($ENV{'KERNELVERSION'})) {
578	$version = $ENV{'KERNELVERSION'};
579    }
580    return $version;
581}
582
583#
584sub print_lineno {
585    my $lineno = shift;
586    if ($enable_lineno && defined($lineno)) {
587        print "#define LINENO " . $lineno . "\n";
588    }
589}
590##
591# dumps section contents to arrays/hashes intended for that purpose.
592#
593sub dump_section {
594    my $file = shift;
595    my $name = shift;
596    my $contents = join "\n", @_;
597
598    if ($name =~ m/$type_param/) {
599	$name = $1;
600	$parameterdescs{$name} = $contents;
601	$sectcheck = $sectcheck . $name . " ";
602        $parameterdesc_start_lines{$name} = $new_start_line;
603        $new_start_line = 0;
604    } elsif ($name eq "@\.\.\.") {
605	$name = "...";
606	$parameterdescs{$name} = $contents;
607	$sectcheck = $sectcheck . $name . " ";
608        $parameterdesc_start_lines{$name} = $new_start_line;
609        $new_start_line = 0;
610    } else {
611	if (defined($sections{$name}) && ($sections{$name} ne "")) {
612	    # Only warn on user specified duplicate section names.
613	    if ($name ne $section_default) {
614		print STDERR "${file}:$.: warning: duplicate section name '$name'\n";
615		++$warnings;
616	    }
617	    $sections{$name} .= $contents;
618	} else {
619	    $sections{$name} = $contents;
620	    push @sectionlist, $name;
621            $section_start_lines{$name} = $new_start_line;
622            $new_start_line = 0;
623	}
624    }
625}
626
627##
628# dump DOC: section after checking that it should go out
629#
630sub dump_doc_section {
631    my $file = shift;
632    my $name = shift;
633    my $contents = join "\n", @_;
634
635    if ($no_doc_sections) {
636        return;
637    }
638
639    return if (defined($nosymbol_table{$name}));
640
641    if (($output_selection == OUTPUT_ALL) ||
642	(($output_selection == OUTPUT_INCLUDE) &&
643	 defined($function_table{$name})))
644    {
645	dump_section($file, $name, $contents);
646	output_blockhead({'sectionlist' => \@sectionlist,
647			  'sections' => \%sections,
648			  'module' => $modulename,
649			  'content-only' => ($output_selection != OUTPUT_ALL), });
650    }
651}
652
653##
654# output function
655#
656# parameterdescs, a hash.
657#  function => "function name"
658#  parameterlist => @list of parameters
659#  parameterdescs => %parameter descriptions
660#  sectionlist => @list of sections
661#  sections => %section descriptions
662#
663
664sub output_highlight {
665    my $contents = join "\n",@_;
666    my $line;
667
668#   DEBUG
669#   if (!defined $contents) {
670#	use Carp;
671#	confess "output_highlight got called with no args?\n";
672#   }
673
674#   print STDERR "contents b4:$contents\n";
675    eval $dohighlight;
676    die $@ if $@;
677#   print STDERR "contents af:$contents\n";
678
679    foreach $line (split "\n", $contents) {
680	if (! $output_preformatted) {
681	    $line =~ s/^\s*//;
682	}
683	if ($line eq ""){
684	    if (! $output_preformatted) {
685		print $lineprefix, $blankline;
686	    }
687	} else {
688	    if ($output_mode eq "man" && substr($line, 0, 1) eq ".") {
689		print "\\&$line";
690	    } else {
691		print $lineprefix, $line;
692	    }
693	}
694	print "\n";
695    }
696}
697
698##
699# output function in man
700sub output_function_man(%) {
701    my %args = %{$_[0]};
702    my ($parameter, $section);
703    my $count;
704
705    print ".TH \"$args{'function'}\" 9 \"$args{'function'}\" \"$man_date\" \"Kernel Hacker's Manual\" LINUX\n";
706
707    print ".SH NAME\n";
708    print $args{'function'} . " \\- " . $args{'purpose'} . "\n";
709
710    print ".SH SYNOPSIS\n";
711    if ($args{'functiontype'} ne "") {
712	print ".B \"" . $args{'functiontype'} . "\" " . $args{'function'} . "\n";
713    } else {
714	print ".B \"" . $args{'function'} . "\n";
715    }
716    $count = 0;
717    my $parenth = "(";
718    my $post = ",";
719    foreach my $parameter (@{$args{'parameterlist'}}) {
720	if ($count == $#{$args{'parameterlist'}}) {
721	    $post = ");";
722	}
723	$type = $args{'parametertypes'}{$parameter};
724	if ($type =~ m/$function_pointer/) {
725	    # pointer-to-function
726	    print ".BI \"" . $parenth . $1 . "\" " . " \") (" . $2 . ")" . $post . "\"\n";
727	} else {
728	    $type =~ s/([^\*])$/$1 /;
729	    print ".BI \"" . $parenth . $type . "\" " . " \"" . $post . "\"\n";
730	}
731	$count++;
732	$parenth = "";
733    }
734
735    print ".SH ARGUMENTS\n";
736    foreach $parameter (@{$args{'parameterlist'}}) {
737	my $parameter_name = $parameter;
738	$parameter_name =~ s/\[.*//;
739
740	print ".IP \"" . $parameter . "\" 12\n";
741	output_highlight($args{'parameterdescs'}{$parameter_name});
742    }
743    foreach $section (@{$args{'sectionlist'}}) {
744	print ".SH \"", uc $section, "\"\n";
745	output_highlight($args{'sections'}{$section});
746    }
747}
748
749##
750# output enum in man
751sub output_enum_man(%) {
752    my %args = %{$_[0]};
753    my ($parameter, $section);
754    my $count;
755
756    print ".TH \"$args{'module'}\" 9 \"enum $args{'enum'}\" \"$man_date\" \"API Manual\" LINUX\n";
757
758    print ".SH NAME\n";
759    print "enum " . $args{'enum'} . " \\- " . $args{'purpose'} . "\n";
760
761    print ".SH SYNOPSIS\n";
762    print "enum " . $args{'enum'} . " {\n";
763    $count = 0;
764    foreach my $parameter (@{$args{'parameterlist'}}) {
765	print ".br\n.BI \"    $parameter\"\n";
766	if ($count == $#{$args{'parameterlist'}}) {
767	    print "\n};\n";
768	    last;
769	}
770	else {
771	    print ", \n.br\n";
772	}
773	$count++;
774    }
775
776    print ".SH Constants\n";
777    foreach $parameter (@{$args{'parameterlist'}}) {
778	my $parameter_name = $parameter;
779	$parameter_name =~ s/\[.*//;
780
781	print ".IP \"" . $parameter . "\" 12\n";
782	output_highlight($args{'parameterdescs'}{$parameter_name});
783    }
784    foreach $section (@{$args{'sectionlist'}}) {
785	print ".SH \"$section\"\n";
786	output_highlight($args{'sections'}{$section});
787    }
788}
789
790##
791# output struct in man
792sub output_struct_man(%) {
793    my %args = %{$_[0]};
794    my ($parameter, $section);
795
796    print ".TH \"$args{'module'}\" 9 \"" . $args{'type'} . " " . $args{'struct'} . "\" \"$man_date\" \"API Manual\" LINUX\n";
797
798    print ".SH NAME\n";
799    print $args{'type'} . " " . $args{'struct'} . " \\- " . $args{'purpose'} . "\n";
800
801    my $declaration = $args{'definition'};
802    $declaration =~ s/\t/  /g;
803    $declaration =~ s/\n/"\n.br\n.BI \"/g;
804    print ".SH SYNOPSIS\n";
805    print $args{'type'} . " " . $args{'struct'} . " {\n.br\n";
806    print ".BI \"$declaration\n};\n.br\n\n";
807
808    print ".SH Members\n";
809    foreach $parameter (@{$args{'parameterlist'}}) {
810	($parameter =~ /^#/) && next;
811
812	my $parameter_name = $parameter;
813	$parameter_name =~ s/\[.*//;
814
815	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
816	print ".IP \"" . $parameter . "\" 12\n";
817	output_highlight($args{'parameterdescs'}{$parameter_name});
818    }
819    foreach $section (@{$args{'sectionlist'}}) {
820	print ".SH \"$section\"\n";
821	output_highlight($args{'sections'}{$section});
822    }
823}
824
825##
826# output typedef in man
827sub output_typedef_man(%) {
828    my %args = %{$_[0]};
829    my ($parameter, $section);
830
831    print ".TH \"$args{'module'}\" 9 \"$args{'typedef'}\" \"$man_date\" \"API Manual\" LINUX\n";
832
833    print ".SH NAME\n";
834    print "typedef " . $args{'typedef'} . " \\- " . $args{'purpose'} . "\n";
835
836    foreach $section (@{$args{'sectionlist'}}) {
837	print ".SH \"$section\"\n";
838	output_highlight($args{'sections'}{$section});
839    }
840}
841
842sub output_blockhead_man(%) {
843    my %args = %{$_[0]};
844    my ($parameter, $section);
845    my $count;
846
847    print ".TH \"$args{'module'}\" 9 \"$args{'module'}\" \"$man_date\" \"API Manual\" LINUX\n";
848
849    foreach $section (@{$args{'sectionlist'}}) {
850	print ".SH \"$section\"\n";
851	output_highlight($args{'sections'}{$section});
852    }
853}
854
855##
856# output in restructured text
857#
858
859#
860# This could use some work; it's used to output the DOC: sections, and
861# starts by putting out the name of the doc section itself, but that tends
862# to duplicate a header already in the template file.
863#
864sub output_blockhead_rst(%) {
865    my %args = %{$_[0]};
866    my ($parameter, $section);
867
868    foreach $section (@{$args{'sectionlist'}}) {
869	next if (defined($nosymbol_table{$section}));
870
871	if ($output_selection != OUTPUT_INCLUDE) {
872	    print ".. _$section:\n\n";
873	    print "**$section**\n\n";
874	}
875        print_lineno($section_start_lines{$section});
876	output_highlight_rst($args{'sections'}{$section});
877	print "\n";
878    }
879}
880
881#
882# Apply the RST highlights to a sub-block of text.
883#
884sub highlight_block($) {
885    # The dohighlight kludge requires the text be called $contents
886    my $contents = shift;
887    eval $dohighlight;
888    die $@ if $@;
889    return $contents;
890}
891
892#
893# Regexes used only here.
894#
895my $sphinx_literal = '^[^.].*::$';
896my $sphinx_cblock = '^\.\.\ +code-block::';
897
898sub output_highlight_rst {
899    my $input = join "\n",@_;
900    my $output = "";
901    my $line;
902    my $in_literal = 0;
903    my $litprefix;
904    my $block = "";
905
906    foreach $line (split "\n",$input) {
907	#
908	# If we're in a literal block, see if we should drop out
909	# of it.  Otherwise pass the line straight through unmunged.
910	#
911	if ($in_literal) {
912	    if (! ($line =~ /^\s*$/)) {
913		#
914		# If this is the first non-blank line in a literal
915		# block we need to figure out what the proper indent is.
916		#
917		if ($litprefix eq "") {
918		    $line =~ /^(\s*)/;
919		    $litprefix = '^' . $1;
920		    $output .= $line . "\n";
921		} elsif (! ($line =~ /$litprefix/)) {
922		    $in_literal = 0;
923		} else {
924		    $output .= $line . "\n";
925		}
926	    } else {
927		$output .= $line . "\n";
928	    }
929	}
930	#
931	# Not in a literal block (or just dropped out)
932	#
933	if (! $in_literal) {
934	    $block .= $line . "\n";
935	    if (($line =~ /$sphinx_literal/) || ($line =~ /$sphinx_cblock/)) {
936		$in_literal = 1;
937		$litprefix = "";
938		$output .= highlight_block($block);
939		$block = ""
940	    }
941	}
942    }
943
944    if ($block) {
945	$output .= highlight_block($block);
946    }
947    foreach $line (split "\n", $output) {
948	print $lineprefix . $line . "\n";
949    }
950}
951
952sub output_function_rst(%) {
953    my %args = %{$_[0]};
954    my ($parameter, $section);
955    my $oldprefix = $lineprefix;
956    my $start = "";
957    my $is_macro = 0;
958
959    if ($sphinx_major < 3) {
960	if ($args{'typedef'}) {
961	    print ".. c:type:: ". $args{'function'} . "\n\n";
962	    print_lineno($declaration_start_line);
963	    print "   **Typedef**: ";
964	    $lineprefix = "";
965	    output_highlight_rst($args{'purpose'});
966	    $start = "\n\n**Syntax**\n\n  ``";
967	    $is_macro = 1;
968	} else {
969	    print ".. c:function:: ";
970	}
971    } else {
972	if ($args{'typedef'} || $args{'functiontype'} eq "") {
973	    $is_macro = 1;
974	    print ".. c:macro:: ". $args{'function'} . "\n\n";
975	} else {
976	    print ".. c:function:: ";
977	}
978
979	if ($args{'typedef'}) {
980	    print_lineno($declaration_start_line);
981	    print "   **Typedef**: ";
982	    $lineprefix = "";
983	    output_highlight_rst($args{'purpose'});
984	    $start = "\n\n**Syntax**\n\n  ``";
985	} else {
986	    print "``" if ($is_macro);
987	}
988    }
989    if ($args{'functiontype'} ne "") {
990	$start .= $args{'functiontype'} . " " . $args{'function'} . " (";
991    } else {
992	$start .= $args{'function'} . " (";
993    }
994    print $start;
995
996    my $count = 0;
997    foreach my $parameter (@{$args{'parameterlist'}}) {
998	if ($count ne 0) {
999	    print ", ";
1000	}
1001	$count++;
1002	$type = $args{'parametertypes'}{$parameter};
1003
1004	if ($type =~ m/$function_pointer/) {
1005	    # pointer-to-function
1006	    print $1 . $parameter . ") (" . $2 . ")";
1007	} else {
1008	    print $type;
1009	}
1010    }
1011    if ($is_macro) {
1012	print ")``\n\n";
1013    } else {
1014	print ")\n\n";
1015    }
1016    if (!$args{'typedef'}) {
1017	print_lineno($declaration_start_line);
1018	$lineprefix = "   ";
1019	output_highlight_rst($args{'purpose'});
1020	print "\n";
1021    }
1022
1023    print "**Parameters**\n\n";
1024    $lineprefix = "  ";
1025    foreach $parameter (@{$args{'parameterlist'}}) {
1026	my $parameter_name = $parameter;
1027	$parameter_name =~ s/\[.*//;
1028	$type = $args{'parametertypes'}{$parameter};
1029
1030	if ($type ne "") {
1031	    print "``$type``\n";
1032	} else {
1033	    print "``$parameter``\n";
1034	}
1035
1036        print_lineno($parameterdesc_start_lines{$parameter_name});
1037
1038	if (defined($args{'parameterdescs'}{$parameter_name}) &&
1039	    $args{'parameterdescs'}{$parameter_name} ne $undescribed) {
1040	    output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1041	} else {
1042	    print "  *undescribed*\n";
1043	}
1044	print "\n";
1045    }
1046
1047    $lineprefix = $oldprefix;
1048    output_section_rst(@_);
1049}
1050
1051sub output_section_rst(%) {
1052    my %args = %{$_[0]};
1053    my $section;
1054    my $oldprefix = $lineprefix;
1055    $lineprefix = "";
1056
1057    foreach $section (@{$args{'sectionlist'}}) {
1058	print "**$section**\n\n";
1059        print_lineno($section_start_lines{$section});
1060	output_highlight_rst($args{'sections'}{$section});
1061	print "\n";
1062    }
1063    print "\n";
1064    $lineprefix = $oldprefix;
1065}
1066
1067sub output_enum_rst(%) {
1068    my %args = %{$_[0]};
1069    my ($parameter);
1070    my $oldprefix = $lineprefix;
1071    my $count;
1072
1073    if ($sphinx_major < 3) {
1074	my $name = "enum " . $args{'enum'};
1075	print "\n\n.. c:type:: " . $name . "\n\n";
1076    } else {
1077	my $name = $args{'enum'};
1078	print "\n\n.. c:enum:: " . $name . "\n\n";
1079    }
1080    print_lineno($declaration_start_line);
1081    $lineprefix = "   ";
1082    output_highlight_rst($args{'purpose'});
1083    print "\n";
1084
1085    print "**Constants**\n\n";
1086    $lineprefix = "  ";
1087    foreach $parameter (@{$args{'parameterlist'}}) {
1088	print "``$parameter``\n";
1089	if ($args{'parameterdescs'}{$parameter} ne $undescribed) {
1090	    output_highlight_rst($args{'parameterdescs'}{$parameter});
1091	} else {
1092	    print "  *undescribed*\n";
1093	}
1094	print "\n";
1095    }
1096
1097    $lineprefix = $oldprefix;
1098    output_section_rst(@_);
1099}
1100
1101sub output_typedef_rst(%) {
1102    my %args = %{$_[0]};
1103    my ($parameter);
1104    my $oldprefix = $lineprefix;
1105    my $name;
1106
1107    if ($sphinx_major < 3) {
1108	$name = "typedef " . $args{'typedef'};
1109    } else {
1110	$name = $args{'typedef'};
1111    }
1112    print "\n\n.. c:type:: " . $name . "\n\n";
1113    print_lineno($declaration_start_line);
1114    $lineprefix = "   ";
1115    output_highlight_rst($args{'purpose'});
1116    print "\n";
1117
1118    $lineprefix = $oldprefix;
1119    output_section_rst(@_);
1120}
1121
1122sub output_struct_rst(%) {
1123    my %args = %{$_[0]};
1124    my ($parameter);
1125    my $oldprefix = $lineprefix;
1126
1127    if ($sphinx_major < 3) {
1128	my $name = $args{'type'} . " " . $args{'struct'};
1129	print "\n\n.. c:type:: " . $name . "\n\n";
1130    } else {
1131	my $name = $args{'struct'};
1132	if ($args{'type'} eq 'union') {
1133	    print "\n\n.. c:union:: " . $name . "\n\n";
1134	} else {
1135	    print "\n\n.. c:struct:: " . $name . "\n\n";
1136	}
1137    }
1138    print_lineno($declaration_start_line);
1139    $lineprefix = "   ";
1140    output_highlight_rst($args{'purpose'});
1141    print "\n";
1142
1143    print "**Definition**\n\n";
1144    print "::\n\n";
1145    my $declaration = $args{'definition'};
1146    $declaration =~ s/\t/  /g;
1147    print "  " . $args{'type'} . " " . $args{'struct'} . " {\n$declaration  };\n\n";
1148
1149    print "**Members**\n\n";
1150    $lineprefix = "  ";
1151    foreach $parameter (@{$args{'parameterlist'}}) {
1152	($parameter =~ /^#/) && next;
1153
1154	my $parameter_name = $parameter;
1155	$parameter_name =~ s/\[.*//;
1156
1157	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
1158	$type = $args{'parametertypes'}{$parameter};
1159        print_lineno($parameterdesc_start_lines{$parameter_name});
1160	print "``" . $parameter . "``\n";
1161	output_highlight_rst($args{'parameterdescs'}{$parameter_name});
1162	print "\n";
1163    }
1164    print "\n";
1165
1166    $lineprefix = $oldprefix;
1167    output_section_rst(@_);
1168}
1169
1170## none mode output functions
1171
1172sub output_function_none(%) {
1173}
1174
1175sub output_enum_none(%) {
1176}
1177
1178sub output_typedef_none(%) {
1179}
1180
1181sub output_struct_none(%) {
1182}
1183
1184sub output_blockhead_none(%) {
1185}
1186
1187##
1188# generic output function for all types (function, struct/union, typedef, enum);
1189# calls the generated, variable output_ function name based on
1190# functype and output_mode
1191sub output_declaration {
1192    no strict 'refs';
1193    my $name = shift;
1194    my $functype = shift;
1195    my $func = "output_${functype}_$output_mode";
1196
1197    return if (defined($nosymbol_table{$name}));
1198
1199    if (($output_selection == OUTPUT_ALL) ||
1200	(($output_selection == OUTPUT_INCLUDE ||
1201	  $output_selection == OUTPUT_EXPORTED) &&
1202	 defined($function_table{$name})) ||
1203	($output_selection == OUTPUT_INTERNAL &&
1204	 !($functype eq "function" && defined($function_table{$name}))))
1205    {
1206	&$func(@_);
1207	$section_counter++;
1208    }
1209}
1210
1211##
1212# generic output function - calls the right one based on current output mode.
1213sub output_blockhead {
1214    no strict 'refs';
1215    my $func = "output_blockhead_" . $output_mode;
1216    &$func(@_);
1217    $section_counter++;
1218}
1219
1220##
1221# takes a declaration (struct, union, enum, typedef) and
1222# invokes the right handler. NOT called for functions.
1223sub dump_declaration($$) {
1224    no strict 'refs';
1225    my ($prototype, $file) = @_;
1226    my $func = "dump_" . $decl_type;
1227    &$func(@_);
1228}
1229
1230sub dump_union($$) {
1231    dump_struct(@_);
1232}
1233
1234sub dump_struct($$) {
1235    my $x = shift;
1236    my $file = shift;
1237    my $decl_type;
1238    my $members;
1239    my $type = qr{struct|union};
1240    # For capturing struct/union definition body, i.e. "{members*}qualifiers*"
1241    my $qualifiers = qr{$attribute|__packed|__aligned|____cacheline_aligned_in_smp|____cacheline_aligned};
1242    my $definition_body = qr{\{(.*)\}\s*$qualifiers*};
1243    my $struct_members = qr{($type)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;};
1244
1245    if ($x =~ /($type)\s+(\w+)\s*$definition_body/) {
1246	$decl_type = $1;
1247	$declaration_name = $2;
1248	$members = $3;
1249    } elsif ($x =~ /typedef\s+($type)\s*$definition_body\s*(\w+)\s*;/) {
1250	$decl_type = $1;
1251	$declaration_name = $3;
1252	$members = $2;
1253    }
1254
1255    if ($members) {
1256	if ($identifier ne $declaration_name) {
1257	    print STDERR "${file}:$.: warning: expecting prototype for $decl_type $identifier. Prototype was for $decl_type $declaration_name instead\n";
1258	    return;
1259	}
1260
1261	# ignore members marked private:
1262	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gosi;
1263	$members =~ s/\/\*\s*private:.*//gosi;
1264	# strip comments:
1265	$members =~ s/\/\*.*?\*\///gos;
1266	# strip attributes
1267	$members =~ s/\s*$attribute/ /gi;
1268	$members =~ s/\s*__aligned\s*\([^;]*\)/ /gos;
1269	$members =~ s/\s*__packed\s*/ /gos;
1270	$members =~ s/\s*CRYPTO_MINALIGN_ATTR/ /gos;
1271	$members =~ s/\s*____cacheline_aligned_in_smp/ /gos;
1272	$members =~ s/\s*____cacheline_aligned/ /gos;
1273	# unwrap struct_group():
1274	# - first eat non-declaration parameters and rewrite for final match
1275	# - then remove macro, outer parens, and trailing semicolon
1276	$members =~ s/\bstruct_group\s*\(([^,]*,)/STRUCT_GROUP(/gos;
1277	$members =~ s/\bstruct_group_(attr|tagged)\s*\(([^,]*,){2}/STRUCT_GROUP(/gos;
1278	$members =~ s/\b__struct_group\s*\(([^,]*,){3}/STRUCT_GROUP(/gos;
1279	$members =~ s/\bSTRUCT_GROUP(\(((?:(?>[^)(]+)|(?1))*)\))[^;]*;/$2/gos;
1280
1281	my $args = qr{([^,)]+)};
1282	# replace DECLARE_BITMAP
1283	$members =~ s/__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, __ETHTOOL_LINK_MODE_MASK_NBITS)/gos;
1284	$members =~ s/DECLARE_PHY_INTERFACE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, PHY_INTERFACE_MODE_MAX)/gos;
1285	$members =~ s/DECLARE_BITMAP\s*\($args,\s*$args\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1286	# replace DECLARE_HASHTABLE
1287	$members =~ s/DECLARE_HASHTABLE\s*\($args,\s*$args\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1288	# replace DECLARE_KFIFO
1289	$members =~ s/DECLARE_KFIFO\s*\($args,\s*$args,\s*$args\)/$2 \*$1/gos;
1290	# replace DECLARE_KFIFO_PTR
1291	$members =~ s/DECLARE_KFIFO_PTR\s*\($args,\s*$args\)/$2 \*$1/gos;
1292	# replace DECLARE_FLEX_ARRAY
1293	$members =~ s/(?:__)?DECLARE_FLEX_ARRAY\s*\($args,\s*$args\)/$1 $2\[\]/gos;
1294	my $declaration = $members;
1295
1296	# Split nested struct/union elements as newer ones
1297	while ($members =~ m/$struct_members/) {
1298		my $newmember;
1299		my $maintype = $1;
1300		my $ids = $4;
1301		my $content = $3;
1302		foreach my $id(split /,/, $ids) {
1303			$newmember .= "$maintype $id; ";
1304
1305			$id =~ s/[:\[].*//;
1306			$id =~ s/^\s*\**(\S+)\s*/$1/;
1307			foreach my $arg (split /;/, $content) {
1308				next if ($arg =~ m/^\s*$/);
1309				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1310					# pointer-to-function
1311					my $type = $1;
1312					my $name = $2;
1313					my $extra = $3;
1314					next if (!$name);
1315					if ($id =~ m/^\s*$/) {
1316						# anonymous struct/union
1317						$newmember .= "$type$name$extra; ";
1318					} else {
1319						$newmember .= "$type$id.$name$extra; ";
1320					}
1321				} else {
1322					my $type;
1323					my $names;
1324					$arg =~ s/^\s+//;
1325					$arg =~ s/\s+$//;
1326					# Handle bitmaps
1327					$arg =~ s/:\s*\d+\s*//g;
1328					# Handle arrays
1329					$arg =~ s/\[.*\]//g;
1330					# The type may have multiple words,
1331					# and multiple IDs can be defined, like:
1332					#	const struct foo, *bar, foobar
1333					# So, we remove spaces when parsing the
1334					# names, in order to match just names
1335					# and commas for the names
1336					$arg =~ s/\s*,\s*/,/g;
1337					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1338						$type = $1;
1339						$names = $2;
1340					} else {
1341						$newmember .= "$arg; ";
1342						next;
1343					}
1344					foreach my $name (split /,/, $names) {
1345						$name =~ s/^\s*\**(\S+)\s*/$1/;
1346						next if (($name =~ m/^\s*$/));
1347						if ($id =~ m/^\s*$/) {
1348							# anonymous struct/union
1349							$newmember .= "$type $name; ";
1350						} else {
1351							$newmember .= "$type $id.$name; ";
1352						}
1353					}
1354				}
1355			}
1356		}
1357		$members =~ s/$struct_members/$newmember/;
1358	}
1359
1360	# Ignore other nested elements, like enums
1361	$members =~ s/(\{[^\{\}]*\})//g;
1362
1363	create_parameterlist($members, ';', $file, $declaration_name);
1364	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1365
1366	# Adjust declaration for better display
1367	$declaration =~ s/([\{;])/$1\n/g;
1368	$declaration =~ s/\}\s+;/};/g;
1369	# Better handle inlined enums
1370	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1371
1372	my @def_args = split /\n/, $declaration;
1373	my $level = 1;
1374	$declaration = "";
1375	foreach my $clause (@def_args) {
1376		$clause =~ s/^\s+//;
1377		$clause =~ s/\s+$//;
1378		$clause =~ s/\s+/ /;
1379		next if (!$clause);
1380		$level-- if ($clause =~ m/(\})/ && $level > 1);
1381		if (!($clause =~ m/^\s*#/)) {
1382			$declaration .= "\t" x $level;
1383		}
1384		$declaration .= "\t" . $clause . "\n";
1385		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1386	}
1387	output_declaration($declaration_name,
1388			   'struct',
1389			   {'struct' => $declaration_name,
1390			    'module' => $modulename,
1391			    'definition' => $declaration,
1392			    'parameterlist' => \@parameterlist,
1393			    'parameterdescs' => \%parameterdescs,
1394			    'parametertypes' => \%parametertypes,
1395			    'sectionlist' => \@sectionlist,
1396			    'sections' => \%sections,
1397			    'purpose' => $declaration_purpose,
1398			    'type' => $decl_type
1399			   });
1400    }
1401    else {
1402	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1403	++$errors;
1404    }
1405}
1406
1407
1408sub show_warnings($$) {
1409	my $functype = shift;
1410	my $name = shift;
1411
1412	return 0 if (defined($nosymbol_table{$name}));
1413
1414	return 1 if ($output_selection == OUTPUT_ALL);
1415
1416	if ($output_selection == OUTPUT_EXPORTED) {
1417		if (defined($function_table{$name})) {
1418			return 1;
1419		} else {
1420			return 0;
1421		}
1422	}
1423        if ($output_selection == OUTPUT_INTERNAL) {
1424		if (!($functype eq "function" && defined($function_table{$name}))) {
1425			return 1;
1426		} else {
1427			return 0;
1428		}
1429	}
1430	if ($output_selection == OUTPUT_INCLUDE) {
1431		if (defined($function_table{$name})) {
1432			return 1;
1433		} else {
1434			return 0;
1435		}
1436	}
1437	die("Please add the new output type at show_warnings()");
1438}
1439
1440sub dump_enum($$) {
1441    my $x = shift;
1442    my $file = shift;
1443    my $members;
1444
1445
1446    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1447    # strip #define macros inside enums
1448    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1449
1450    if ($x =~ /typedef\s+enum\s*\{(.*)\}\s*(\w*)\s*;/) {
1451	$declaration_name = $2;
1452	$members = $1;
1453    } elsif ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1454	$declaration_name = $1;
1455	$members = $2;
1456    }
1457
1458    if ($members) {
1459	if ($identifier ne $declaration_name) {
1460	    if ($identifier eq "") {
1461		print STDERR "${file}:$.: warning: wrong kernel-doc identifier on line:\n";
1462	    } else {
1463		print STDERR "${file}:$.: warning: expecting prototype for enum $identifier. Prototype was for enum $declaration_name instead\n";
1464	    }
1465	    return;
1466	}
1467	$declaration_name = "(anonymous)" if ($declaration_name eq "");
1468
1469	my %_members;
1470
1471	$members =~ s/\s+$//;
1472
1473	foreach my $arg (split ',', $members) {
1474	    $arg =~ s/^\s*(\w+).*/$1/;
1475	    push @parameterlist, $arg;
1476	    if (!$parameterdescs{$arg}) {
1477		$parameterdescs{$arg} = $undescribed;
1478	        if (show_warnings("enum", $declaration_name)) {
1479			print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1480		}
1481	    }
1482	    $_members{$arg} = 1;
1483	}
1484
1485	while (my ($k, $v) = each %parameterdescs) {
1486	    if (!exists($_members{$k})) {
1487	        if (show_warnings("enum", $declaration_name)) {
1488		     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1489		}
1490	    }
1491        }
1492
1493	output_declaration($declaration_name,
1494			   'enum',
1495			   {'enum' => $declaration_name,
1496			    'module' => $modulename,
1497			    'parameterlist' => \@parameterlist,
1498			    'parameterdescs' => \%parameterdescs,
1499			    'sectionlist' => \@sectionlist,
1500			    'sections' => \%sections,
1501			    'purpose' => $declaration_purpose
1502			   });
1503    } else {
1504	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1505	++$errors;
1506    }
1507}
1508
1509my $typedef_type = qr { ((?:\s+[\w\*]+\b){1,8})\s* }x;
1510my $typedef_ident = qr { \*?\s*(\w\S+)\s* }x;
1511my $typedef_args = qr { \s*\((.*)\); }x;
1512
1513my $typedef1 = qr { typedef$typedef_type\($typedef_ident\)$typedef_args }x;
1514my $typedef2 = qr { typedef$typedef_type$typedef_ident$typedef_args }x;
1515
1516sub dump_typedef($$) {
1517    my $x = shift;
1518    my $file = shift;
1519
1520    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1521
1522    # Parse function typedef prototypes
1523    if ($x =~ $typedef1 || $x =~ $typedef2) {
1524	$return_type = $1;
1525	$declaration_name = $2;
1526	my $args = $3;
1527	$return_type =~ s/^\s+//;
1528
1529	if ($identifier ne $declaration_name) {
1530	    print STDERR "${file}:$.: warning: expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n";
1531	    return;
1532	}
1533
1534	create_parameterlist($args, ',', $file, $declaration_name);
1535
1536	output_declaration($declaration_name,
1537			   'function',
1538			   {'function' => $declaration_name,
1539			    'typedef' => 1,
1540			    'module' => $modulename,
1541			    'functiontype' => $return_type,
1542			    'parameterlist' => \@parameterlist,
1543			    'parameterdescs' => \%parameterdescs,
1544			    'parametertypes' => \%parametertypes,
1545			    'sectionlist' => \@sectionlist,
1546			    'sections' => \%sections,
1547			    'purpose' => $declaration_purpose
1548			   });
1549	return;
1550    }
1551
1552    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1553	$x =~ s/\(*.\)\s*;$/;/;
1554	$x =~ s/\[*.\]\s*;$/;/;
1555    }
1556
1557    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1558	$declaration_name = $1;
1559
1560	if ($identifier ne $declaration_name) {
1561	    print STDERR "${file}:$.: warning: expecting prototype for typedef $identifier. Prototype was for typedef $declaration_name instead\n";
1562	    return;
1563	}
1564
1565	output_declaration($declaration_name,
1566			   'typedef',
1567			   {'typedef' => $declaration_name,
1568			    'module' => $modulename,
1569			    'sectionlist' => \@sectionlist,
1570			    'sections' => \%sections,
1571			    'purpose' => $declaration_purpose
1572			   });
1573    }
1574    else {
1575	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1576	++$errors;
1577    }
1578}
1579
1580sub save_struct_actual($) {
1581    my $actual = shift;
1582
1583    # strip all spaces from the actual param so that it looks like one string item
1584    $actual =~ s/\s*//g;
1585    $struct_actual = $struct_actual . $actual . " ";
1586}
1587
1588sub create_parameterlist($$$$) {
1589    my $args = shift;
1590    my $splitter = shift;
1591    my $file = shift;
1592    my $declaration_name = shift;
1593    my $type;
1594    my $param;
1595
1596    # temporarily replace commas inside function pointer definition
1597    my $arg_expr = qr{\([^\),]+};
1598    while ($args =~ /$arg_expr,/) {
1599	$args =~ s/($arg_expr),/$1#/g;
1600    }
1601
1602    foreach my $arg (split($splitter, $args)) {
1603	# strip comments
1604	$arg =~ s/\/\*.*\*\///;
1605	# strip leading/trailing spaces
1606	$arg =~ s/^\s*//;
1607	$arg =~ s/\s*$//;
1608	$arg =~ s/\s+/ /;
1609
1610	if ($arg =~ /^#/) {
1611	    # Treat preprocessor directive as a typeless variable just to fill
1612	    # corresponding data structures "correctly". Catch it later in
1613	    # output_* subs.
1614	    push_parameter($arg, "", "", $file);
1615	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1616	    # pointer-to-function
1617	    $arg =~ tr/#/,/;
1618	    $arg =~ m/[^\(]+\(\*?\s*([\w\[\]\.]*)\s*\)/;
1619	    $param = $1;
1620	    $type = $arg;
1621	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1622	    save_struct_actual($param);
1623	    push_parameter($param, $type, $arg, $file, $declaration_name);
1624	} elsif ($arg) {
1625	    $arg =~ s/\s*:\s*/:/g;
1626	    $arg =~ s/\s*\[/\[/g;
1627
1628	    my @args = split('\s*,\s*', $arg);
1629	    if ($args[0] =~ m/\*/) {
1630		$args[0] =~ s/(\*+)\s*/ $1/;
1631	    }
1632
1633	    my @first_arg;
1634	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1635		    shift @args;
1636		    push(@first_arg, split('\s+', $1));
1637		    push(@first_arg, $2);
1638	    } else {
1639		    @first_arg = split('\s+', shift @args);
1640	    }
1641
1642	    unshift(@args, pop @first_arg);
1643	    $type = join " ", @first_arg;
1644
1645	    foreach $param (@args) {
1646		if ($param =~ m/^(\*+)\s*(.*)/) {
1647		    save_struct_actual($2);
1648
1649		    push_parameter($2, "$type $1", $arg, $file, $declaration_name);
1650		}
1651		elsif ($param =~ m/(.*?):(\d+)/) {
1652		    if ($type ne "") { # skip unnamed bit-fields
1653			save_struct_actual($1);
1654			push_parameter($1, "$type:$2", $arg, $file, $declaration_name)
1655		    }
1656		}
1657		else {
1658		    save_struct_actual($param);
1659		    push_parameter($param, $type, $arg, $file, $declaration_name);
1660		}
1661	    }
1662	}
1663    }
1664}
1665
1666sub push_parameter($$$$$) {
1667	my $param = shift;
1668	my $type = shift;
1669	my $org_arg = shift;
1670	my $file = shift;
1671	my $declaration_name = shift;
1672
1673	if (($anon_struct_union == 1) && ($type eq "") &&
1674	    ($param eq "}")) {
1675		return;		# ignore the ending }; from anon. struct/union
1676	}
1677
1678	$anon_struct_union = 0;
1679	$param =~ s/[\[\)].*//;
1680
1681	if ($type eq "" && $param =~ /\.\.\.$/)
1682	{
1683	    if (!$param =~ /\w\.\.\.$/) {
1684	      # handles unnamed variable parameters
1685	      $param = "...";
1686	    }
1687	    elsif ($param =~ /\w\.\.\.$/) {
1688	      # for named variable parameters of the form `x...`, remove the dots
1689	      $param =~ s/\.\.\.$//;
1690	    }
1691	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1692		$parameterdescs{$param} = "variable arguments";
1693	    }
1694	}
1695	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1696	{
1697	    $param="void";
1698	    $parameterdescs{void} = "no arguments";
1699	}
1700	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1701	# handle unnamed (anonymous) union or struct:
1702	{
1703		$type = $param;
1704		$param = "{unnamed_" . $param . "}";
1705		$parameterdescs{$param} = "anonymous\n";
1706		$anon_struct_union = 1;
1707	}
1708
1709	# warn if parameter has no description
1710	# (but ignore ones starting with # as these are not parameters
1711	# but inline preprocessor statements);
1712	# Note: It will also ignore void params and unnamed structs/unions
1713	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1714		$parameterdescs{$param} = $undescribed;
1715
1716	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1717			print STDERR
1718			      "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1719			++$warnings;
1720		}
1721	}
1722
1723	# strip spaces from $param so that it is one continuous string
1724	# on @parameterlist;
1725	# this fixes a problem where check_sections() cannot find
1726	# a parameter like "addr[6 + 2]" because it actually appears
1727	# as "addr[6", "+", "2]" on the parameter list;
1728	# but it's better to maintain the param string unchanged for output,
1729	# so just weaken the string compare in check_sections() to ignore
1730	# "[blah" in a parameter string;
1731	###$param =~ s/\s*//g;
1732	push @parameterlist, $param;
1733	$org_arg =~ s/\s\s+/ /g;
1734	$parametertypes{$param} = $org_arg;
1735}
1736
1737sub check_sections($$$$$) {
1738	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1739	my @sects = split ' ', $sectcheck;
1740	my @prms = split ' ', $prmscheck;
1741	my $err;
1742	my ($px, $sx);
1743	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1744
1745	foreach $sx (0 .. $#sects) {
1746		$err = 1;
1747		foreach $px (0 .. $#prms) {
1748			$prm_clean = $prms[$px];
1749			$prm_clean =~ s/\[.*\]//;
1750			$prm_clean =~ s/$attribute//i;
1751			# ignore array size in a parameter string;
1752			# however, the original param string may contain
1753			# spaces, e.g.:  addr[6 + 2]
1754			# and this appears in @prms as "addr[6" since the
1755			# parameter list is split at spaces;
1756			# hence just ignore "[..." for the sections check;
1757			$prm_clean =~ s/\[.*//;
1758
1759			##$prm_clean =~ s/^\**//;
1760			if ($prm_clean eq $sects[$sx]) {
1761				$err = 0;
1762				last;
1763			}
1764		}
1765		if ($err) {
1766			if ($decl_type eq "function") {
1767				print STDERR "${file}:$.: warning: " .
1768					"Excess function parameter " .
1769					"'$sects[$sx]' " .
1770					"description in '$decl_name'\n";
1771				++$warnings;
1772			}
1773		}
1774	}
1775}
1776
1777##
1778# Checks the section describing the return value of a function.
1779sub check_return_section {
1780        my $file = shift;
1781        my $declaration_name = shift;
1782        my $return_type = shift;
1783
1784        # Ignore an empty return type (It's a macro)
1785        # Ignore functions with a "void" return type. (But don't ignore "void *")
1786        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1787                return;
1788        }
1789
1790        if (!defined($sections{$section_return}) ||
1791            $sections{$section_return} eq "") {
1792                print STDERR "${file}:$.: warning: " .
1793                        "No description found for return value of " .
1794                        "'$declaration_name'\n";
1795                ++$warnings;
1796        }
1797}
1798
1799##
1800# takes a function prototype and the name of the current file being
1801# processed and spits out all the details stored in the global
1802# arrays/hashes.
1803sub dump_function($$) {
1804    my $prototype = shift;
1805    my $file = shift;
1806    my $noret = 0;
1807
1808    print_lineno($new_start_line);
1809
1810    $prototype =~ s/^static +//;
1811    $prototype =~ s/^extern +//;
1812    $prototype =~ s/^asmlinkage +//;
1813    $prototype =~ s/^inline +//;
1814    $prototype =~ s/^__inline__ +//;
1815    $prototype =~ s/^__inline +//;
1816    $prototype =~ s/^__always_inline +//;
1817    $prototype =~ s/^noinline +//;
1818    $prototype =~ s/__init +//;
1819    $prototype =~ s/__init_or_module +//;
1820    $prototype =~ s/__deprecated +//;
1821    $prototype =~ s/__flatten +//;
1822    $prototype =~ s/__meminit +//;
1823    $prototype =~ s/__must_check +//;
1824    $prototype =~ s/__weak +//;
1825    $prototype =~ s/__sched +//;
1826    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1827    $prototype =~ s/__alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\) +//;
1828    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1829    $prototype =~ s/__attribute_const__ +//;
1830    $prototype =~ s/__attribute__\s*\(\(
1831            (?:
1832                 [\w\s]++          # attribute name
1833                 (?:\([^)]*+\))?   # attribute arguments
1834                 \s*+,?            # optional comma at the end
1835            )+
1836          \)\)\s+//x;
1837
1838    # Yes, this truly is vile.  We are looking for:
1839    # 1. Return type (may be nothing if we're looking at a macro)
1840    # 2. Function name
1841    # 3. Function parameters.
1842    #
1843    # All the while we have to watch out for function pointer parameters
1844    # (which IIRC is what the two sections are for), C types (these
1845    # regexps don't even start to express all the possibilities), and
1846    # so on.
1847    #
1848    # If you mess with these regexps, it's a good idea to check that
1849    # the following functions' documentation still comes out right:
1850    # - parport_register_device (function pointer parameters)
1851    # - atomic_set (macro)
1852    # - pci_match_device, __copy_to_user (long return type)
1853    my $name = qr{[a-zA-Z0-9_~:]+};
1854    my $prototype_end1 = qr{[^\(]*};
1855    my $prototype_end2 = qr{[^\{]*};
1856    my $prototype_end = qr{\(($prototype_end1|$prototype_end2)\)};
1857    my $type1 = qr{[\w\s]+};
1858    my $type2 = qr{$type1\*+};
1859
1860    if ($define && $prototype =~ m/^()($name)\s+/) {
1861        # This is an object-like macro, it has no return type and no parameter
1862        # list.
1863        # Function-like macros are not allowed to have spaces between
1864        # declaration_name and opening parenthesis (notice the \s+).
1865        $return_type = $1;
1866        $declaration_name = $2;
1867        $noret = 1;
1868    } elsif ($prototype =~ m/^()($name)\s*$prototype_end/ ||
1869	$prototype =~ m/^($type1)\s+($name)\s*$prototype_end/ ||
1870	$prototype =~ m/^($type2+)\s*($name)\s*$prototype_end/)  {
1871	$return_type = $1;
1872	$declaration_name = $2;
1873	my $args = $3;
1874
1875	create_parameterlist($args, ',', $file, $declaration_name);
1876    } else {
1877	print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1878	return;
1879    }
1880
1881    if ($identifier ne $declaration_name) {
1882	print STDERR "${file}:$.: warning: expecting prototype for $identifier(). Prototype was for $declaration_name() instead\n";
1883	return;
1884    }
1885
1886    my $prms = join " ", @parameterlist;
1887    check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1888
1889    # This check emits a lot of warnings at the moment, because many
1890    # functions don't have a 'Return' doc section. So until the number
1891    # of warnings goes sufficiently down, the check is only performed in
1892    # verbose mode.
1893    # TODO: always perform the check.
1894    if ($verbose && !$noret) {
1895	    check_return_section($file, $declaration_name, $return_type);
1896    }
1897
1898    # The function parser can be called with a typedef parameter.
1899    # Handle it.
1900    if ($return_type =~ /typedef/) {
1901	output_declaration($declaration_name,
1902			   'function',
1903			   {'function' => $declaration_name,
1904			    'typedef' => 1,
1905			    'module' => $modulename,
1906			    'functiontype' => $return_type,
1907			    'parameterlist' => \@parameterlist,
1908			    'parameterdescs' => \%parameterdescs,
1909			    'parametertypes' => \%parametertypes,
1910			    'sectionlist' => \@sectionlist,
1911			    'sections' => \%sections,
1912			    'purpose' => $declaration_purpose
1913			   });
1914    } else {
1915	output_declaration($declaration_name,
1916			   'function',
1917			   {'function' => $declaration_name,
1918			    'module' => $modulename,
1919			    'functiontype' => $return_type,
1920			    'parameterlist' => \@parameterlist,
1921			    'parameterdescs' => \%parameterdescs,
1922			    'parametertypes' => \%parametertypes,
1923			    'sectionlist' => \@sectionlist,
1924			    'sections' => \%sections,
1925			    'purpose' => $declaration_purpose
1926			   });
1927    }
1928}
1929
1930sub reset_state {
1931    $function = "";
1932    %parameterdescs = ();
1933    %parametertypes = ();
1934    @parameterlist = ();
1935    %sections = ();
1936    @sectionlist = ();
1937    $sectcheck = "";
1938    $struct_actual = "";
1939    $prototype = "";
1940
1941    $state = STATE_NORMAL;
1942    $inline_doc_state = STATE_INLINE_NA;
1943}
1944
1945sub tracepoint_munge($) {
1946	my $file = shift;
1947	my $tracepointname = 0;
1948	my $tracepointargs = 0;
1949
1950	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1951		$tracepointname = $1;
1952	}
1953	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1954		$tracepointname = $1;
1955	}
1956	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1957		$tracepointname = $2;
1958	}
1959	$tracepointname =~ s/^\s+//; #strip leading whitespace
1960	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1961		$tracepointargs = $1;
1962	}
1963	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1964		print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1965			     "$prototype\n";
1966	} else {
1967		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1968		$identifier = "trace_$identifier";
1969	}
1970}
1971
1972sub syscall_munge() {
1973	my $void = 0;
1974
1975	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1976##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1977	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1978		$void = 1;
1979##		$prototype = "long sys_$1(void)";
1980	}
1981
1982	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1983	if ($prototype =~ m/long (sys_.*?),/) {
1984		$prototype =~ s/,/\(/;
1985	} elsif ($void) {
1986		$prototype =~ s/\)/\(void\)/;
1987	}
1988
1989	# now delete all of the odd-number commas in $prototype
1990	# so that arg types & arg names don't have a comma between them
1991	my $count = 0;
1992	my $len = length($prototype);
1993	if ($void) {
1994		$len = 0;	# skip the for-loop
1995	}
1996	for (my $ix = 0; $ix < $len; $ix++) {
1997		if (substr($prototype, $ix, 1) eq ',') {
1998			$count++;
1999			if ($count % 2 == 1) {
2000				substr($prototype, $ix, 1) = ' ';
2001			}
2002		}
2003	}
2004}
2005
2006sub process_proto_function($$) {
2007    my $x = shift;
2008    my $file = shift;
2009
2010    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
2011
2012    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
2013	# do nothing
2014    }
2015    elsif ($x =~ /([^\{]*)/) {
2016	$prototype .= $1;
2017    }
2018
2019    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
2020	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
2021	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
2022	$prototype =~ s@^\s+@@gos; # strip leading spaces
2023
2024	 # Handle prototypes for function pointers like:
2025	 # int (*pcs_config)(struct foo)
2026	$prototype =~ s@^(\S+\s+)\(\s*\*(\S+)\)@$1$2@gos;
2027
2028	if ($prototype =~ /SYSCALL_DEFINE/) {
2029		syscall_munge();
2030	}
2031	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
2032	    $prototype =~ /DEFINE_SINGLE_EVENT/)
2033	{
2034		tracepoint_munge($file);
2035	}
2036	dump_function($prototype, $file);
2037	reset_state();
2038    }
2039}
2040
2041sub process_proto_type($$) {
2042    my $x = shift;
2043    my $file = shift;
2044
2045    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
2046    $x =~ s@^\s+@@gos; # strip leading spaces
2047    $x =~ s@\s+$@@gos; # strip trailing spaces
2048    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
2049
2050    if ($x =~ /^#/) {
2051	# To distinguish preprocessor directive from regular declaration later.
2052	$x .= ";";
2053    }
2054
2055    while (1) {
2056	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
2057            if( length $prototype ) {
2058                $prototype .= " "
2059            }
2060	    $prototype .= $1 . $2;
2061	    ($2 eq '{') && $brcount++;
2062	    ($2 eq '}') && $brcount--;
2063	    if (($2 eq ';') && ($brcount == 0)) {
2064		dump_declaration($prototype, $file);
2065		reset_state();
2066		last;
2067	    }
2068	    $x = $3;
2069	} else {
2070	    $prototype .= $x;
2071	    last;
2072	}
2073    }
2074}
2075
2076
2077sub map_filename($) {
2078    my $file;
2079    my ($orig_file) = @_;
2080
2081    if (defined($ENV{'SRCTREE'})) {
2082	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
2083    } else {
2084	$file = $orig_file;
2085    }
2086
2087    if (defined($source_map{$file})) {
2088	$file = $source_map{$file};
2089    }
2090
2091    return $file;
2092}
2093
2094sub process_export_file($) {
2095    my ($orig_file) = @_;
2096    my $file = map_filename($orig_file);
2097
2098    if (!open(IN,"<$file")) {
2099	print STDERR "Error: Cannot open file $file\n";
2100	++$errors;
2101	return;
2102    }
2103
2104    while (<IN>) {
2105	if (/$export_symbol/) {
2106	    next if (defined($nosymbol_table{$2}));
2107	    $function_table{$2} = 1;
2108	}
2109    }
2110
2111    close(IN);
2112}
2113
2114#
2115# Parsers for the various processing states.
2116#
2117# STATE_NORMAL: looking for the /** to begin everything.
2118#
2119sub process_normal() {
2120    if (/$doc_start/o) {
2121	$state = STATE_NAME;	# next line is always the function name
2122	$in_doc_sect = 0;
2123	$declaration_start_line = $. + 1;
2124    }
2125}
2126
2127#
2128# STATE_NAME: Looking for the "name - description" line
2129#
2130sub process_name($$) {
2131    my $file = shift;
2132    my $descr;
2133
2134    if (/$doc_block/o) {
2135	$state = STATE_DOCBLOCK;
2136	$contents = "";
2137	$new_start_line = $.;
2138
2139	if ( $1 eq "" ) {
2140	    $section = $section_intro;
2141	} else {
2142	    $section = $1;
2143	}
2144    } elsif (/$doc_decl/o) {
2145	$identifier = $1;
2146	my $is_kernel_comment = 0;
2147	my $decl_start = qr{$doc_com};
2148	# test for pointer declaration type, foo * bar() - desc
2149	my $fn_type = qr{\w+\s*\*\s*};
2150	my $parenthesis = qr{\(\w*\)};
2151	my $decl_end = qr{[-:].*};
2152	if (/^$decl_start([\w\s]+?)$parenthesis?\s*$decl_end?$/) {
2153	    $identifier = $1;
2154	}
2155	if ($identifier =~ m/^(struct|union|enum|typedef)\b\s*(\S*)/) {
2156	    $decl_type = $1;
2157	    $identifier = $2;
2158	    $is_kernel_comment = 1;
2159	}
2160	# Look for foo() or static void foo() - description; or misspelt
2161	# identifier
2162	elsif (/^$decl_start$fn_type?(\w+)\s*$parenthesis?\s*$decl_end?$/ ||
2163	    /^$decl_start$fn_type?(\w+.*)$parenthesis?\s*$decl_end$/) {
2164	    $identifier = $1;
2165	    $decl_type = 'function';
2166	    $identifier =~ s/^define\s+//;
2167	    $is_kernel_comment = 1;
2168	}
2169	$identifier =~ s/\s+$//;
2170
2171	$state = STATE_BODY;
2172	# if there's no @param blocks need to set up default section
2173	# here
2174	$contents = "";
2175	$section = $section_default;
2176	$new_start_line = $. + 1;
2177	if (/[-:](.*)/) {
2178	    # strip leading/trailing/multiple spaces
2179	    $descr= $1;
2180	    $descr =~ s/^\s*//;
2181	    $descr =~ s/\s*$//;
2182	    $descr =~ s/\s+/ /g;
2183	    $declaration_purpose = $descr;
2184	    $state = STATE_BODY_MAYBE;
2185	} else {
2186	    $declaration_purpose = "";
2187	}
2188
2189	if (!$is_kernel_comment) {
2190	    print STDERR "${file}:$.: warning: This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst\n";
2191	    print STDERR $_;
2192	    ++$warnings;
2193	    $state = STATE_NORMAL;
2194	}
2195
2196	if (($declaration_purpose eq "") && $verbose) {
2197	    print STDERR "${file}:$.: warning: missing initial short description on line:\n";
2198	    print STDERR $_;
2199	    ++$warnings;
2200	}
2201
2202	if ($identifier eq "" && $decl_type ne "enum") {
2203	    print STDERR "${file}:$.: warning: wrong kernel-doc identifier on line:\n";
2204	    print STDERR $_;
2205	    ++$warnings;
2206	    $state = STATE_NORMAL;
2207	}
2208
2209	if ($verbose) {
2210	    print STDERR "${file}:$.: info: Scanning doc for $decl_type $identifier\n";
2211	}
2212    } else {
2213	print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
2214	    " - I thought it was a doc line\n";
2215	++$warnings;
2216	$state = STATE_NORMAL;
2217    }
2218}
2219
2220
2221#
2222# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
2223#
2224sub process_body($$) {
2225    my $file = shift;
2226
2227    # Until all named variable macro parameters are
2228    # documented using the bare name (`x`) rather than with
2229    # dots (`x...`), strip the dots:
2230    if ($section =~ /\w\.\.\.$/) {
2231	$section =~ s/\.\.\.$//;
2232
2233	if ($verbose) {
2234	    print STDERR "${file}:$.: warning: Variable macro arguments should be documented without dots\n";
2235	    ++$warnings;
2236	}
2237    }
2238
2239    if ($state == STATE_BODY_WITH_BLANK_LINE && /^\s*\*\s?\S/) {
2240	dump_section($file, $section, $contents);
2241	$section = $section_default;
2242	$new_start_line = $.;
2243	$contents = "";
2244    }
2245
2246    if (/$doc_sect/i) { # case insensitive for supported section names
2247	$newsection = $1;
2248	$newcontents = $2;
2249
2250	# map the supported section names to the canonical names
2251	if ($newsection =~ m/^description$/i) {
2252	    $newsection = $section_default;
2253	} elsif ($newsection =~ m/^context$/i) {
2254	    $newsection = $section_context;
2255	} elsif ($newsection =~ m/^returns?$/i) {
2256	    $newsection = $section_return;
2257	} elsif ($newsection =~ m/^\@return$/) {
2258	    # special: @return is a section, not a param description
2259	    $newsection = $section_return;
2260	}
2261
2262	if (($contents ne "") && ($contents ne "\n")) {
2263	    if (!$in_doc_sect && $verbose) {
2264		print STDERR "${file}:$.: warning: contents before sections\n";
2265		++$warnings;
2266	    }
2267	    dump_section($file, $section, $contents);
2268	    $section = $section_default;
2269	}
2270
2271	$in_doc_sect = 1;
2272	$state = STATE_BODY;
2273	$contents = $newcontents;
2274	$new_start_line = $.;
2275	while (substr($contents, 0, 1) eq " ") {
2276	    $contents = substr($contents, 1);
2277	}
2278	if ($contents ne "") {
2279	    $contents .= "\n";
2280	}
2281	$section = $newsection;
2282	$leading_space = undef;
2283    } elsif (/$doc_end/) {
2284	if (($contents ne "") && ($contents ne "\n")) {
2285	    dump_section($file, $section, $contents);
2286	    $section = $section_default;
2287	    $contents = "";
2288	}
2289	# look for doc_com + <text> + doc_end:
2290	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2291	    print STDERR "${file}:$.: warning: suspicious ending line: $_";
2292	    ++$warnings;
2293	}
2294
2295	$prototype = "";
2296	$state = STATE_PROTO;
2297	$brcount = 0;
2298        $new_start_line = $. + 1;
2299    } elsif (/$doc_content/) {
2300	if ($1 eq "") {
2301	    if ($section eq $section_context) {
2302		dump_section($file, $section, $contents);
2303		$section = $section_default;
2304		$contents = "";
2305		$new_start_line = $.;
2306		$state = STATE_BODY;
2307	    } else {
2308		if ($section ne $section_default) {
2309		    $state = STATE_BODY_WITH_BLANK_LINE;
2310		} else {
2311		    $state = STATE_BODY;
2312		}
2313		$contents .= "\n";
2314	    }
2315	} elsif ($state == STATE_BODY_MAYBE) {
2316	    # Continued declaration purpose
2317	    chomp($declaration_purpose);
2318	    $declaration_purpose .= " " . $1;
2319	    $declaration_purpose =~ s/\s+/ /g;
2320	} else {
2321	    my $cont = $1;
2322	    if ($section =~ m/^@/ || $section eq $section_context) {
2323		if (!defined $leading_space) {
2324		    if ($cont =~ m/^(\s+)/) {
2325			$leading_space = $1;
2326		    } else {
2327			$leading_space = "";
2328		    }
2329		}
2330		$cont =~ s/^$leading_space//;
2331	    }
2332	    $contents .= $cont . "\n";
2333	}
2334    } else {
2335	# i dont know - bad line?  ignore.
2336	print STDERR "${file}:$.: warning: bad line: $_";
2337	++$warnings;
2338    }
2339}
2340
2341
2342#
2343# STATE_PROTO: reading a function/whatever prototype.
2344#
2345sub process_proto($$) {
2346    my $file = shift;
2347
2348    if (/$doc_inline_oneline/) {
2349	$section = $1;
2350	$contents = $2;
2351	if ($contents ne "") {
2352	    $contents .= "\n";
2353	    dump_section($file, $section, $contents);
2354	    $section = $section_default;
2355	    $contents = "";
2356	}
2357    } elsif (/$doc_inline_start/) {
2358	$state = STATE_INLINE;
2359	$inline_doc_state = STATE_INLINE_NAME;
2360    } elsif ($decl_type eq 'function') {
2361	process_proto_function($_, $file);
2362    } else {
2363	process_proto_type($_, $file);
2364    }
2365}
2366
2367#
2368# STATE_DOCBLOCK: within a DOC: block.
2369#
2370sub process_docblock($$) {
2371    my $file = shift;
2372
2373    if (/$doc_end/) {
2374	dump_doc_section($file, $section, $contents);
2375	$section = $section_default;
2376	$contents = "";
2377	$function = "";
2378	%parameterdescs = ();
2379	%parametertypes = ();
2380	@parameterlist = ();
2381	%sections = ();
2382	@sectionlist = ();
2383	$prototype = "";
2384	$state = STATE_NORMAL;
2385    } elsif (/$doc_content/) {
2386	if ( $1 eq "" )	{
2387	    $contents .= $blankline;
2388	} else {
2389	    $contents .= $1 . "\n";
2390	}
2391    }
2392}
2393
2394#
2395# STATE_INLINE: docbook comments within a prototype.
2396#
2397sub process_inline($$) {
2398    my $file = shift;
2399
2400    # First line (state 1) needs to be a @parameter
2401    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2402	$section = $1;
2403	$contents = $2;
2404	$new_start_line = $.;
2405	if ($contents ne "") {
2406	    while (substr($contents, 0, 1) eq " ") {
2407		$contents = substr($contents, 1);
2408	    }
2409	    $contents .= "\n";
2410	}
2411	$inline_doc_state = STATE_INLINE_TEXT;
2412	# Documentation block end */
2413    } elsif (/$doc_inline_end/) {
2414	if (($contents ne "") && ($contents ne "\n")) {
2415	    dump_section($file, $section, $contents);
2416	    $section = $section_default;
2417	    $contents = "";
2418	}
2419	$state = STATE_PROTO;
2420	$inline_doc_state = STATE_INLINE_NA;
2421	# Regular text
2422    } elsif (/$doc_content/) {
2423	if ($inline_doc_state == STATE_INLINE_TEXT) {
2424	    $contents .= $1 . "\n";
2425	    # nuke leading blank lines
2426	    if ($contents =~ /^\s*$/) {
2427		$contents = "";
2428	    }
2429	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2430	    $inline_doc_state = STATE_INLINE_ERROR;
2431	    print STDERR "${file}:$.: warning: ";
2432	    print STDERR "Incorrect use of kernel-doc format: $_";
2433	    ++$warnings;
2434	}
2435    }
2436}
2437
2438
2439sub process_file($) {
2440    my $file;
2441    my $initial_section_counter = $section_counter;
2442    my ($orig_file) = @_;
2443
2444    $file = map_filename($orig_file);
2445
2446    if (!open(IN_FILE,"<$file")) {
2447	print STDERR "Error: Cannot open file $file\n";
2448	++$errors;
2449	return;
2450    }
2451
2452    $. = 1;
2453
2454    $section_counter = 0;
2455    while (<IN_FILE>) {
2456	while (s/\\\s*$//) {
2457	    $_ .= <IN_FILE>;
2458	}
2459	# Replace tabs by spaces
2460        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2461	# Hand this line to the appropriate state handler
2462	if ($state == STATE_NORMAL) {
2463	    process_normal();
2464	} elsif ($state == STATE_NAME) {
2465	    process_name($file, $_);
2466	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE ||
2467		 $state == STATE_BODY_WITH_BLANK_LINE) {
2468	    process_body($file, $_);
2469	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2470	    process_inline($file, $_);
2471	} elsif ($state == STATE_PROTO) {
2472	    process_proto($file, $_);
2473	} elsif ($state == STATE_DOCBLOCK) {
2474	    process_docblock($file, $_);
2475	}
2476    }
2477
2478    # Make sure we got something interesting.
2479    if ($initial_section_counter == $section_counter && $
2480	output_mode ne "none") {
2481	if ($output_selection == OUTPUT_INCLUDE) {
2482	    print STDERR "${file}:1: warning: '$_' not found\n"
2483		for keys %function_table;
2484	}
2485	else {
2486	    print STDERR "${file}:1: warning: no structured comments found\n";
2487	}
2488    }
2489    close IN_FILE;
2490}
2491
2492
2493if ($output_mode eq "rst") {
2494	get_sphinx_version() if (!$sphinx_major);
2495}
2496
2497$kernelversion = get_kernel_version();
2498
2499# generate a sequence of code that will splice in highlighting information
2500# using the s// operator.
2501for (my $k = 0; $k < @highlights; $k++) {
2502    my $pattern = $highlights[$k][0];
2503    my $result = $highlights[$k][1];
2504#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2505    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2506}
2507
2508# Read the file that maps relative names to absolute names for
2509# separate source and object directories and for shadow trees.
2510if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2511	my ($relname, $absname);
2512	while(<SOURCE_MAP>) {
2513		chop();
2514		($relname, $absname) = (split())[0..1];
2515		$relname =~ s:^/+::;
2516		$source_map{$relname} = $absname;
2517	}
2518	close(SOURCE_MAP);
2519}
2520
2521if ($output_selection == OUTPUT_EXPORTED ||
2522    $output_selection == OUTPUT_INTERNAL) {
2523
2524    push(@export_file_list, @ARGV);
2525
2526    foreach (@export_file_list) {
2527	chomp;
2528	process_export_file($_);
2529    }
2530}
2531
2532foreach (@ARGV) {
2533    chomp;
2534    process_file($_);
2535}
2536if ($verbose && $errors) {
2537  print STDERR "$errors errors\n";
2538}
2539if ($verbose && $warnings) {
2540  print STDERR "$warnings warnings\n";
2541}
2542
2543if ($Werror && $warnings) {
2544    print STDERR "$warnings warnings as Errors\n";
2545    exit($warnings);
2546} else {
2547    exit($output_mode eq "none" ? 0 : $errors)
2548}
2549