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