xref: /openbmc/qemu/scripts/kernel-doc (revision 697f668ad1f9e8aae6bb0666a367a1849f84f896)
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|__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
1133	# replace DECLARE_BITMAP
1134	$members =~ s/__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)/DECLARE_BITMAP($1, __ETHTOOL_LINK_MODE_MASK_NBITS)/gos;
1135	$members =~ s/DECLARE_BITMAP\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[BITS_TO_LONGS($2)\]/gos;
1136	# replace DECLARE_HASHTABLE
1137	$members =~ s/DECLARE_HASHTABLE\s*\(([^,)]+),\s*([^,)]+)\)/unsigned long $1\[1 << (($2) - 1)\]/gos;
1138	# replace DECLARE_KFIFO
1139	$members =~ s/DECLARE_KFIFO\s*\(([^,)]+),\s*([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1140	# replace DECLARE_KFIFO_PTR
1141	$members =~ s/DECLARE_KFIFO_PTR\s*\(([^,)]+),\s*([^,)]+)\)/$2 \*$1/gos;
1142
1143	my $declaration = $members;
1144
1145	# Split nested struct/union elements as newer ones
1146	while ($members =~ m/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/) {
1147		my $newmember;
1148		my $maintype = $1;
1149		my $ids = $4;
1150		my $content = $3;
1151		foreach my $id(split /,/, $ids) {
1152			$newmember .= "$maintype $id; ";
1153
1154			$id =~ s/[:\[].*//;
1155			$id =~ s/^\s*\**(\S+)\s*/$1/;
1156			foreach my $arg (split /;/, $content) {
1157				next if ($arg =~ m/^\s*$/);
1158				if ($arg =~ m/^([^\(]+\(\*?\s*)([\w\.]*)(\s*\).*)/) {
1159					# pointer-to-function
1160					my $type = $1;
1161					my $name = $2;
1162					my $extra = $3;
1163					next if (!$name);
1164					if ($id =~ m/^\s*$/) {
1165						# anonymous struct/union
1166						$newmember .= "$type$name$extra; ";
1167					} else {
1168						$newmember .= "$type$id.$name$extra; ";
1169					}
1170				} else {
1171					my $type;
1172					my $names;
1173					$arg =~ s/^\s+//;
1174					$arg =~ s/\s+$//;
1175					# Handle bitmaps
1176					$arg =~ s/:\s*\d+\s*//g;
1177					# Handle arrays
1178					$arg =~ s/\[.*\]//g;
1179					# The type may have multiple words,
1180					# and multiple IDs can be defined, like:
1181					#	const struct foo, *bar, foobar
1182					# So, we remove spaces when parsing the
1183					# names, in order to match just names
1184					# and commas for the names
1185					$arg =~ s/\s*,\s*/,/g;
1186					if ($arg =~ m/(.*)\s+([\S+,]+)/) {
1187						$type = $1;
1188						$names = $2;
1189					} else {
1190						$newmember .= "$arg; ";
1191						next;
1192					}
1193					foreach my $name (split /,/, $names) {
1194						$name =~ s/^\s*\**(\S+)\s*/$1/;
1195						next if (($name =~ m/^\s*$/));
1196						if ($id =~ m/^\s*$/) {
1197							# anonymous struct/union
1198							$newmember .= "$type $name; ";
1199						} else {
1200							$newmember .= "$type $id.$name; ";
1201						}
1202					}
1203				}
1204			}
1205		}
1206		$members =~ s/(struct|union)([^\{\};]+)\{([^\{\}]*)\}([^\{\}\;]*)\;/$newmember/;
1207	}
1208
1209	# Ignore other nested elements, like enums
1210	$members =~ s/(\{[^\{\}]*\})//g;
1211
1212	create_parameterlist($members, ';', $file, $declaration_name);
1213	check_sections($file, $declaration_name, $decl_type, $sectcheck, $struct_actual);
1214
1215	# Adjust declaration for better display
1216	$declaration =~ s/([\{;])/$1\n/g;
1217	$declaration =~ s/\}\s+;/};/g;
1218	# Better handle inlined enums
1219	do {} while ($declaration =~ s/(enum\s+\{[^\}]+),([^\n])/$1,\n$2/);
1220
1221	my @def_args = split /\n/, $declaration;
1222	my $level = 1;
1223	$declaration = "";
1224	foreach my $clause (@def_args) {
1225		$clause =~ s/^\s+//;
1226		$clause =~ s/\s+$//;
1227		$clause =~ s/\s+/ /;
1228		next if (!$clause);
1229		$level-- if ($clause =~ m/(\})/ && $level > 1);
1230		if (!($clause =~ m/^\s*#/)) {
1231			$declaration .= "\t" x $level;
1232		}
1233		$declaration .= "\t" . $clause . "\n";
1234		$level++ if ($clause =~ m/(\{)/ && !($clause =~m/\}/));
1235	}
1236	output_declaration($declaration_name,
1237			   'struct',
1238			   {'struct' => $declaration_name,
1239			    'module' => $modulename,
1240			    'definition' => $declaration,
1241			    'parameterlist' => \@parameterlist,
1242			    'parameterdescs' => \%parameterdescs,
1243			    'parametertypes' => \%parametertypes,
1244			    'sectionlist' => \@sectionlist,
1245			    'sections' => \%sections,
1246			    'purpose' => $declaration_purpose,
1247			    'type' => $decl_type
1248			   });
1249    }
1250    else {
1251	print STDERR "${file}:$.: error: Cannot parse struct or union!\n";
1252	++$errors;
1253    }
1254}
1255
1256
1257sub show_warnings($$) {
1258	my $functype = shift;
1259	my $name = shift;
1260
1261	return 1 if ($output_selection == OUTPUT_ALL);
1262
1263	if ($output_selection == OUTPUT_EXPORTED) {
1264		if (defined($function_table{$name})) {
1265			return 1;
1266		} else {
1267			return 0;
1268		}
1269	}
1270        if ($output_selection == OUTPUT_INTERNAL) {
1271		if (!($functype eq "function" && defined($function_table{$name}))) {
1272			return 1;
1273		} else {
1274			return 0;
1275		}
1276	}
1277	if ($output_selection == OUTPUT_INCLUDE) {
1278		if (defined($function_table{$name})) {
1279			return 1;
1280		} else {
1281			return 0;
1282		}
1283	}
1284	if ($output_selection == OUTPUT_EXCLUDE) {
1285		if (!defined($function_table{$name})) {
1286			return 1;
1287		} else {
1288			return 0;
1289		}
1290	}
1291	die("Please add the new output type at show_warnings()");
1292}
1293
1294sub dump_enum($$) {
1295    my $x = shift;
1296    my $file = shift;
1297
1298    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1299    # strip #define macros inside enums
1300    $x =~ s@#\s*((define|ifdef)\s+|endif)[^;]*;@@gos;
1301
1302    if ($x =~ /enum\s+(\w*)\s*\{(.*)\}/) {
1303	$declaration_name = $1;
1304	my $members = $2;
1305	my %_members;
1306
1307	$members =~ s/\s+$//;
1308
1309	foreach my $arg (split ',', $members) {
1310	    $arg =~ s/^\s*(\w+).*/$1/;
1311	    push @parameterlist, $arg;
1312	    if (!$parameterdescs{$arg}) {
1313		$parameterdescs{$arg} = $undescribed;
1314	        if (show_warnings("enum", $declaration_name)) {
1315			print STDERR "${file}:$.: warning: Enum value '$arg' not described in enum '$declaration_name'\n";
1316		}
1317	    }
1318	    $_members{$arg} = 1;
1319	}
1320
1321	while (my ($k, $v) = each %parameterdescs) {
1322	    if (!exists($_members{$k})) {
1323	        if (show_warnings("enum", $declaration_name)) {
1324		     print STDERR "${file}:$.: warning: Excess enum value '$k' description in '$declaration_name'\n";
1325		}
1326	    }
1327        }
1328
1329	output_declaration($declaration_name,
1330			   'enum',
1331			   {'enum' => $declaration_name,
1332			    'module' => $modulename,
1333			    'parameterlist' => \@parameterlist,
1334			    'parameterdescs' => \%parameterdescs,
1335			    'sectionlist' => \@sectionlist,
1336			    'sections' => \%sections,
1337			    'purpose' => $declaration_purpose
1338			   });
1339    }
1340    else {
1341	print STDERR "${file}:$.: error: Cannot parse enum!\n";
1342	++$errors;
1343    }
1344}
1345
1346sub dump_typedef($$) {
1347    my $x = shift;
1348    my $file = shift;
1349
1350    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
1351
1352    # Parse function prototypes
1353    if ($x =~ /typedef\s+(\w+\s*\**)\s*\(\*?\s*(\w\S+)\s*\)\s*\((.*)\);/ ||
1354	$x =~ /typedef\s+(\w+\s*\**)\s*(\w\S+)\s*\s*\((.*)\);/) {
1355
1356	# Function typedefs
1357	$return_type = $1;
1358	$declaration_name = $2;
1359	my $args = $3;
1360
1361	create_parameterlist($args, ',', $file, $declaration_name);
1362
1363	output_declaration($declaration_name,
1364			   'function',
1365			   {'function' => $declaration_name,
1366			    'typedef' => 1,
1367			    'module' => $modulename,
1368			    'functiontype' => $return_type,
1369			    'parameterlist' => \@parameterlist,
1370			    'parameterdescs' => \%parameterdescs,
1371			    'parametertypes' => \%parametertypes,
1372			    'sectionlist' => \@sectionlist,
1373			    'sections' => \%sections,
1374			    'purpose' => $declaration_purpose
1375			   });
1376	return;
1377    }
1378
1379    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
1380	$x =~ s/\(*.\)\s*;$/;/;
1381	$x =~ s/\[*.\]\s*;$/;/;
1382    }
1383
1384    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
1385	$declaration_name = $1;
1386
1387	output_declaration($declaration_name,
1388			   'typedef',
1389			   {'typedef' => $declaration_name,
1390			    'module' => $modulename,
1391			    'sectionlist' => \@sectionlist,
1392			    'sections' => \%sections,
1393			    'purpose' => $declaration_purpose
1394			   });
1395    }
1396    else {
1397	print STDERR "${file}:$.: error: Cannot parse typedef!\n";
1398	++$errors;
1399    }
1400}
1401
1402sub save_struct_actual($) {
1403    my $actual = shift;
1404
1405    # strip all spaces from the actual param so that it looks like one string item
1406    $actual =~ s/\s*//g;
1407    $struct_actual = $struct_actual . $actual . " ";
1408}
1409
1410sub create_parameterlist($$$$) {
1411    my $args = shift;
1412    my $splitter = shift;
1413    my $file = shift;
1414    my $declaration_name = shift;
1415    my $type;
1416    my $param;
1417
1418    # temporarily replace commas inside function pointer definition
1419    while ($args =~ /(\([^\),]+),/) {
1420	$args =~ s/(\([^\),]+),/$1#/g;
1421    }
1422
1423    foreach my $arg (split($splitter, $args)) {
1424	# strip comments
1425	$arg =~ s/\/\*.*\*\///;
1426	# strip leading/trailing spaces
1427	$arg =~ s/^\s*//;
1428	$arg =~ s/\s*$//;
1429	$arg =~ s/\s+/ /;
1430
1431	if ($arg =~ /^#/) {
1432	    # Treat preprocessor directive as a typeless variable just to fill
1433	    # corresponding data structures "correctly". Catch it later in
1434	    # output_* subs.
1435	    push_parameter($arg, "", $file);
1436	} elsif ($arg =~ m/\(.+\)\s*\(/) {
1437	    # pointer-to-function
1438	    $arg =~ tr/#/,/;
1439	    $arg =~ m/[^\(]+\(\*?\s*([\w\.]*)\s*\)/;
1440	    $param = $1;
1441	    $type = $arg;
1442	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
1443	    save_struct_actual($param);
1444	    push_parameter($param, $type, $file, $declaration_name);
1445	} elsif ($arg) {
1446	    $arg =~ s/\s*:\s*/:/g;
1447	    $arg =~ s/\s*\[/\[/g;
1448
1449	    my @args = split('\s*,\s*', $arg);
1450	    if ($args[0] =~ m/\*/) {
1451		$args[0] =~ s/(\*+)\s*/ $1/;
1452	    }
1453
1454	    my @first_arg;
1455	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
1456		    shift @args;
1457		    push(@first_arg, split('\s+', $1));
1458		    push(@first_arg, $2);
1459	    } else {
1460		    @first_arg = split('\s+', shift @args);
1461	    }
1462
1463	    unshift(@args, pop @first_arg);
1464	    $type = join " ", @first_arg;
1465
1466	    foreach $param (@args) {
1467		if ($param =~ m/^(\*+)\s*(.*)/) {
1468		    save_struct_actual($2);
1469		    push_parameter($2, "$type $1", $file, $declaration_name);
1470		}
1471		elsif ($param =~ m/(.*?):(\d+)/) {
1472		    if ($type ne "") { # skip unnamed bit-fields
1473			save_struct_actual($1);
1474			push_parameter($1, "$type:$2", $file, $declaration_name)
1475		    }
1476		}
1477		else {
1478		    save_struct_actual($param);
1479		    push_parameter($param, $type, $file, $declaration_name);
1480		}
1481	    }
1482	}
1483    }
1484}
1485
1486sub push_parameter($$$$) {
1487	my $param = shift;
1488	my $type = shift;
1489	my $file = shift;
1490	my $declaration_name = shift;
1491
1492	if (($anon_struct_union == 1) && ($type eq "") &&
1493	    ($param eq "}")) {
1494		return;		# ignore the ending }; from anon. struct/union
1495	}
1496
1497	$anon_struct_union = 0;
1498	$param =~ s/[\[\)].*//;
1499
1500	if ($type eq "" && $param =~ /\.\.\.$/)
1501	{
1502	    if (!$param =~ /\w\.\.\.$/) {
1503	      # handles unnamed variable parameters
1504	      $param = "...";
1505	    }
1506	    elsif ($param =~ /\w\.\.\.$/) {
1507	      # for named variable parameters of the form `x...`, remove the dots
1508	      $param =~ s/\.\.\.$//;
1509	    }
1510	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
1511		$parameterdescs{$param} = "variable arguments";
1512	    }
1513	}
1514	elsif ($type eq "" && ($param eq "" or $param eq "void"))
1515	{
1516	    $param="void";
1517	    $parameterdescs{void} = "no arguments";
1518	}
1519	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
1520	# handle unnamed (anonymous) union or struct:
1521	{
1522		$type = $param;
1523		$param = "{unnamed_" . $param . "}";
1524		$parameterdescs{$param} = "anonymous\n";
1525		$anon_struct_union = 1;
1526	}
1527
1528	# warn if parameter has no description
1529	# (but ignore ones starting with # as these are not parameters
1530	# but inline preprocessor statements);
1531	# Note: It will also ignore void params and unnamed structs/unions
1532	if (!defined $parameterdescs{$param} && $param !~ /^#/) {
1533		$parameterdescs{$param} = $undescribed;
1534
1535	        if (show_warnings($type, $declaration_name) && $param !~ /\./) {
1536			print STDERR
1537			      "${file}:$.: warning: Function parameter or member '$param' not described in '$declaration_name'\n";
1538			++$warnings;
1539		}
1540	}
1541
1542	# strip spaces from $param so that it is one continuous string
1543	# on @parameterlist;
1544	# this fixes a problem where check_sections() cannot find
1545	# a parameter like "addr[6 + 2]" because it actually appears
1546	# as "addr[6", "+", "2]" on the parameter list;
1547	# but it's better to maintain the param string unchanged for output,
1548	# so just weaken the string compare in check_sections() to ignore
1549	# "[blah" in a parameter string;
1550	###$param =~ s/\s*//g;
1551	push @parameterlist, $param;
1552	$type =~ s/\s\s+/ /g;
1553	$parametertypes{$param} = $type;
1554}
1555
1556sub check_sections($$$$$) {
1557	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck) = @_;
1558	my @sects = split ' ', $sectcheck;
1559	my @prms = split ' ', $prmscheck;
1560	my $err;
1561	my ($px, $sx);
1562	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"
1563
1564	foreach $sx (0 .. $#sects) {
1565		$err = 1;
1566		foreach $px (0 .. $#prms) {
1567			$prm_clean = $prms[$px];
1568			$prm_clean =~ s/\[.*\]//;
1569			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//i;
1570			# ignore array size in a parameter string;
1571			# however, the original param string may contain
1572			# spaces, e.g.:  addr[6 + 2]
1573			# and this appears in @prms as "addr[6" since the
1574			# parameter list is split at spaces;
1575			# hence just ignore "[..." for the sections check;
1576			$prm_clean =~ s/\[.*//;
1577
1578			##$prm_clean =~ s/^\**//;
1579			if ($prm_clean eq $sects[$sx]) {
1580				$err = 0;
1581				last;
1582			}
1583		}
1584		if ($err) {
1585			if ($decl_type eq "function") {
1586				print STDERR "${file}:$.: warning: " .
1587					"Excess function parameter " .
1588					"'$sects[$sx]' " .
1589					"description in '$decl_name'\n";
1590				++$warnings;
1591			}
1592		}
1593	}
1594}
1595
1596##
1597# Checks the section describing the return value of a function.
1598sub check_return_section {
1599        my $file = shift;
1600        my $declaration_name = shift;
1601        my $return_type = shift;
1602
1603        # Ignore an empty return type (It's a macro)
1604        # Ignore functions with a "void" return type. (But don't ignore "void *")
1605        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
1606                return;
1607        }
1608
1609        if (!defined($sections{$section_return}) ||
1610            $sections{$section_return} eq "") {
1611                print STDERR "${file}:$.: warning: " .
1612                        "No description found for return value of " .
1613                        "'$declaration_name'\n";
1614                ++$warnings;
1615        }
1616}
1617
1618##
1619# takes a function prototype and the name of the current file being
1620# processed and spits out all the details stored in the global
1621# arrays/hashes.
1622sub dump_function($$) {
1623    my $prototype = shift;
1624    my $file = shift;
1625    my $noret = 0;
1626
1627    print_lineno($.);
1628
1629    $prototype =~ s/^static +//;
1630    $prototype =~ s/^extern +//;
1631    $prototype =~ s/^asmlinkage +//;
1632    $prototype =~ s/^inline +//;
1633    $prototype =~ s/^__inline__ +//;
1634    $prototype =~ s/^__inline +//;
1635    $prototype =~ s/^__always_inline +//;
1636    $prototype =~ s/^noinline +//;
1637    $prototype =~ s/__init +//;
1638    $prototype =~ s/__init_or_module +//;
1639    $prototype =~ s/__meminit +//;
1640    $prototype =~ s/__must_check +//;
1641    $prototype =~ s/__weak +//;
1642    $prototype =~ s/__sched +//;
1643    $prototype =~ s/__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +//;
1644    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
1645    $prototype =~ s/__attribute__\s*\(\(
1646            (?:
1647                 [\w\s]++          # attribute name
1648                 (?:\([^)]*+\))?   # attribute arguments
1649                 \s*+,?            # optional comma at the end
1650            )+
1651          \)\)\s+//x;
1652
1653    # Yes, this truly is vile.  We are looking for:
1654    # 1. Return type (may be nothing if we're looking at a macro)
1655    # 2. Function name
1656    # 3. Function parameters.
1657    #
1658    # All the while we have to watch out for function pointer parameters
1659    # (which IIRC is what the two sections are for), C types (these
1660    # regexps don't even start to express all the possibilities), and
1661    # so on.
1662    #
1663    # If you mess with these regexps, it's a good idea to check that
1664    # the following functions' documentation still comes out right:
1665    # - parport_register_device (function pointer parameters)
1666    # - qatomic_set (macro)
1667    # - pci_match_device, __copy_to_user (long return type)
1668
1669    if ($define && $prototype =~ m/^()([a-zA-Z0-9_~:]+)\s+/) {
1670        # This is an object-like macro, it has no return type and no parameter
1671        # list.
1672        # Function-like macros are not allowed to have spaces between
1673        # declaration_name and opening parenthesis (notice the \s+).
1674        $return_type = $1;
1675        $declaration_name = $2;
1676        $noret = 1;
1677    } elsif ($prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1678	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1679	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1680	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1681	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1682	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1683	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
1684	$prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1685	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1686	$prototype =~ m/^(\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1687	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1688	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1689	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1690	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1691	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1692	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
1693	$prototype =~ m/^(\w+\s+\w+\s*\*+\s*\w+\s*\*+\s*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/)  {
1694	$return_type = $1;
1695	$declaration_name = $2;
1696	my $args = $3;
1697
1698	create_parameterlist($args, ',', $file, $declaration_name);
1699    } else {
1700	print STDERR "${file}:$.: warning: cannot understand function prototype: '$prototype'\n";
1701	return;
1702    }
1703
1704	my $prms = join " ", @parameterlist;
1705	check_sections($file, $declaration_name, "function", $sectcheck, $prms);
1706
1707        # This check emits a lot of warnings at the moment, because many
1708        # functions don't have a 'Return' doc section. So until the number
1709        # of warnings goes sufficiently down, the check is only performed in
1710        # verbose mode.
1711        # TODO: always perform the check.
1712        if ($verbose && !$noret) {
1713                check_return_section($file, $declaration_name, $return_type);
1714        }
1715
1716    output_declaration($declaration_name,
1717		       'function',
1718		       {'function' => $declaration_name,
1719			'module' => $modulename,
1720			'functiontype' => $return_type,
1721			'parameterlist' => \@parameterlist,
1722			'parameterdescs' => \%parameterdescs,
1723			'parametertypes' => \%parametertypes,
1724			'sectionlist' => \@sectionlist,
1725			'sections' => \%sections,
1726			'purpose' => $declaration_purpose
1727		       });
1728}
1729
1730sub reset_state {
1731    $function = "";
1732    %parameterdescs = ();
1733    %parametertypes = ();
1734    @parameterlist = ();
1735    %sections = ();
1736    @sectionlist = ();
1737    $sectcheck = "";
1738    $struct_actual = "";
1739    $prototype = "";
1740
1741    $state = STATE_NORMAL;
1742    $inline_doc_state = STATE_INLINE_NA;
1743}
1744
1745sub tracepoint_munge($) {
1746	my $file = shift;
1747	my $tracepointname = 0;
1748	my $tracepointargs = 0;
1749
1750	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
1751		$tracepointname = $1;
1752	}
1753	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
1754		$tracepointname = $1;
1755	}
1756	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
1757		$tracepointname = $2;
1758	}
1759	$tracepointname =~ s/^\s+//; #strip leading whitespace
1760	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
1761		$tracepointargs = $1;
1762	}
1763	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
1764		print STDERR "${file}:$.: warning: Unrecognized tracepoint format: \n".
1765			     "$prototype\n";
1766	} else {
1767		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
1768	}
1769}
1770
1771sub syscall_munge() {
1772	my $void = 0;
1773
1774	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/CR's
1775##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
1776	if ($prototype =~ m/SYSCALL_DEFINE0/) {
1777		$void = 1;
1778##		$prototype = "long sys_$1(void)";
1779	}
1780
1781	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
1782	if ($prototype =~ m/long (sys_.*?),/) {
1783		$prototype =~ s/,/\(/;
1784	} elsif ($void) {
1785		$prototype =~ s/\)/\(void\)/;
1786	}
1787
1788	# now delete all of the odd-number commas in $prototype
1789	# so that arg types & arg names don't have a comma between them
1790	my $count = 0;
1791	my $len = length($prototype);
1792	if ($void) {
1793		$len = 0;	# skip the for-loop
1794	}
1795	for (my $ix = 0; $ix < $len; $ix++) {
1796		if (substr($prototype, $ix, 1) eq ',') {
1797			$count++;
1798			if ($count % 2 == 1) {
1799				substr($prototype, $ix, 1) = ' ';
1800			}
1801		}
1802	}
1803}
1804
1805sub process_proto_function($$) {
1806    my $x = shift;
1807    my $file = shift;
1808
1809    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1810
1811    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
1812	# do nothing
1813    }
1814    elsif ($x =~ /([^\{]*)/) {
1815	$prototype .= $1;
1816    }
1817
1818    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
1819	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
1820	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1821	$prototype =~ s@^\s+@@gos; # strip leading spaces
1822
1823	 # Handle prototypes for function pointers like:
1824	 # int (*pcs_config)(struct foo)
1825	$prototype =~ s@^(\S+\s+)\(\s*\*(\S+)\)@$1$2@gos;
1826
1827	if ($prototype =~ /SYSCALL_DEFINE/) {
1828		syscall_munge();
1829	}
1830	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
1831	    $prototype =~ /DEFINE_SINGLE_EVENT/)
1832	{
1833		tracepoint_munge($file);
1834	}
1835	dump_function($prototype, $file);
1836	reset_state();
1837    }
1838}
1839
1840sub process_proto_type($$) {
1841    my $x = shift;
1842    my $file = shift;
1843
1844    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
1845    $x =~ s@^\s+@@gos; # strip leading spaces
1846    $x =~ s@\s+$@@gos; # strip trailing spaces
1847    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line
1848
1849    if ($x =~ /^#/) {
1850	# To distinguish preprocessor directive from regular declaration later.
1851	$x .= ";";
1852    }
1853
1854    while (1) {
1855	if ( $x =~ /([^\{\};]*)([\{\};])(.*)/ ) {
1856            if( length $prototype ) {
1857                $prototype .= " "
1858            }
1859	    $prototype .= $1 . $2;
1860	    ($2 eq '{') && $brcount++;
1861	    ($2 eq '}') && $brcount--;
1862	    if (($2 eq ';') && ($brcount == 0)) {
1863		dump_declaration($prototype, $file);
1864		reset_state();
1865		last;
1866	    }
1867	    $x = $3;
1868	} else {
1869	    $prototype .= $x;
1870	    last;
1871	}
1872    }
1873}
1874
1875
1876sub map_filename($) {
1877    my $file;
1878    my ($orig_file) = @_;
1879
1880    if (defined($ENV{'SRCTREE'})) {
1881	$file = "$ENV{'SRCTREE'}" . "/" . $orig_file;
1882    } else {
1883	$file = $orig_file;
1884    }
1885
1886    if (defined($source_map{$file})) {
1887	$file = $source_map{$file};
1888    }
1889
1890    return $file;
1891}
1892
1893sub process_export_file($) {
1894    my ($orig_file) = @_;
1895    my $file = map_filename($orig_file);
1896
1897    if (!open(IN,"<$file")) {
1898	print STDERR "Error: Cannot open file $file\n";
1899	++$errors;
1900	return;
1901    }
1902
1903    while (<IN>) {
1904	if (/$export_symbol/) {
1905	    $function_table{$2} = 1;
1906	}
1907    }
1908
1909    close(IN);
1910}
1911
1912#
1913# Parsers for the various processing states.
1914#
1915# STATE_NORMAL: looking for the /** to begin everything.
1916#
1917sub process_normal() {
1918    if (/$doc_start/o) {
1919	$state = STATE_NAME;	# next line is always the function name
1920	$in_doc_sect = 0;
1921	$declaration_start_line = $. + 1;
1922    }
1923}
1924
1925#
1926# STATE_NAME: Looking for the "name - description" line
1927#
1928sub process_name($$) {
1929    my $file = shift;
1930    my $identifier;
1931    my $descr;
1932
1933    if (/$doc_block/o) {
1934	$state = STATE_DOCBLOCK;
1935	$contents = "";
1936	$new_start_line = $. + 1;
1937
1938	if ( $1 eq "" ) {
1939	    $section = $section_intro;
1940	} else {
1941	    $section = $1;
1942	}
1943    }
1944    elsif (/$doc_decl/o) {
1945	$identifier = $1;
1946	if (/\s*([\w\s]+?)(\s*-|:)/) {
1947	    $identifier = $1;
1948	}
1949
1950	$state = STATE_BODY;
1951	# if there's no @param blocks need to set up default section
1952	# here
1953	$contents = "";
1954	$section = $section_default;
1955	$new_start_line = $. + 1;
1956	if (/[-:](.*)/) {
1957	    # strip leading/trailing/multiple spaces
1958	    $descr= $1;
1959	    $descr =~ s/^\s*//;
1960	    $descr =~ s/\s*$//;
1961	    $descr =~ s/\s+/ /g;
1962	    $declaration_purpose = $descr;
1963	    $state = STATE_BODY_MAYBE;
1964	} else {
1965	    $declaration_purpose = "";
1966	}
1967
1968	if (($declaration_purpose eq "") && $verbose) {
1969	    print STDERR "${file}:$.: warning: missing initial short description on line:\n";
1970	    print STDERR $_;
1971	    ++$warnings;
1972	}
1973
1974	if ($identifier =~ m/^struct\b/) {
1975	    $decl_type = 'struct';
1976	} elsif ($identifier =~ m/^union\b/) {
1977	    $decl_type = 'union';
1978	} elsif ($identifier =~ m/^enum\b/) {
1979	    $decl_type = 'enum';
1980	} elsif ($identifier =~ m/^typedef\b/) {
1981	    $decl_type = 'typedef';
1982	} else {
1983	    $decl_type = 'function';
1984	}
1985
1986	if ($verbose) {
1987	    print STDERR "${file}:$.: info: Scanning doc for $identifier\n";
1988	}
1989    } else {
1990	print STDERR "${file}:$.: warning: Cannot understand $_ on line $.",
1991	    " - I thought it was a doc line\n";
1992	++$warnings;
1993	$state = STATE_NORMAL;
1994    }
1995}
1996
1997
1998#
1999# STATE_BODY and STATE_BODY_MAYBE: the bulk of a kerneldoc comment.
2000#
2001sub process_body($$) {
2002    my $file = shift;
2003
2004    # Until all named variable macro parameters are
2005    # documented using the bare name (`x`) rather than with
2006    # dots (`x...`), strip the dots:
2007    if ($section =~ /\w\.\.\.$/) {
2008	$section =~ s/\.\.\.$//;
2009
2010	if ($verbose) {
2011	    print STDERR "${file}:$.: warning: Variable macro arguments should be documented without dots\n";
2012	    ++$warnings;
2013	}
2014    }
2015
2016    if ($state == STATE_BODY_WITH_BLANK_LINE && /^\s*\*\s?\S/) {
2017	dump_section($file, $section, $contents);
2018	$section = $section_default;
2019	$contents = "";
2020    }
2021
2022    if (/$doc_sect/i) { # case insensitive for supported section names
2023	$newsection = $1;
2024	$newcontents = $2;
2025
2026	# map the supported section names to the canonical names
2027	if ($newsection =~ m/^description$/i) {
2028	    $newsection = $section_default;
2029	} elsif ($newsection =~ m/^context$/i) {
2030	    $newsection = $section_context;
2031	} elsif ($newsection =~ m/^returns?$/i) {
2032	    $newsection = $section_return;
2033	} elsif ($newsection =~ m/^\@return$/) {
2034	    # special: @return is a section, not a param description
2035	    $newsection = $section_return;
2036	}
2037
2038	if (($contents ne "") && ($contents ne "\n")) {
2039	    if (!$in_doc_sect && $verbose) {
2040		print STDERR "${file}:$.: warning: contents before sections\n";
2041		++$warnings;
2042	    }
2043	    dump_section($file, $section, $contents);
2044	    $section = $section_default;
2045	}
2046
2047	$in_doc_sect = 1;
2048	$state = STATE_BODY;
2049	$contents = $newcontents;
2050	$new_start_line = $.;
2051	while (substr($contents, 0, 1) eq " ") {
2052	    $contents = substr($contents, 1);
2053	}
2054	if ($contents ne "") {
2055	    $contents .= "\n";
2056	}
2057	$section = $newsection;
2058	$leading_space = undef;
2059    } elsif (/$doc_end/) {
2060	if (($contents ne "") && ($contents ne "\n")) {
2061	    dump_section($file, $section, $contents);
2062	    $section = $section_default;
2063	    $contents = "";
2064	}
2065	# look for doc_com + <text> + doc_end:
2066	if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
2067	    print STDERR "${file}:$.: warning: suspicious ending line: $_";
2068	    ++$warnings;
2069	}
2070
2071	$prototype = "";
2072	$state = STATE_PROTO;
2073	$brcount = 0;
2074    } elsif (/$doc_content/) {
2075	if ($1 eq "") {
2076	    if ($section eq $section_context) {
2077		dump_section($file, $section, $contents);
2078		$section = $section_default;
2079		$contents = "";
2080		$new_start_line = $.;
2081		$state = STATE_BODY;
2082	    } else {
2083		if ($section ne $section_default) {
2084		    $state = STATE_BODY_WITH_BLANK_LINE;
2085		} else {
2086		    $state = STATE_BODY;
2087		}
2088		$contents .= "\n";
2089	    }
2090	} elsif ($state == STATE_BODY_MAYBE) {
2091	    # Continued declaration purpose
2092	    chomp($declaration_purpose);
2093	    $declaration_purpose .= " " . $1;
2094	    $declaration_purpose =~ s/\s+/ /g;
2095	} else {
2096	    my $cont = $1;
2097	    if ($section =~ m/^@/ || $section eq $section_context) {
2098		if (!defined $leading_space) {
2099		    if ($cont =~ m/^(\s+)/) {
2100			$leading_space = $1;
2101		    } else {
2102			$leading_space = "";
2103		    }
2104		}
2105		$cont =~ s/^$leading_space//;
2106	    }
2107	    $contents .= $cont . "\n";
2108	}
2109    } else {
2110	# i dont know - bad line?  ignore.
2111	print STDERR "${file}:$.: warning: bad line: $_";
2112	++$warnings;
2113    }
2114}
2115
2116
2117#
2118# STATE_PROTO: reading a function/whatever prototype.
2119#
2120sub process_proto($$) {
2121    my $file = shift;
2122
2123    if (/$doc_inline_oneline/) {
2124	$section = $1;
2125	$contents = $2;
2126	if ($contents ne "") {
2127	    $contents .= "\n";
2128	    dump_section($file, $section, $contents);
2129	    $section = $section_default;
2130	    $contents = "";
2131	}
2132    } elsif (/$doc_inline_start/) {
2133	$state = STATE_INLINE;
2134	$inline_doc_state = STATE_INLINE_NAME;
2135    } elsif ($decl_type eq 'function') {
2136	process_proto_function($_, $file);
2137    } else {
2138	process_proto_type($_, $file);
2139    }
2140}
2141
2142#
2143# STATE_DOCBLOCK: within a DOC: block.
2144#
2145sub process_docblock($$) {
2146    my $file = shift;
2147
2148    if (/$doc_end/) {
2149	dump_doc_section($file, $section, $contents);
2150	$section = $section_default;
2151	$contents = "";
2152	$function = "";
2153	%parameterdescs = ();
2154	%parametertypes = ();
2155	@parameterlist = ();
2156	%sections = ();
2157	@sectionlist = ();
2158	$prototype = "";
2159	$state = STATE_NORMAL;
2160    } elsif (/$doc_content/) {
2161	if ( $1 eq "" )	{
2162	    $contents .= $blankline;
2163	} else {
2164	    $contents .= $1 . "\n";
2165	}
2166    }
2167}
2168
2169#
2170# STATE_INLINE: docbook comments within a prototype.
2171#
2172sub process_inline($$) {
2173    my $file = shift;
2174
2175    # First line (state 1) needs to be a @parameter
2176    if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) {
2177	$section = $1;
2178	$contents = $2;
2179	$new_start_line = $.;
2180	if ($contents ne "") {
2181	    while (substr($contents, 0, 1) eq " ") {
2182		$contents = substr($contents, 1);
2183	    }
2184	    $contents .= "\n";
2185	}
2186	$inline_doc_state = STATE_INLINE_TEXT;
2187	# Documentation block end */
2188    } elsif (/$doc_inline_end/) {
2189	if (($contents ne "") && ($contents ne "\n")) {
2190	    dump_section($file, $section, $contents);
2191	    $section = $section_default;
2192	    $contents = "";
2193	}
2194	$state = STATE_PROTO;
2195	$inline_doc_state = STATE_INLINE_NA;
2196	# Regular text
2197    } elsif (/$doc_content/) {
2198	if ($inline_doc_state == STATE_INLINE_TEXT) {
2199	    $contents .= $1 . "\n";
2200	    # nuke leading blank lines
2201	    if ($contents =~ /^\s*$/) {
2202		$contents = "";
2203	    }
2204	} elsif ($inline_doc_state == STATE_INLINE_NAME) {
2205	    $inline_doc_state = STATE_INLINE_ERROR;
2206	    print STDERR "${file}:$.: warning: ";
2207	    print STDERR "Incorrect use of kernel-doc format: $_";
2208	    ++$warnings;
2209	}
2210    }
2211}
2212
2213
2214sub process_file($) {
2215    my $file;
2216    my $initial_section_counter = $section_counter;
2217    my ($orig_file) = @_;
2218
2219    $file = map_filename($orig_file);
2220
2221    if (!open(IN,"<$file")) {
2222	print STDERR "Error: Cannot open file $file\n";
2223	++$errors;
2224	return;
2225    }
2226
2227    $. = 1;
2228
2229    $section_counter = 0;
2230    while (<IN>) {
2231	while (s/\\\s*$//) {
2232	    $_ .= <IN>;
2233	}
2234	# Replace tabs by spaces
2235        while ($_ =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {};
2236	# Hand this line to the appropriate state handler
2237	if ($state == STATE_NORMAL) {
2238	    process_normal();
2239	} elsif ($state == STATE_NAME) {
2240	    process_name($file, $_);
2241	} elsif ($state == STATE_BODY || $state == STATE_BODY_MAYBE ||
2242		 $state == STATE_BODY_WITH_BLANK_LINE) {
2243	    process_body($file, $_);
2244	} elsif ($state == STATE_INLINE) { # scanning for inline parameters
2245	    process_inline($file, $_);
2246	} elsif ($state == STATE_PROTO) {
2247	    process_proto($file, $_);
2248	} elsif ($state == STATE_DOCBLOCK) {
2249	    process_docblock($file, $_);
2250	}
2251    }
2252
2253    # Make sure we got something interesting.
2254    if ($initial_section_counter == $section_counter && $
2255	output_mode ne "none") {
2256	if ($output_selection == OUTPUT_INCLUDE) {
2257	    print STDERR "${file}:1: warning: '$_' not found\n"
2258		for keys %function_table;
2259	}
2260	else {
2261	    print STDERR "${file}:1: warning: no structured comments found\n";
2262	}
2263    }
2264}
2265
2266
2267$kernelversion = get_kernel_version();
2268
2269# generate a sequence of code that will splice in highlighting information
2270# using the s// operator.
2271for (my $k = 0; $k < @highlights; $k++) {
2272    my $pattern = $highlights[$k][0];
2273    my $result = $highlights[$k][1];
2274#   print STDERR "scanning pattern:$pattern, highlight:($result)\n";
2275    $dohighlight .=  "\$contents =~ s:$pattern:$result:gs;\n";
2276}
2277
2278# Read the file that maps relative names to absolute names for
2279# separate source and object directories and for shadow trees.
2280if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
2281	my ($relname, $absname);
2282	while(<SOURCE_MAP>) {
2283		chop();
2284		($relname, $absname) = (split())[0..1];
2285		$relname =~ s:^/+::;
2286		$source_map{$relname} = $absname;
2287	}
2288	close(SOURCE_MAP);
2289}
2290
2291if ($output_selection == OUTPUT_EXPORTED ||
2292    $output_selection == OUTPUT_INTERNAL) {
2293
2294    push(@export_file_list, @ARGV);
2295
2296    foreach (@export_file_list) {
2297	chomp;
2298	process_export_file($_);
2299    }
2300}
2301
2302foreach (@ARGV) {
2303    chomp;
2304    process_file($_);
2305}
2306if ($verbose && $errors) {
2307  print STDERR "$errors errors\n";
2308}
2309if ($verbose && $warnings) {
2310  print STDERR "$warnings warnings\n";
2311}
2312
2313if ($Werror && $warnings) {
2314    print STDERR "$warnings warnings as Errors\n";
2315    exit($warnings);
2316} else {
2317    exit($output_mode eq "none" ? 0 : $errors)
2318}
2319