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