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