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