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