xref: /linux/scripts/checkpatch.pl (revision 509d3f45847627f4c5cdce004c3ec79262b5239c)
1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3#
4# (c) 2001, Dave Jones. (the file handling bit)
5# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8# (c) 2010-2018 Joe Perches <joe@perches.com>
9
10use strict;
11use warnings;
12use POSIX;
13use File::Basename;
14use Cwd 'abs_path';
15use Term::ANSIColor qw(:constants);
16use Encode qw(decode encode);
17
18my $P = $0;
19my $D = dirname(abs_path($P));
20
21my $V = '0.32';
22
23use Getopt::Long qw(:config no_auto_abbrev);
24
25my $quiet = 0;
26my $verbose = 0;
27my %verbose_messages = ();
28my %verbose_emitted = ();
29my $tree = 1;
30my $chk_signoff = 1;
31my $chk_fixes_tag = 1;
32my $chk_patch = 1;
33my $tst_only;
34my $emacs = 0;
35my $terse = 0;
36my $showfile = 0;
37my $file = 0;
38my $git = 0;
39my %git_commits = ();
40my $check = 0;
41my $check_orig = 0;
42my $summary = 1;
43my $mailback = 0;
44my $summary_file = 0;
45my $show_types = 0;
46my $list_types = 0;
47my $fix = 0;
48my $fix_inplace = 0;
49my $root;
50my $gitroot = $ENV{'GIT_DIR'};
51$gitroot = ".git" if !defined($gitroot);
52my %debug;
53my %camelcase = ();
54my %use_type = ();
55my @use = ();
56my %ignore_type = ();
57my @ignore = ();
58my $help = 0;
59my $configuration_file = ".checkpatch.conf";
60my $max_line_length = 100;
61my $ignore_perl_version = 0;
62my $minimum_perl_version = 5.10.0;
63my $min_conf_desc_length = 4;
64my $spelling_file = "$D/spelling.txt";
65my $codespell = 0;
66my $codespellfile = "/usr/share/codespell/dictionary.txt";
67my $user_codespellfile = "";
68my $conststructsfile = "$D/const_structs.checkpatch";
69my $docsfile = "$D/../Documentation/dev-tools/checkpatch.rst";
70my $typedefsfile;
71my $color = "auto";
72my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
73# git output parsing needs US English output, so first set backtick child process LANGUAGE
74my $git_command ='export LANGUAGE=en_US.UTF-8; git';
75my $tabsize = 8;
76my ${CONFIG_} = "CONFIG_";
77
78my %maybe_linker_symbol; # for externs in c exceptions, when seen in *vmlinux.lds.h
79
80sub help {
81	my ($exitcode) = @_;
82
83	print << "EOM";
84Usage: $P [OPTION]... [FILE]...
85Version: $V
86
87Options:
88  -q, --quiet                quiet
89  -v, --verbose              verbose mode
90  --no-tree                  run without a kernel tree
91  --no-signoff               do not check for 'Signed-off-by' line
92  --no-fixes-tag             do not check for 'Fixes:' tag
93  --patch                    treat FILE as patchfile (default)
94  --emacs                    emacs compile window format
95  --terse                    one line per report
96  --showfile                 emit diffed file position, not input file position
97  -g, --git                  treat FILE as a single commit or git revision range
98                             single git commit with:
99                               <rev>
100                               <rev>^
101                               <rev>~n
102                             multiple git commits with:
103                               <rev1>..<rev2>
104                               <rev1>...<rev2>
105                               <rev>-<count>
106                             git merges are ignored
107  -f, --file                 treat FILE as regular source file
108  --subjective, --strict     enable more subjective tests
109  --list-types               list the possible message types
110  --types TYPE(,TYPE2...)    show only these comma separated message types
111  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
112  --show-types               show the specific message type in the output
113  --max-line-length=n        set the maximum line length, (default $max_line_length)
114                             if exceeded, warn on patches
115                             requires --strict for use with --file
116  --min-conf-desc-length=n   set the minimum description length for config symbols
117                             in lines, if shorter, warn (default $min_conf_desc_length)
118  --tab-size=n               set the number of spaces for tab (default $tabsize)
119  --root=PATH                PATH to the kernel tree root
120  --no-summary               suppress the per-file summary
121  --mailback                 only produce a report in case of warnings/errors
122  --summary-file             include the filename in summary
123  --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
124                             'values', 'possible', 'type', and 'attr' (default
125                             is all off)
126  --test-only=WORD           report only warnings/errors containing WORD
127                             literally
128  --fix                      EXPERIMENTAL - may create horrible results
129                             If correctable single-line errors exist, create
130                             "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
131                             with potential errors corrected to the preferred
132                             checkpatch style
133  --fix-inplace              EXPERIMENTAL - may create horrible results
134                             Is the same as --fix, but overwrites the input
135                             file.  It's your fault if there's no backup or git
136  --ignore-perl-version      override checking of perl version.  expect
137                             runtime errors.
138  --codespell                Use the codespell dictionary for spelling/typos
139                             (default:$codespellfile)
140  --codespellfile            Use this codespell dictionary
141  --typedefsfile             Read additional types from this file
142  --color[=WHEN]             Use colors 'always', 'never', or only when output
143                             is a terminal ('auto'). Default is 'auto'.
144  --kconfig-prefix=WORD      use WORD as a prefix for Kconfig symbols (default
145                             ${CONFIG_})
146  -h, --help, --version      display this help and exit
147
148When FILE is - read standard input.
149EOM
150
151	exit($exitcode);
152}
153
154my $DO_WHILE_0_ADVICE = q{
155   do {} while (0) advice is over-stated in a few situations:
156
157   The more obvious case is macros, like MODULE_PARM_DESC, invoked at
158   file-scope, where C disallows code (it must be in functions).  See
159   $exceptions if you have one to add by name.
160
161   More troublesome is declarative macros used at top of new scope,
162   like DECLARE_PER_CPU.  These might just compile with a do-while-0
163   wrapper, but would be incorrect.  Most of these are handled by
164   detecting struct,union,etc declaration primitives in $exceptions.
165
166   Theres also macros called inside an if (block), which "return" an
167   expression.  These cannot do-while, and need a ({}) wrapper.
168
169   Enjoy this qualification while we work to improve our heuristics.
170};
171
172sub uniq {
173	my %seen;
174	return grep { !$seen{$_}++ } @_;
175}
176
177sub list_types {
178	my ($exitcode) = @_;
179
180	my $count = 0;
181
182	local $/ = undef;
183
184	open(my $script, '<', abs_path($P)) or
185	    die "$P: Can't read '$P' $!\n";
186
187	my $text = <$script>;
188	close($script);
189
190	my %types = ();
191	# Also catch when type or level is passed through a variable
192	while ($text =~ /(?:(\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
193		if (defined($1)) {
194			if (exists($types{$2})) {
195				$types{$2} .= ",$1" if ($types{$2} ne $1);
196			} else {
197				$types{$2} = $1;
198			}
199		} else {
200			$types{$2} = "UNDETERMINED";
201		}
202	}
203
204	print("#\tMessage type\n\n");
205	if ($color) {
206		print(" ( Color coding: ");
207		print(RED . "ERROR" . RESET);
208		print(" | ");
209		print(YELLOW . "WARNING" . RESET);
210		print(" | ");
211		print(GREEN . "CHECK" . RESET);
212		print(" | ");
213		print("Multiple levels / Undetermined");
214		print(" )\n\n");
215	}
216
217	foreach my $type (sort keys %types) {
218		my $orig_type = $type;
219		if ($color) {
220			my $level = $types{$type};
221			if ($level eq "ERROR") {
222				$type = RED . $type . RESET;
223			} elsif ($level eq "WARN") {
224				$type = YELLOW . $type . RESET;
225			} elsif ($level eq "CHK") {
226				$type = GREEN . $type . RESET;
227			}
228		}
229		print(++$count . "\t" . $type . "\n");
230		if ($verbose && exists($verbose_messages{$orig_type})) {
231			my $message = $verbose_messages{$orig_type};
232			$message =~ s/\n/\n\t/g;
233			print("\t" . $message . "\n\n");
234		}
235	}
236
237	exit($exitcode);
238}
239
240my $conf = which_conf($configuration_file);
241if (-f $conf) {
242	my @conf_args;
243	open(my $conffile, '<', "$conf")
244	    or warn "$P: Can't find a readable $configuration_file file $!\n";
245
246	while (<$conffile>) {
247		my $line = $_;
248
249		$line =~ s/\s*\n?$//g;
250		$line =~ s/^\s*//g;
251		$line =~ s/\s+/ /g;
252
253		next if ($line =~ m/^\s*#/);
254		next if ($line =~ m/^\s*$/);
255
256		my @words = split(" ", $line);
257		foreach my $word (@words) {
258			last if ($word =~ m/^#/);
259			push (@conf_args, $word);
260		}
261	}
262	close($conffile);
263	unshift(@ARGV, @conf_args) if @conf_args;
264}
265
266sub load_docs {
267	open(my $docs, '<', "$docsfile")
268	    or warn "$P: Can't read the documentation file $docsfile $!\n";
269
270	my $type = '';
271	my $desc = '';
272	my $in_desc = 0;
273
274	while (<$docs>) {
275		chomp;
276		my $line = $_;
277		$line =~ s/\s+$//;
278
279		if ($line =~ /^\s*\*\*(.+)\*\*$/) {
280			if ($desc ne '') {
281				$verbose_messages{$type} = trim($desc);
282			}
283			$type = $1;
284			$desc = '';
285			$in_desc = 1;
286		} elsif ($in_desc) {
287			if ($line =~ /^(?:\s{4,}|$)/) {
288				$line =~ s/^\s{4}//;
289				$desc .= $line;
290				$desc .= "\n";
291			} else {
292				$verbose_messages{$type} = trim($desc);
293				$type = '';
294				$desc = '';
295				$in_desc = 0;
296			}
297		}
298	}
299
300	if ($desc ne '') {
301		$verbose_messages{$type} = trim($desc);
302	}
303	close($docs);
304}
305
306# Perl's Getopt::Long allows options to take optional arguments after a space.
307# Prevent --color by itself from consuming other arguments
308foreach (@ARGV) {
309	if ($_ eq "--color" || $_ eq "-color") {
310		$_ = "--color=$color";
311	}
312}
313
314GetOptions(
315	'q|quiet+'	=> \$quiet,
316	'v|verbose!'	=> \$verbose,
317	'tree!'		=> \$tree,
318	'signoff!'	=> \$chk_signoff,
319	'fixes-tag!'	=> \$chk_fixes_tag,
320	'patch!'	=> \$chk_patch,
321	'emacs!'	=> \$emacs,
322	'terse!'	=> \$terse,
323	'showfile!'	=> \$showfile,
324	'f|file!'	=> \$file,
325	'g|git!'	=> \$git,
326	'subjective!'	=> \$check,
327	'strict!'	=> \$check,
328	'ignore=s'	=> \@ignore,
329	'types=s'	=> \@use,
330	'show-types!'	=> \$show_types,
331	'list-types!'	=> \$list_types,
332	'max-line-length=i' => \$max_line_length,
333	'min-conf-desc-length=i' => \$min_conf_desc_length,
334	'tab-size=i'	=> \$tabsize,
335	'root=s'	=> \$root,
336	'summary!'	=> \$summary,
337	'mailback!'	=> \$mailback,
338	'summary-file!'	=> \$summary_file,
339	'fix!'		=> \$fix,
340	'fix-inplace!'	=> \$fix_inplace,
341	'ignore-perl-version!' => \$ignore_perl_version,
342	'debug=s'	=> \%debug,
343	'test-only=s'	=> \$tst_only,
344	'codespell!'	=> \$codespell,
345	'codespellfile=s'	=> \$user_codespellfile,
346	'typedefsfile=s'	=> \$typedefsfile,
347	'color=s'	=> \$color,
348	'no-color'	=> \$color,	#keep old behaviors of -nocolor
349	'nocolor'	=> \$color,	#keep old behaviors of -nocolor
350	'kconfig-prefix=s'	=> \${CONFIG_},
351	'h|help'	=> \$help,
352	'version'	=> \$help
353) or $help = 2;
354
355if ($user_codespellfile) {
356	# Use the user provided codespell file unconditionally
357	$codespellfile = $user_codespellfile;
358} elsif (!(-f $codespellfile)) {
359	# If /usr/share/codespell/dictionary.txt is not present, try to find it
360	# under codespell's install directory: <codespell_root>/data/dictionary.txt
361	if (($codespell || $help) && which("python3") ne "") {
362		my $python_codespell_dict = << "EOF";
363
364import os.path as op
365import codespell_lib
366codespell_dir = op.dirname(codespell_lib.__file__)
367codespell_file = op.join(codespell_dir, 'data', 'dictionary.txt')
368print(codespell_file, end='')
369EOF
370
371		my $codespell_dict = `python3 -c "$python_codespell_dict" 2> /dev/null`;
372		$codespellfile = $codespell_dict if (-f $codespell_dict);
373	}
374}
375
376# $help is 1 if either -h, --help or --version is passed as option - exitcode: 0
377# $help is 2 if invalid option is passed - exitcode: 1
378help($help - 1) if ($help);
379
380die "$P: --git cannot be used with --file or --fix\n" if ($git && ($file || $fix));
381die "$P: --verbose cannot be used with --terse\n" if ($verbose && $terse);
382
383if ($color =~ /^[01]$/) {
384	$color = !$color;
385} elsif ($color =~ /^always$/i) {
386	$color = 1;
387} elsif ($color =~ /^never$/i) {
388	$color = 0;
389} elsif ($color =~ /^auto$/i) {
390	$color = (-t STDOUT);
391} else {
392	die "$P: Invalid color mode: $color\n";
393}
394
395load_docs() if ($verbose);
396list_types(0) if ($list_types);
397
398$fix = 1 if ($fix_inplace);
399$check_orig = $check;
400
401my $exit = 0;
402
403my $perl_version_ok = 1;
404if ($^V && $^V lt $minimum_perl_version) {
405	$perl_version_ok = 0;
406	printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
407	exit(1) if (!$ignore_perl_version);
408}
409
410#if no filenames are given, push '-' to read patch from stdin
411if ($#ARGV < 0) {
412	push(@ARGV, '-');
413}
414
415# skip TAB size 1 to avoid additional checks on $tabsize - 1
416die "$P: Invalid TAB size: $tabsize\n" if ($tabsize < 2);
417
418sub hash_save_array_words {
419	my ($hashRef, $arrayRef) = @_;
420
421	my @array = split(/,/, join(',', @$arrayRef));
422	foreach my $word (@array) {
423		$word =~ s/\s*\n?$//g;
424		$word =~ s/^\s*//g;
425		$word =~ s/\s+/ /g;
426		$word =~ tr/[a-z]/[A-Z]/;
427
428		next if ($word =~ m/^\s*#/);
429		next if ($word =~ m/^\s*$/);
430
431		$hashRef->{$word}++;
432	}
433}
434
435sub hash_show_words {
436	my ($hashRef, $prefix) = @_;
437
438	if (keys %$hashRef) {
439		print "\nNOTE: $prefix message types:";
440		foreach my $word (sort keys %$hashRef) {
441			print " $word";
442		}
443		print "\n";
444	}
445}
446
447hash_save_array_words(\%ignore_type, \@ignore);
448hash_save_array_words(\%use_type, \@use);
449
450my $dbg_values = 0;
451my $dbg_possible = 0;
452my $dbg_type = 0;
453my $dbg_attr = 0;
454for my $key (keys %debug) {
455	## no critic
456	eval "\${dbg_$key} = '$debug{$key}';";
457	die "$@" if ($@);
458}
459
460my $rpt_cleaners = 0;
461
462if ($terse) {
463	$emacs = 1;
464	$quiet++;
465}
466
467if ($tree) {
468	if (defined $root) {
469		if (!top_of_kernel_tree($root)) {
470			die "$P: $root: --root does not point at a valid tree\n";
471		}
472	} else {
473		if (top_of_kernel_tree('.')) {
474			$root = '.';
475		} elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
476						top_of_kernel_tree($1)) {
477			$root = $1;
478		}
479	}
480
481	if (!defined $root) {
482		print "Must be run from the top-level dir. of a kernel tree\n";
483		exit(2);
484	}
485}
486
487my $emitted_corrupt = 0;
488
489our $Ident	= qr{
490			[A-Za-z_][A-Za-z\d_]*
491			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
492		}x;
493our $Storage	= qr{extern|static|asmlinkage};
494our $Sparse	= qr{
495			__user|
496			__kernel|
497			__force|
498			__iomem|
499			__must_check|
500			__kprobes|
501			__ref|
502			__refconst|
503			__refdata|
504			__rcu|
505			__private
506		}x;
507our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
508our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
509our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
510our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
511our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
512
513# Notes to $Attribute:
514# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
515our $Attribute	= qr{
516			const|
517			volatile|
518			__percpu|
519			__nocast|
520			__safe|
521			__bitwise|
522			__packed__|
523			__packed2__|
524			__naked|
525			__maybe_unused|
526			__always_unused|
527			__noreturn|
528			__used|
529			__cold|
530			__pure|
531			__noclone|
532			__deprecated|
533			__read_mostly|
534			__ro_after_init|
535			__kprobes|
536			$InitAttribute|
537			__aligned\s*\(.*\)|
538			____cacheline_aligned|
539			____cacheline_aligned_in_smp|
540			____cacheline_internodealigned_in_smp|
541			__weak|
542			__alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)
543		  }x;
544our $Modifier;
545our $Inline	= qr{inline|__always_inline|noinline|__inline|__inline__};
546our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
547our $Lval	= qr{$Ident(?:$Member)*};
548
549our $Int_type	= qr{(?i)llu|ull|ll|lu|ul|l|u};
550our $Binary	= qr{(?i)0b[01]+$Int_type?};
551our $Hex	= qr{(?i)0x[0-9a-f]+$Int_type?};
552our $Int	= qr{[0-9]+$Int_type?};
553our $Octal	= qr{0[0-7]+$Int_type?};
554our $String	= qr{(?:\b[Lu])?"[X\t]*"};
555our $Float_hex	= qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
556our $Float_dec	= qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
557our $Float_int	= qr{(?i)[0-9]+e-?[0-9]+[fl]?};
558our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
559our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
560our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
561our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
562our $Arithmetic = qr{\+|-|\*|\/|%};
563our $Operators	= qr{
564			<=|>=|==|!=|
565			=>|->|<<|>>|<|>|!|~|
566			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
567		  }x;
568
569our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
570
571our $BasicType;
572our $NonptrType;
573our $NonptrTypeMisordered;
574our $NonptrTypeWithAttr;
575our $Type;
576our $TypeMisordered;
577our $Declare;
578our $DeclareMisordered;
579
580our $NON_ASCII_UTF8	= qr{
581	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
582	|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
583	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
584	|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
585	|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
586	| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
587	|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
588}x;
589
590our $UTF8	= qr{
591	[\x09\x0A\x0D\x20-\x7E]              # ASCII
592	| $NON_ASCII_UTF8
593}x;
594
595our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
596our $typeOtherOSTypedefs = qr{(?x:
597	u_(?:char|short|int|long) |          # bsd
598	u(?:nchar|short|int|long)            # sysv
599)};
600our $typeKernelTypedefs = qr{(?x:
601	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
602	atomic_t
603)};
604our $typeStdioTypedefs = qr{(?x:
605	FILE
606)};
607our $typeTypedefs = qr{(?x:
608	$typeC99Typedefs\b|
609	$typeOtherOSTypedefs\b|
610	$typeKernelTypedefs\b|
611	$typeStdioTypedefs\b
612)};
613
614our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
615
616our $logFunctions = qr{(?x:
617	printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
618	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
619	TP_printk|
620	WARN(?:_RATELIMIT|_ONCE|)|
621	panic|
622	MODULE_[A-Z_]+|
623	seq_vprintf|seq_printf|seq_puts
624)};
625
626our $allocFunctions = qr{(?x:
627	(?:(?:devm_)?
628		(?:kv|k|v)[czm]alloc(?:_array)?(?:_node)? |
629		kstrdup(?:_const)? |
630		kmemdup(?:_nul)?) |
631	(?:\w+)?alloc_skb(?:_ip_align)? |
632				# dev_alloc_skb/netdev_alloc_skb, et al
633	dma_alloc_coherent
634)};
635
636our $signature_tags = qr{(?xi:
637	Signed-off-by:|
638	Co-developed-by:|
639	Acked-by:|
640	Tested-by:|
641	Reviewed-by:|
642	Reported-by:|
643	Suggested-by:|
644	To:|
645	Cc:
646)};
647
648our @link_tags = qw(Link Closes);
649
650#Create a search and print patterns for all these strings to be used directly below
651our $link_tags_search = "";
652our $link_tags_print = "";
653foreach my $entry (@link_tags) {
654	if ($link_tags_search ne "") {
655		$link_tags_search .= '|';
656		$link_tags_print .= ' or ';
657	}
658	$entry .= ':';
659	$link_tags_search .= $entry;
660	$link_tags_print .= "'$entry'";
661}
662$link_tags_search = "(?:${link_tags_search})";
663
664our $tracing_logging_tags = qr{(?xi:
665	[=-]*> |
666	<[=-]* |
667	\[ |
668	\] |
669	start |
670	called |
671	entered |
672	entry |
673	enter |
674	in |
675	inside |
676	here |
677	begin |
678	exit |
679	end |
680	done |
681	leave |
682	completed |
683	out |
684	return |
685	[\.\!:\s]*
686)};
687
688# Device ID types like found in include/linux/mod_devicetable.h.
689our $dev_id_types = qr{\b[a-z]\w*_device_id\b};
690
691sub edit_distance_min {
692	my (@arr) = @_;
693	my $len = scalar @arr;
694	if ((scalar @arr) < 1) {
695		# if underflow, return
696		return;
697	}
698	my $min = $arr[0];
699	for my $i (0 .. ($len-1)) {
700		if ($arr[$i] < $min) {
701			$min = $arr[$i];
702		}
703	}
704	return $min;
705}
706
707sub get_edit_distance {
708	my ($str1, $str2) = @_;
709	$str1 = lc($str1);
710	$str2 = lc($str2);
711	$str1 =~ s/-//g;
712	$str2 =~ s/-//g;
713	my $len1 = length($str1);
714	my $len2 = length($str2);
715	# two dimensional array storing minimum edit distance
716	my @distance;
717	for my $i (0 .. $len1) {
718		for my $j (0 .. $len2) {
719			if ($i == 0) {
720				$distance[$i][$j] = $j;
721			} elsif ($j == 0) {
722				$distance[$i][$j] = $i;
723			} elsif (substr($str1, $i-1, 1) eq substr($str2, $j-1, 1)) {
724				$distance[$i][$j] = $distance[$i - 1][$j - 1];
725			} else {
726				my $dist1 = $distance[$i][$j - 1]; #insert distance
727				my $dist2 = $distance[$i - 1][$j]; # remove
728				my $dist3 = $distance[$i - 1][$j - 1]; #replace
729				$distance[$i][$j] = 1 + edit_distance_min($dist1, $dist2, $dist3);
730			}
731		}
732	}
733	return $distance[$len1][$len2];
734}
735
736sub find_standard_signature {
737	my ($sign_off) = @_;
738	my @standard_signature_tags = (
739		'Signed-off-by:', 'Co-developed-by:', 'Acked-by:', 'Tested-by:',
740		'Reviewed-by:', 'Reported-by:', 'Suggested-by:'
741	);
742	foreach my $signature (@standard_signature_tags) {
743		return $signature if (get_edit_distance($sign_off, $signature) <= 2);
744	}
745
746	return "";
747}
748
749our $obsolete_archives = qr{(?xi:
750	\Qfreedesktop.org/archives/dri-devel\E |
751	\Qlists.infradead.org\E |
752	\Qlkml.org\E |
753	\Qmail-archive.com\E |
754	\Qmailman.alsa-project.org/pipermail\E |
755	\Qmarc.info\E |
756	\Qozlabs.org/pipermail\E |
757	\Qspinics.net\E
758)};
759
760our @typeListMisordered = (
761	qr{char\s+(?:un)?signed},
762	qr{int\s+(?:(?:un)?signed\s+)?short\s},
763	qr{int\s+short(?:\s+(?:un)?signed)},
764	qr{short\s+int(?:\s+(?:un)?signed)},
765	qr{(?:un)?signed\s+int\s+short},
766	qr{short\s+(?:un)?signed},
767	qr{long\s+int\s+(?:un)?signed},
768	qr{int\s+long\s+(?:un)?signed},
769	qr{long\s+(?:un)?signed\s+int},
770	qr{int\s+(?:un)?signed\s+long},
771	qr{int\s+(?:un)?signed},
772	qr{int\s+long\s+long\s+(?:un)?signed},
773	qr{long\s+long\s+int\s+(?:un)?signed},
774	qr{long\s+long\s+(?:un)?signed\s+int},
775	qr{long\s+long\s+(?:un)?signed},
776	qr{long\s+(?:un)?signed},
777);
778
779our @typeList = (
780	qr{void},
781	qr{(?:(?:un)?signed\s+)?char},
782	qr{(?:(?:un)?signed\s+)?short\s+int},
783	qr{(?:(?:un)?signed\s+)?short},
784	qr{(?:(?:un)?signed\s+)?int},
785	qr{(?:(?:un)?signed\s+)?long\s+int},
786	qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
787	qr{(?:(?:un)?signed\s+)?long\s+long},
788	qr{(?:(?:un)?signed\s+)?long},
789	qr{(?:un)?signed},
790	qr{float},
791	qr{double},
792	qr{bool},
793	qr{struct\s+$Ident},
794	qr{union\s+$Ident},
795	qr{enum\s+$Ident},
796	qr{${Ident}_t},
797	qr{${Ident}_handler},
798	qr{${Ident}_handler_fn},
799	@typeListMisordered,
800);
801
802our $C90_int_types = qr{(?x:
803	long\s+long\s+int\s+(?:un)?signed|
804	long\s+long\s+(?:un)?signed\s+int|
805	long\s+long\s+(?:un)?signed|
806	(?:(?:un)?signed\s+)?long\s+long\s+int|
807	(?:(?:un)?signed\s+)?long\s+long|
808	int\s+long\s+long\s+(?:un)?signed|
809	int\s+(?:(?:un)?signed\s+)?long\s+long|
810
811	long\s+int\s+(?:un)?signed|
812	long\s+(?:un)?signed\s+int|
813	long\s+(?:un)?signed|
814	(?:(?:un)?signed\s+)?long\s+int|
815	(?:(?:un)?signed\s+)?long|
816	int\s+long\s+(?:un)?signed|
817	int\s+(?:(?:un)?signed\s+)?long|
818
819	int\s+(?:un)?signed|
820	(?:(?:un)?signed\s+)?int
821)};
822
823our @typeListFile = ();
824our @typeListWithAttr = (
825	@typeList,
826	qr{struct\s+$InitAttribute\s+$Ident},
827	qr{union\s+$InitAttribute\s+$Ident},
828);
829
830our @modifierList = (
831	qr{fastcall},
832);
833our @modifierListFile = ();
834
835our @mode_permission_funcs = (
836	["module_param", 3],
837	["module_param_(?:array|named|string)", 4],
838	["module_param_array_named", 5],
839	["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
840	["proc_create(?:_data|)", 2],
841	["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
842	["IIO_DEV_ATTR_[A-Z_]+", 1],
843	["SENSOR_(?:DEVICE_|)ATTR_2", 2],
844	["SENSOR_TEMPLATE(?:_2|)", 3],
845	["__ATTR", 2],
846);
847
848my $word_pattern = '\b[A-Z]?[a-z]{2,}\b';
849
850#Create a search pattern for all these functions to speed up a loop below
851our $mode_perms_search = "";
852foreach my $entry (@mode_permission_funcs) {
853	$mode_perms_search .= '|' if ($mode_perms_search ne "");
854	$mode_perms_search .= $entry->[0];
855}
856$mode_perms_search = "(?:${mode_perms_search})";
857
858our %deprecated_apis = (
859	"kmap"					=> "kmap_local_page",
860	"kunmap"				=> "kunmap_local",
861	"kmap_atomic"				=> "kmap_local_page",
862	"kunmap_atomic"				=> "kunmap_local",
863	#These should be enough to drive away new IDR users
864	"DEFINE_IDR"				=> "DEFINE_XARRAY",
865	"idr_init"				=> "xa_init",
866	"idr_init_base"				=> "xa_init_flags"
867);
868
869#Create a search pattern for all these strings to speed up a loop below
870our $deprecated_apis_search = "";
871foreach my $entry (keys %deprecated_apis) {
872	$deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
873	$deprecated_apis_search .= $entry;
874}
875$deprecated_apis_search = "(?:${deprecated_apis_search})";
876
877our $mode_perms_world_writable = qr{
878	S_IWUGO		|
879	S_IWOTH		|
880	S_IRWXUGO	|
881	S_IALLUGO	|
882	0[0-7][0-7][2367]
883}x;
884
885our %mode_permission_string_types = (
886	"S_IRWXU" => 0700,
887	"S_IRUSR" => 0400,
888	"S_IWUSR" => 0200,
889	"S_IXUSR" => 0100,
890	"S_IRWXG" => 0070,
891	"S_IRGRP" => 0040,
892	"S_IWGRP" => 0020,
893	"S_IXGRP" => 0010,
894	"S_IRWXO" => 0007,
895	"S_IROTH" => 0004,
896	"S_IWOTH" => 0002,
897	"S_IXOTH" => 0001,
898	"S_IRWXUGO" => 0777,
899	"S_IRUGO" => 0444,
900	"S_IWUGO" => 0222,
901	"S_IXUGO" => 0111,
902);
903
904#Create a search pattern for all these strings to speed up a loop below
905our $mode_perms_string_search = "";
906foreach my $entry (keys %mode_permission_string_types) {
907	$mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
908	$mode_perms_string_search .= $entry;
909}
910our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
911our $multi_mode_perms_string_search = qr{
912	${single_mode_perms_string_search}
913	(?:\s*\|\s*${single_mode_perms_string_search})*
914}x;
915
916sub perms_to_octal {
917	my ($string) = @_;
918
919	return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
920
921	my $val = "";
922	my $oval = "";
923	my $to = 0;
924	my $curpos = 0;
925	my $lastpos = 0;
926	while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
927		$curpos = pos($string);
928		my $match = $2;
929		my $omatch = $1;
930		last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
931		$lastpos = $curpos;
932		$to |= $mode_permission_string_types{$match};
933		$val .= '\s*\|\s*' if ($val ne "");
934		$val .= $match;
935		$oval .= $omatch;
936	}
937	$oval =~ s/^\s*\|\s*//;
938	$oval =~ s/\s*\|\s*$//;
939	return sprintf("%04o", $to);
940}
941
942our $allowed_asm_includes = qr{(?x:
943	irq|
944	memory|
945	time|
946	reboot
947)};
948# memory.h: ARM has a custom one
949
950# Load common spelling mistakes and build regular expression list.
951my $misspellings;
952my %spelling_fix;
953
954if (open(my $spelling, '<', $spelling_file)) {
955	while (<$spelling>) {
956		my $line = $_;
957
958		$line =~ s/\s*\n?$//g;
959		$line =~ s/^\s*//g;
960
961		next if ($line =~ m/^\s*#/);
962		next if ($line =~ m/^\s*$/);
963
964		my ($suspect, $fix) = split(/\|\|/, $line);
965
966		$spelling_fix{$suspect} = $fix;
967	}
968	close($spelling);
969} else {
970	warn "No typos will be found - file '$spelling_file': $!\n";
971}
972
973if ($codespell) {
974	if (open(my $spelling, '<', $codespellfile)) {
975		while (<$spelling>) {
976			my $line = $_;
977
978			$line =~ s/\s*\n?$//g;
979			$line =~ s/^\s*//g;
980
981			next if ($line =~ m/^\s*#/);
982			next if ($line =~ m/^\s*$/);
983			next if ($line =~ m/, disabled/i);
984
985			$line =~ s/,.*$//;
986
987			my ($suspect, $fix) = split(/->/, $line);
988
989			$spelling_fix{$suspect} = $fix;
990		}
991		close($spelling);
992	} else {
993		warn "No codespell typos will be found - file '$codespellfile': $!\n";
994	}
995}
996
997$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
998
999sub read_words {
1000	my ($wordsRef, $file) = @_;
1001
1002	if (open(my $words, '<', $file)) {
1003		while (<$words>) {
1004			my $line = $_;
1005
1006			$line =~ s/\s*\n?$//g;
1007			$line =~ s/^\s*//g;
1008
1009			next if ($line =~ m/^\s*#/);
1010			next if ($line =~ m/^\s*$/);
1011			if ($line =~ /\s/) {
1012				print("$file: '$line' invalid - ignored\n");
1013				next;
1014			}
1015
1016			$$wordsRef .= '|' if (defined $$wordsRef);
1017			$$wordsRef .= $line;
1018		}
1019		close($file);
1020		return 1;
1021	}
1022
1023	return 0;
1024}
1025
1026my $const_structs;
1027if (show_type("CONST_STRUCT")) {
1028	read_words(\$const_structs, $conststructsfile)
1029	    or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
1030}
1031
1032if (defined($typedefsfile)) {
1033	my $typeOtherTypedefs;
1034	read_words(\$typeOtherTypedefs, $typedefsfile)
1035	    or warn "No additional types will be considered - file '$typedefsfile': $!\n";
1036	$typeTypedefs .= '|' . $typeOtherTypedefs if (defined $typeOtherTypedefs);
1037}
1038
1039sub build_types {
1040	my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
1041	my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
1042	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
1043	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
1044	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
1045	$BasicType	= qr{
1046				(?:$typeTypedefs\b)|
1047				(?:${all}\b)
1048		}x;
1049	$NonptrType	= qr{
1050			(?:$Modifier\s+|const\s+)*
1051			(?:
1052				(?:typeof|__typeof__)\s*\([^\)]*\)|
1053				(?:$typeTypedefs\b)|
1054				(?:${all}\b)
1055			)
1056			(?:\s+$Modifier|\s+const)*
1057		  }x;
1058	$NonptrTypeMisordered	= qr{
1059			(?:$Modifier\s+|const\s+)*
1060			(?:
1061				(?:${Misordered}\b)
1062			)
1063			(?:\s+$Modifier|\s+const)*
1064		  }x;
1065	$NonptrTypeWithAttr	= qr{
1066			(?:$Modifier\s+|const\s+)*
1067			(?:
1068				(?:typeof|__typeof__)\s*\([^\)]*\)|
1069				(?:$typeTypedefs\b)|
1070				(?:${allWithAttr}\b)
1071			)
1072			(?:\s+$Modifier|\s+const)*
1073		  }x;
1074	$Type	= qr{
1075			$NonptrType
1076			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1077			(?:\s+$Inline|\s+$Modifier)*
1078		  }x;
1079	$TypeMisordered	= qr{
1080			$NonptrTypeMisordered
1081			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+){0,4}
1082			(?:\s+$Inline|\s+$Modifier)*
1083		  }x;
1084	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
1085	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
1086}
1087build_types();
1088
1089our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
1090
1091# Using $balanced_parens, $LvalOrFunc, or $FuncArg
1092# requires at least perl version v5.10.0
1093# Any use must be runtime checked with $^V
1094
1095our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
1096our $LvalOrFunc	= qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
1097our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
1098
1099our $declaration_macros = qr{(?x:
1100	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
1101	(?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
1102	(?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(|
1103	(?:$Storage\s+)?(?:XA_STATE|XA_STATE_ORDER)\s*\(
1104)};
1105
1106our %allow_repeated_words = (
1107	add => '',
1108	added => '',
1109	bad => '',
1110	be => '',
1111);
1112
1113sub deparenthesize {
1114	my ($string) = @_;
1115	return "" if (!defined($string));
1116
1117	while ($string =~ /^\s*\(.*\)\s*$/) {
1118		$string =~ s@^\s*\(\s*@@;
1119		$string =~ s@\s*\)\s*$@@;
1120	}
1121
1122	$string =~ s@\s+@ @g;
1123
1124	return $string;
1125}
1126
1127sub seed_camelcase_file {
1128	my ($file) = @_;
1129
1130	return if (!(-f $file));
1131
1132	local $/;
1133
1134	open(my $include_file, '<', "$file")
1135	    or warn "$P: Can't read '$file' $!\n";
1136	my $text = <$include_file>;
1137	close($include_file);
1138
1139	my @lines = split('\n', $text);
1140
1141	foreach my $line (@lines) {
1142		next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
1143		if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
1144			$camelcase{$1} = 1;
1145		} elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
1146			$camelcase{$1} = 1;
1147		} elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
1148			$camelcase{$1} = 1;
1149		}
1150	}
1151}
1152
1153our %maintained_status = ();
1154
1155sub is_maintained_obsolete {
1156	my ($filename) = @_;
1157
1158	return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
1159
1160	if (!exists($maintained_status{$filename})) {
1161		$maintained_status{$filename} = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
1162	}
1163
1164	return $maintained_status{$filename} =~ /obsolete/i;
1165}
1166
1167sub is_SPDX_License_valid {
1168	my ($license) = @_;
1169
1170	return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
1171
1172	my $root_path = abs_path($root);
1173	my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
1174	return 0 if ($status ne "");
1175	return 1;
1176}
1177
1178my $camelcase_seeded = 0;
1179sub seed_camelcase_includes {
1180	return if ($camelcase_seeded);
1181
1182	my $files;
1183	my $camelcase_cache = "";
1184	my @include_files = ();
1185
1186	$camelcase_seeded = 1;
1187
1188	if (-e "$gitroot") {
1189		my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
1190		chomp $git_last_include_commit;
1191		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
1192	} else {
1193		my $last_mod_date = 0;
1194		$files = `find $root/include -name "*.h"`;
1195		@include_files = split('\n', $files);
1196		foreach my $file (@include_files) {
1197			my $date = POSIX::strftime("%Y%m%d%H%M",
1198						   localtime((stat $file)[9]));
1199			$last_mod_date = $date if ($last_mod_date < $date);
1200		}
1201		$camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
1202	}
1203
1204	if ($camelcase_cache ne "" && -f $camelcase_cache) {
1205		open(my $camelcase_file, '<', "$camelcase_cache")
1206		    or warn "$P: Can't read '$camelcase_cache' $!\n";
1207		while (<$camelcase_file>) {
1208			chomp;
1209			$camelcase{$_} = 1;
1210		}
1211		close($camelcase_file);
1212
1213		return;
1214	}
1215
1216	if (-e "$gitroot") {
1217		$files = `${git_command} ls-files "include/*.h"`;
1218		@include_files = split('\n', $files);
1219	}
1220
1221	foreach my $file (@include_files) {
1222		seed_camelcase_file($file);
1223	}
1224
1225	if ($camelcase_cache ne "") {
1226		unlink glob ".checkpatch-camelcase.*";
1227		open(my $camelcase_file, '>', "$camelcase_cache")
1228		    or warn "$P: Can't write '$camelcase_cache' $!\n";
1229		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
1230			print $camelcase_file ("$_\n");
1231		}
1232		close($camelcase_file);
1233	}
1234}
1235
1236sub git_is_single_file {
1237	my ($filename) = @_;
1238
1239	return 0 if ((which("git") eq "") || !(-e "$gitroot"));
1240
1241	my $output = `${git_command} ls-files -- $filename 2>/dev/null`;
1242	my $count = $output =~ tr/\n//;
1243	return $count eq 1 && $output =~ m{^${filename}$};
1244}
1245
1246sub git_commit_info {
1247	my ($commit, $id, $desc) = @_;
1248
1249	return ($id, $desc) if ((which("git") eq "") || !(-e "$gitroot"));
1250
1251	my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
1252	$output =~ s/^\s*//gm;
1253	my @lines = split("\n", $output);
1254
1255	return ($id, $desc) if ($#lines < 0);
1256
1257	if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
1258# Maybe one day convert this block of bash into something that returns
1259# all matching commit ids, but it's very slow...
1260#
1261#		echo "checking commits $1..."
1262#		git rev-list --remotes | grep -i "^$1" |
1263#		while read line ; do
1264#		    git log --format='%H %s' -1 $line |
1265#		    echo "commit $(cut -c 1-12,41-)"
1266#		done
1267	} elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./ ||
1268		 $lines[0] =~ /^fatal: bad object $commit/) {
1269		$id = undef;
1270	} else {
1271		$id = substr($lines[0], 0, 12);
1272		$desc = substr($lines[0], 41);
1273	}
1274
1275	return ($id, $desc);
1276}
1277
1278$chk_signoff = 0 if ($file);
1279$chk_fixes_tag = 0 if ($file);
1280
1281my @rawlines = ();
1282my @lines = ();
1283my @fixed = ();
1284my @fixed_inserted = ();
1285my @fixed_deleted = ();
1286my $fixlinenr = -1;
1287
1288# If input is git commits, extract all commits from the commit expressions.
1289# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1290die "$P: No git repository found\n" if ($git && !-e "$gitroot");
1291
1292if ($git) {
1293	my @commits = ();
1294	foreach my $commit_expr (@ARGV) {
1295		my $git_range;
1296		if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1297			$git_range = "-$2 $1";
1298		} elsif ($commit_expr =~ m/\.\./) {
1299			$git_range = "$commit_expr";
1300		} else {
1301			$git_range = "-1 $commit_expr";
1302		}
1303		my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1304		foreach my $line (split(/\n/, $lines)) {
1305			$line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1306			next if (!defined($1) || !defined($2));
1307			my $sha1 = $1;
1308			my $subject = $2;
1309			unshift(@commits, $sha1);
1310			$git_commits{$sha1} = $subject;
1311		}
1312	}
1313	die "$P: no git commits after extraction!\n" if (@commits == 0);
1314	@ARGV = @commits;
1315}
1316
1317my $vname;
1318$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1319for my $filename (@ARGV) {
1320	my $FILE;
1321	my $is_git_file = git_is_single_file($filename);
1322	my $oldfile = $file;
1323	$file = 1 if ($is_git_file);
1324	if ($git) {
1325		open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1326			die "$P: $filename: git format-patch failed - $!\n";
1327	} elsif ($file) {
1328		open($FILE, '-|', "diff -u /dev/null $filename") ||
1329			die "$P: $filename: diff failed - $!\n";
1330	} elsif ($filename eq '-') {
1331		open($FILE, '<&STDIN');
1332	} else {
1333		open($FILE, '<', "$filename") ||
1334			die "$P: $filename: open failed - $!\n";
1335	}
1336	if ($filename eq '-') {
1337		$vname = 'Your patch';
1338	} elsif ($git) {
1339		$vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1340	} else {
1341		$vname = $filename;
1342	}
1343	while (<$FILE>) {
1344		chomp;
1345		push(@rawlines, $_);
1346		$vname = qq("$1") if ($filename eq '-' && $_ =~ m/^Subject:\s+(.+)/i);
1347	}
1348	close($FILE);
1349
1350	if ($#ARGV > 0 && $quiet == 0) {
1351		print '-' x length($vname) . "\n";
1352		print "$vname\n";
1353		print '-' x length($vname) . "\n";
1354	}
1355
1356	if (!process($filename)) {
1357		$exit = 1;
1358	}
1359	@rawlines = ();
1360	@lines = ();
1361	@fixed = ();
1362	@fixed_inserted = ();
1363	@fixed_deleted = ();
1364	$fixlinenr = -1;
1365	@modifierListFile = ();
1366	@typeListFile = ();
1367	build_types();
1368	$file = $oldfile if ($is_git_file);
1369}
1370
1371if (!$quiet) {
1372	hash_show_words(\%use_type, "Used");
1373	hash_show_words(\%ignore_type, "Ignored");
1374
1375	if (!$perl_version_ok) {
1376		print << "EOM"
1377
1378NOTE: perl $^V is not modern enough to detect all possible issues.
1379      An upgrade to at least perl $minimum_perl_version is suggested.
1380EOM
1381	}
1382	if ($exit) {
1383		print << "EOM"
1384
1385NOTE: If any of the errors are false positives, please report
1386      them to the maintainer, see CHECKPATCH in MAINTAINERS.
1387EOM
1388	}
1389}
1390
1391exit($exit);
1392
1393sub top_of_kernel_tree {
1394	my ($root) = @_;
1395
1396	my @tree_check = (
1397		"COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1398		"README", "Documentation", "arch", "include", "drivers",
1399		"fs", "init", "ipc", "kernel", "lib", "scripts",
1400	);
1401
1402	foreach my $check (@tree_check) {
1403		if (! -e $root . '/' . $check) {
1404			return 0;
1405		}
1406	}
1407	return 1;
1408}
1409
1410sub parse_email {
1411	my ($formatted_email) = @_;
1412
1413	my $name = "";
1414	my $quoted = "";
1415	my $name_comment = "";
1416	my $address = "";
1417	my $comment = "";
1418
1419	if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1420		$name = $1;
1421		$address = $2;
1422		$comment = $3 if defined $3;
1423	} elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1424		$address = $1;
1425		$comment = $2 if defined $2;
1426	} elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1427		$address = $1;
1428		$comment = $2 if defined $2;
1429		$formatted_email =~ s/\Q$address\E.*$//;
1430		$name = $formatted_email;
1431		$name = trim($name);
1432		$name =~ s/^\"|\"$//g;
1433		# If there's a name left after stripping spaces and
1434		# leading quotes, and the address doesn't have both
1435		# leading and trailing angle brackets, the address
1436		# is invalid. ie:
1437		#   "joe smith joe@smith.com" bad
1438		#   "joe smith <joe@smith.com" bad
1439		if ($name ne "" && $address !~ /^<[^>]+>$/) {
1440			$name = "";
1441			$address = "";
1442			$comment = "";
1443		}
1444	}
1445
1446	# Extract comments from names excluding quoted parts
1447	# "John D. (Doe)" - Do not extract
1448	if ($name =~ s/\"(.+)\"//) {
1449		$quoted = $1;
1450	}
1451	while ($name =~ s/\s*($balanced_parens)\s*/ /) {
1452		$name_comment .= trim($1);
1453	}
1454	$name =~ s/^[ \"]+|[ \"]+$//g;
1455	$name = trim("$quoted $name");
1456
1457	$address = trim($address);
1458	$address =~ s/^\<|\>$//g;
1459	$comment = trim($comment);
1460
1461	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1462		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1463		$name = "\"$name\"";
1464	}
1465
1466	return ($name, $name_comment, $address, $comment);
1467}
1468
1469sub format_email {
1470	my ($name, $name_comment, $address, $comment) = @_;
1471
1472	my $formatted_email;
1473
1474	$name =~ s/^[ \"]+|[ \"]+$//g;
1475	$address = trim($address);
1476	$address =~ s/(?:\.|\,|\")+$//; ##trailing commas, dots or quotes
1477
1478	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1479		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1480		$name = "\"$name\"";
1481	}
1482
1483	$name_comment = trim($name_comment);
1484	$name_comment = " $name_comment" if ($name_comment ne "");
1485	$comment = trim($comment);
1486	$comment = " $comment" if ($comment ne "");
1487
1488	if ("$name" eq "") {
1489		$formatted_email = "$address";
1490	} else {
1491		$formatted_email = "$name$name_comment <$address>";
1492	}
1493	$formatted_email .= "$comment";
1494	return $formatted_email;
1495}
1496
1497sub reformat_email {
1498	my ($email) = @_;
1499
1500	my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
1501	return format_email($email_name, $name_comment, $email_address, $comment);
1502}
1503
1504sub same_email_addresses {
1505	my ($email1, $email2) = @_;
1506
1507	my ($email1_name, $name1_comment, $email1_address, $comment1) = parse_email($email1);
1508	my ($email2_name, $name2_comment, $email2_address, $comment2) = parse_email($email2);
1509
1510	return $email1_name eq $email2_name &&
1511	       $email1_address eq $email2_address &&
1512	       $name1_comment eq $name2_comment &&
1513	       $comment1 eq $comment2;
1514}
1515
1516sub which {
1517	my ($bin) = @_;
1518
1519	foreach my $path (split(/:/, $ENV{PATH})) {
1520		if (-e "$path/$bin") {
1521			return "$path/$bin";
1522		}
1523	}
1524
1525	return "";
1526}
1527
1528sub which_conf {
1529	my ($conf) = @_;
1530
1531	foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1532		if (-e "$path/$conf") {
1533			return "$path/$conf";
1534		}
1535	}
1536
1537	return "";
1538}
1539
1540sub expand_tabs {
1541	my ($str) = @_;
1542
1543	my $res = '';
1544	my $n = 0;
1545	for my $c (split(//, $str)) {
1546		if ($c eq "\t") {
1547			$res .= ' ';
1548			$n++;
1549			for (; ($n % $tabsize) != 0; $n++) {
1550				$res .= ' ';
1551			}
1552			next;
1553		}
1554		$res .= $c;
1555		$n++;
1556	}
1557
1558	return $res;
1559}
1560sub copy_spacing {
1561	(my $res = shift) =~ tr/\t/ /c;
1562	return $res;
1563}
1564
1565sub line_stats {
1566	my ($line) = @_;
1567
1568	# Drop the diff line leader and expand tabs
1569	$line =~ s/^.//;
1570	$line = expand_tabs($line);
1571
1572	# Pick the indent from the front of the line.
1573	my ($white) = ($line =~ /^(\s*)/);
1574
1575	return (length($line), length($white));
1576}
1577
1578my $sanitise_quote = '';
1579
1580sub sanitise_line_reset {
1581	my ($in_comment) = @_;
1582
1583	if ($in_comment) {
1584		$sanitise_quote = '*/';
1585	} else {
1586		$sanitise_quote = '';
1587	}
1588}
1589sub sanitise_line {
1590	my ($line) = @_;
1591
1592	my $res = '';
1593	my $l = '';
1594
1595	my $qlen = 0;
1596	my $off = 0;
1597	my $c;
1598
1599	# Always copy over the diff marker.
1600	$res = substr($line, 0, 1);
1601
1602	for ($off = 1; $off < length($line); $off++) {
1603		$c = substr($line, $off, 1);
1604
1605		# Comments we are whacking completely including the begin
1606		# and end, all to $;.
1607		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1608			$sanitise_quote = '*/';
1609
1610			substr($res, $off, 2, "$;$;");
1611			$off++;
1612			next;
1613		}
1614		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1615			$sanitise_quote = '';
1616			substr($res, $off, 2, "$;$;");
1617			$off++;
1618			next;
1619		}
1620		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1621			$sanitise_quote = '//';
1622
1623			substr($res, $off, 2, $sanitise_quote);
1624			$off++;
1625			next;
1626		}
1627
1628		# A \ in a string means ignore the next character.
1629		if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1630		    $c eq "\\") {
1631			substr($res, $off, 2, 'XX');
1632			$off++;
1633			next;
1634		}
1635		# Regular quotes.
1636		if ($c eq "'" || $c eq '"') {
1637			if ($sanitise_quote eq '') {
1638				$sanitise_quote = $c;
1639
1640				substr($res, $off, 1, $c);
1641				next;
1642			} elsif ($sanitise_quote eq $c) {
1643				$sanitise_quote = '';
1644			}
1645		}
1646
1647		#print "c<$c> SQ<$sanitise_quote>\n";
1648		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1649			substr($res, $off, 1, $;);
1650		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1651			substr($res, $off, 1, $;);
1652		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1653			substr($res, $off, 1, 'X');
1654		} else {
1655			substr($res, $off, 1, $c);
1656		}
1657	}
1658
1659	if ($sanitise_quote eq '//') {
1660		$sanitise_quote = '';
1661	}
1662
1663	# The pathname on a #include may be surrounded by '<' and '>'.
1664	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1665		my $clean = 'X' x length($1);
1666		$res =~ s@\<.*\>@<$clean>@;
1667
1668	# The whole of a #error is a string.
1669	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1670		my $clean = 'X' x length($1);
1671		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1672	}
1673
1674	if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1675		my $match = $1;
1676		$res =~ s/\Q$match\E/"$;" x length($match)/e;
1677	}
1678
1679	return $res;
1680}
1681
1682sub get_quoted_string {
1683	my ($line, $rawline) = @_;
1684
1685	return "" if (!defined($line) || !defined($rawline));
1686	return "" if ($line !~ m/($String)/g);
1687	return substr($rawline, $-[0], $+[0] - $-[0]);
1688}
1689
1690sub ctx_statement_block {
1691	my ($linenr, $remain, $off) = @_;
1692	my $line = $linenr - 1;
1693	my $blk = '';
1694	my $soff = $off;
1695	my $coff = $off - 1;
1696	my $coff_set = 0;
1697
1698	my $loff = 0;
1699
1700	my $type = '';
1701	my $level = 0;
1702	my @stack = ();
1703	my $p;
1704	my $c;
1705	my $len = 0;
1706
1707	my $remainder;
1708	while (1) {
1709		@stack = (['', 0]) if ($#stack == -1);
1710
1711		#warn "CSB: blk<$blk> remain<$remain>\n";
1712		# If we are about to drop off the end, pull in more
1713		# context.
1714		if ($off >= $len) {
1715			for (; $remain > 0; $line++) {
1716				last if (!defined $lines[$line]);
1717				next if ($lines[$line] =~ /^-/);
1718				$remain--;
1719				$loff = $len;
1720				$blk .= $lines[$line] . "\n";
1721				$len = length($blk);
1722				$line++;
1723				last;
1724			}
1725			# Bail if there is no further context.
1726			#warn "CSB: blk<$blk> off<$off> len<$len>\n";
1727			if ($off >= $len) {
1728				last;
1729			}
1730			if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1731				$level++;
1732				$type = '#';
1733			}
1734		}
1735		$p = $c;
1736		$c = substr($blk, $off, 1);
1737		$remainder = substr($blk, $off);
1738
1739		#warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1740
1741		# Handle nested #if/#else.
1742		if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1743			push(@stack, [ $type, $level ]);
1744		} elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1745			($type, $level) = @{$stack[$#stack - 1]};
1746		} elsif ($remainder =~ /^#\s*endif\b/) {
1747			($type, $level) = @{pop(@stack)};
1748		}
1749
1750		# Statement ends at the ';' or a close '}' at the
1751		# outermost level.
1752		if ($level == 0 && $c eq ';') {
1753			last;
1754		}
1755
1756		# An else is really a conditional as long as its not else if
1757		if ($level == 0 && $coff_set == 0 &&
1758				(!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1759				$remainder =~ /^(else)(?:\s|{)/ &&
1760				$remainder !~ /^else\s+if\b/) {
1761			$coff = $off + length($1) - 1;
1762			$coff_set = 1;
1763			#warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1764			#warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1765		}
1766
1767		if (($type eq '' || $type eq '(') && $c eq '(') {
1768			$level++;
1769			$type = '(';
1770		}
1771		if ($type eq '(' && $c eq ')') {
1772			$level--;
1773			$type = ($level != 0)? '(' : '';
1774
1775			if ($level == 0 && $coff < $soff) {
1776				$coff = $off;
1777				$coff_set = 1;
1778				#warn "CSB: mark coff<$coff>\n";
1779			}
1780		}
1781		if (($type eq '' || $type eq '{') && $c eq '{') {
1782			$level++;
1783			$type = '{';
1784		}
1785		if ($type eq '{' && $c eq '}') {
1786			$level--;
1787			$type = ($level != 0)? '{' : '';
1788
1789			if ($level == 0) {
1790				if (substr($blk, $off + 1, 1) eq ';') {
1791					$off++;
1792				}
1793				last;
1794			}
1795		}
1796		# Preprocessor commands end at the newline unless escaped.
1797		if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1798			$level--;
1799			$type = '';
1800			$off++;
1801			last;
1802		}
1803		$off++;
1804	}
1805	# We are truly at the end, so shuffle to the next line.
1806	if ($off == $len) {
1807		$loff = $len + 1;
1808		$line++;
1809		$remain--;
1810	}
1811
1812	my $statement = substr($blk, $soff, $off - $soff + 1);
1813	my $condition = substr($blk, $soff, $coff - $soff + 1);
1814
1815	#warn "STATEMENT<$statement>\n";
1816	#warn "CONDITION<$condition>\n";
1817
1818	#print "coff<$coff> soff<$off> loff<$loff>\n";
1819
1820	return ($statement, $condition,
1821			$line, $remain + 1, $off - $loff + 1, $level);
1822}
1823
1824sub statement_lines {
1825	my ($stmt) = @_;
1826
1827	# Strip the diff line prefixes and rip blank lines at start and end.
1828	$stmt =~ s/(^|\n)./$1/g;
1829	$stmt =~ s/^\s*//;
1830	$stmt =~ s/\s*$//;
1831
1832	my @stmt_lines = ($stmt =~ /\n/g);
1833
1834	return $#stmt_lines + 2;
1835}
1836
1837sub statement_rawlines {
1838	my ($stmt) = @_;
1839
1840	my @stmt_lines = ($stmt =~ /\n/g);
1841
1842	return $#stmt_lines + 2;
1843}
1844
1845sub statement_block_size {
1846	my ($stmt) = @_;
1847
1848	$stmt =~ s/(^|\n)./$1/g;
1849	$stmt =~ s/^\s*{//;
1850	$stmt =~ s/}\s*$//;
1851	$stmt =~ s/^\s*//;
1852	$stmt =~ s/\s*$//;
1853
1854	my @stmt_lines = ($stmt =~ /\n/g);
1855	my @stmt_statements = ($stmt =~ /;/g);
1856
1857	my $stmt_lines = $#stmt_lines + 2;
1858	my $stmt_statements = $#stmt_statements + 1;
1859
1860	if ($stmt_lines > $stmt_statements) {
1861		return $stmt_lines;
1862	} else {
1863		return $stmt_statements;
1864	}
1865}
1866
1867sub ctx_statement_full {
1868	my ($linenr, $remain, $off) = @_;
1869	my ($statement, $condition, $level);
1870
1871	my (@chunks);
1872
1873	# Grab the first conditional/block pair.
1874	($statement, $condition, $linenr, $remain, $off, $level) =
1875				ctx_statement_block($linenr, $remain, $off);
1876	#print "F: c<$condition> s<$statement> remain<$remain>\n";
1877	push(@chunks, [ $condition, $statement ]);
1878	if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1879		return ($level, $linenr, @chunks);
1880	}
1881
1882	# Pull in the following conditional/block pairs and see if they
1883	# could continue the statement.
1884	for (;;) {
1885		($statement, $condition, $linenr, $remain, $off, $level) =
1886				ctx_statement_block($linenr, $remain, $off);
1887		#print "C: c<$condition> s<$statement> remain<$remain>\n";
1888		last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1889		#print "C: push\n";
1890		push(@chunks, [ $condition, $statement ]);
1891	}
1892
1893	return ($level, $linenr, @chunks);
1894}
1895
1896sub ctx_block_get {
1897	my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1898	my $line;
1899	my $start = $linenr - 1;
1900	my $blk = '';
1901	my @o;
1902	my @c;
1903	my @res = ();
1904
1905	my $level = 0;
1906	my @stack = ($level);
1907	for ($line = $start; $remain > 0; $line++) {
1908		next if ($rawlines[$line] =~ /^-/);
1909		$remain--;
1910
1911		$blk .= $rawlines[$line];
1912
1913		# Handle nested #if/#else.
1914		if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1915			push(@stack, $level);
1916		} elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1917			$level = $stack[$#stack - 1];
1918		} elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1919			$level = pop(@stack);
1920		}
1921
1922		foreach my $c (split(//, $lines[$line])) {
1923			##print "C<$c>L<$level><$open$close>O<$off>\n";
1924			if ($off > 0) {
1925				$off--;
1926				next;
1927			}
1928
1929			if ($c eq $close && $level > 0) {
1930				$level--;
1931				last if ($level == 0);
1932			} elsif ($c eq $open) {
1933				$level++;
1934			}
1935		}
1936
1937		if (!$outer || $level <= 1) {
1938			push(@res, $rawlines[$line]);
1939		}
1940
1941		last if ($level == 0);
1942	}
1943
1944	return ($level, @res);
1945}
1946sub ctx_block_outer {
1947	my ($linenr, $remain) = @_;
1948
1949	my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1950	return @r;
1951}
1952sub ctx_block {
1953	my ($linenr, $remain) = @_;
1954
1955	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1956	return @r;
1957}
1958sub ctx_statement {
1959	my ($linenr, $remain, $off) = @_;
1960
1961	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1962	return @r;
1963}
1964sub ctx_block_level {
1965	my ($linenr, $remain) = @_;
1966
1967	return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1968}
1969sub ctx_statement_level {
1970	my ($linenr, $remain, $off) = @_;
1971
1972	return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1973}
1974
1975sub ctx_locate_comment {
1976	my ($first_line, $end_line) = @_;
1977
1978	# If c99 comment on the current line, or the line before or after
1979	my ($current_comment) = ($rawlines[$end_line - 1] =~ m@^\+.*(//.*$)@);
1980	return $current_comment if (defined $current_comment);
1981	($current_comment) = ($rawlines[$end_line - 2] =~ m@^[\+ ].*(//.*$)@);
1982	return $current_comment if (defined $current_comment);
1983	($current_comment) = ($rawlines[$end_line] =~ m@^[\+ ].*(//.*$)@);
1984	return $current_comment if (defined $current_comment);
1985
1986	# Catch a comment on the end of the line itself.
1987	($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1988	return $current_comment if (defined $current_comment);
1989
1990	# Look through the context and try and figure out if there is a
1991	# comment.
1992	my $in_comment = 0;
1993	$current_comment = '';
1994	for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1995		my $line = $rawlines[$linenr - 1];
1996		#warn "           $line\n";
1997		if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1998			$in_comment = 1;
1999		}
2000		if ($line =~ m@/\*@) {
2001			$in_comment = 1;
2002		}
2003		if (!$in_comment && $current_comment ne '') {
2004			$current_comment = '';
2005		}
2006		$current_comment .= $line . "\n" if ($in_comment);
2007		if ($line =~ m@\*/@) {
2008			$in_comment = 0;
2009		}
2010	}
2011
2012	chomp($current_comment);
2013	return($current_comment);
2014}
2015sub ctx_has_comment {
2016	my ($first_line, $end_line) = @_;
2017	my $cmt = ctx_locate_comment($first_line, $end_line);
2018
2019	##print "LINE: $rawlines[$end_line - 1 ]\n";
2020	##print "CMMT: $cmt\n";
2021
2022	return ($cmt ne '');
2023}
2024
2025sub raw_line {
2026	my ($linenr, $cnt) = @_;
2027
2028	my $offset = $linenr - 1;
2029	$cnt++;
2030
2031	my $line;
2032	while ($cnt) {
2033		$line = $rawlines[$offset++];
2034		next if (defined($line) && $line =~ /^-/);
2035		$cnt--;
2036	}
2037
2038	return $line;
2039}
2040
2041sub get_stat_real {
2042	my ($linenr, $lc) = @_;
2043
2044	my $stat_real = raw_line($linenr, 0);
2045	for (my $count = $linenr + 1; $count <= $lc; $count++) {
2046		$stat_real = $stat_real . "\n" . raw_line($count, 0);
2047	}
2048
2049	return $stat_real;
2050}
2051
2052sub get_stat_here {
2053	my ($linenr, $cnt, $here) = @_;
2054
2055	my $herectx = $here . "\n";
2056	for (my $n = 0; $n < $cnt; $n++) {
2057		$herectx .= raw_line($linenr, $n) . "\n";
2058	}
2059
2060	return $herectx;
2061}
2062
2063sub cat_vet {
2064	my ($vet) = @_;
2065	my ($res, $coded);
2066
2067	$res = '';
2068	while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
2069		$res .= $1;
2070		if ($2 ne '') {
2071			$coded = sprintf("^%c", unpack('C', $2) + 64);
2072			$res .= $coded;
2073		}
2074	}
2075	$res =~ s/$/\$/;
2076
2077	return $res;
2078}
2079
2080my $av_preprocessor = 0;
2081my $av_pending;
2082my @av_paren_type;
2083my $av_pend_colon;
2084
2085sub annotate_reset {
2086	$av_preprocessor = 0;
2087	$av_pending = '_';
2088	@av_paren_type = ('E');
2089	$av_pend_colon = 'O';
2090}
2091
2092sub annotate_values {
2093	my ($stream, $type) = @_;
2094
2095	my $res;
2096	my $var = '_' x length($stream);
2097	my $cur = $stream;
2098
2099	print "$stream\n" if ($dbg_values > 1);
2100
2101	while (length($cur)) {
2102		@av_paren_type = ('E') if ($#av_paren_type < 0);
2103		print " <" . join('', @av_paren_type) .
2104				"> <$type> <$av_pending>" if ($dbg_values > 1);
2105		if ($cur =~ /^(\s+)/o) {
2106			print "WS($1)\n" if ($dbg_values > 1);
2107			if ($1 =~ /\n/ && $av_preprocessor) {
2108				$type = pop(@av_paren_type);
2109				$av_preprocessor = 0;
2110			}
2111
2112		} elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
2113			print "CAST($1)\n" if ($dbg_values > 1);
2114			push(@av_paren_type, $type);
2115			$type = 'c';
2116
2117		} elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
2118			print "DECLARE($1)\n" if ($dbg_values > 1);
2119			$type = 'T';
2120
2121		} elsif ($cur =~ /^($Modifier)\s*/) {
2122			print "MODIFIER($1)\n" if ($dbg_values > 1);
2123			$type = 'T';
2124
2125		} elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
2126			print "DEFINE($1,$2)\n" if ($dbg_values > 1);
2127			$av_preprocessor = 1;
2128			push(@av_paren_type, $type);
2129			if ($2 ne '') {
2130				$av_pending = 'N';
2131			}
2132			$type = 'E';
2133
2134		} elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
2135			print "UNDEF($1)\n" if ($dbg_values > 1);
2136			$av_preprocessor = 1;
2137			push(@av_paren_type, $type);
2138
2139		} elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
2140			print "PRE_START($1)\n" if ($dbg_values > 1);
2141			$av_preprocessor = 1;
2142
2143			push(@av_paren_type, $type);
2144			push(@av_paren_type, $type);
2145			$type = 'E';
2146
2147		} elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
2148			print "PRE_RESTART($1)\n" if ($dbg_values > 1);
2149			$av_preprocessor = 1;
2150
2151			push(@av_paren_type, $av_paren_type[$#av_paren_type]);
2152
2153			$type = 'E';
2154
2155		} elsif ($cur =~ /^(\#\s*(?:endif))/o) {
2156			print "PRE_END($1)\n" if ($dbg_values > 1);
2157
2158			$av_preprocessor = 1;
2159
2160			# Assume all arms of the conditional end as this
2161			# one does, and continue as if the #endif was not here.
2162			pop(@av_paren_type);
2163			push(@av_paren_type, $type);
2164			$type = 'E';
2165
2166		} elsif ($cur =~ /^(\\\n)/o) {
2167			print "PRECONT($1)\n" if ($dbg_values > 1);
2168
2169		} elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
2170			print "ATTR($1)\n" if ($dbg_values > 1);
2171			$av_pending = $type;
2172			$type = 'N';
2173
2174		} elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
2175			print "SIZEOF($1)\n" if ($dbg_values > 1);
2176			if (defined $2) {
2177				$av_pending = 'V';
2178			}
2179			$type = 'N';
2180
2181		} elsif ($cur =~ /^(if|while|for)\b/o) {
2182			print "COND($1)\n" if ($dbg_values > 1);
2183			$av_pending = 'E';
2184			$type = 'N';
2185
2186		} elsif ($cur =~/^(case)/o) {
2187			print "CASE($1)\n" if ($dbg_values > 1);
2188			$av_pend_colon = 'C';
2189			$type = 'N';
2190
2191		} elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
2192			print "KEYWORD($1)\n" if ($dbg_values > 1);
2193			$type = 'N';
2194
2195		} elsif ($cur =~ /^(\()/o) {
2196			print "PAREN('$1')\n" if ($dbg_values > 1);
2197			push(@av_paren_type, $av_pending);
2198			$av_pending = '_';
2199			$type = 'N';
2200
2201		} elsif ($cur =~ /^(\))/o) {
2202			my $new_type = pop(@av_paren_type);
2203			if ($new_type ne '_') {
2204				$type = $new_type;
2205				print "PAREN('$1') -> $type\n"
2206							if ($dbg_values > 1);
2207			} else {
2208				print "PAREN('$1')\n" if ($dbg_values > 1);
2209			}
2210
2211		} elsif ($cur =~ /^($Ident)\s*\(/o) {
2212			print "FUNC($1)\n" if ($dbg_values > 1);
2213			$type = 'V';
2214			$av_pending = 'V';
2215
2216		} elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
2217			if (defined $2 && $type eq 'C' || $type eq 'T') {
2218				$av_pend_colon = 'B';
2219			} elsif ($type eq 'E') {
2220				$av_pend_colon = 'L';
2221			}
2222			print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
2223			$type = 'V';
2224
2225		} elsif ($cur =~ /^($Ident|$Constant)/o) {
2226			print "IDENT($1)\n" if ($dbg_values > 1);
2227			$type = 'V';
2228
2229		} elsif ($cur =~ /^($Assignment)/o) {
2230			print "ASSIGN($1)\n" if ($dbg_values > 1);
2231			$type = 'N';
2232
2233		} elsif ($cur =~/^(;|{|})/) {
2234			print "END($1)\n" if ($dbg_values > 1);
2235			$type = 'E';
2236			$av_pend_colon = 'O';
2237
2238		} elsif ($cur =~/^(,)/) {
2239			print "COMMA($1)\n" if ($dbg_values > 1);
2240			$type = 'C';
2241
2242		} elsif ($cur =~ /^(\?)/o) {
2243			print "QUESTION($1)\n" if ($dbg_values > 1);
2244			$type = 'N';
2245
2246		} elsif ($cur =~ /^(:)/o) {
2247			print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
2248
2249			substr($var, length($res), 1, $av_pend_colon);
2250			if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
2251				$type = 'E';
2252			} else {
2253				$type = 'N';
2254			}
2255			$av_pend_colon = 'O';
2256
2257		} elsif ($cur =~ /^(\[)/o) {
2258			print "CLOSE($1)\n" if ($dbg_values > 1);
2259			$type = 'N';
2260
2261		} elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
2262			my $variant;
2263
2264			print "OPV($1)\n" if ($dbg_values > 1);
2265			if ($type eq 'V') {
2266				$variant = 'B';
2267			} else {
2268				$variant = 'U';
2269			}
2270
2271			substr($var, length($res), 1, $variant);
2272			$type = 'N';
2273
2274		} elsif ($cur =~ /^($Operators)/o) {
2275			print "OP($1)\n" if ($dbg_values > 1);
2276			if ($1 ne '++' && $1 ne '--') {
2277				$type = 'N';
2278			}
2279
2280		} elsif ($cur =~ /(^.)/o) {
2281			print "C($1)\n" if ($dbg_values > 1);
2282		}
2283		if (defined $1) {
2284			$cur = substr($cur, length($1));
2285			$res .= $type x length($1);
2286		}
2287	}
2288
2289	return ($res, $var);
2290}
2291
2292sub possible {
2293	my ($possible, $line) = @_;
2294	my $notPermitted = qr{(?:
2295		^(?:
2296			$Modifier|
2297			$Storage|
2298			$Type|
2299			DEFINE_\S+
2300		)$|
2301		^(?:
2302			goto|
2303			return|
2304			case|
2305			else|
2306			asm|__asm__|
2307			do|
2308			\#|
2309			\#\#|
2310		)(?:\s|$)|
2311		^(?:typedef|struct|enum)\b
2312	    )}x;
2313	warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
2314	if ($possible !~ $notPermitted) {
2315		# Check for modifiers.
2316		$possible =~ s/\s*$Storage\s*//g;
2317		$possible =~ s/\s*$Sparse\s*//g;
2318		if ($possible =~ /^\s*$/) {
2319
2320		} elsif ($possible =~ /\s/) {
2321			$possible =~ s/\s*$Type\s*//g;
2322			for my $modifier (split(' ', $possible)) {
2323				if ($modifier !~ $notPermitted) {
2324					warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
2325					push(@modifierListFile, $modifier);
2326				}
2327			}
2328
2329		} else {
2330			warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2331			push(@typeListFile, $possible);
2332		}
2333		build_types();
2334	} else {
2335		warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2336	}
2337}
2338
2339my $prefix = '';
2340
2341sub show_type {
2342	my ($type) = @_;
2343
2344	$type =~ tr/[a-z]/[A-Z]/;
2345
2346	return defined $use_type{$type} if (scalar keys %use_type > 0);
2347
2348	return !defined $ignore_type{$type};
2349}
2350
2351sub report {
2352	my ($level, $type, $msg) = @_;
2353
2354	if (!show_type($type) ||
2355	    (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2356		return 0;
2357	}
2358	my $output = '';
2359	if ($color) {
2360		if ($level eq 'ERROR') {
2361			$output .= RED;
2362		} elsif ($level eq 'WARNING') {
2363			$output .= YELLOW;
2364		} else {
2365			$output .= GREEN;
2366		}
2367	}
2368	$output .= $prefix . $level . ':';
2369	if ($show_types) {
2370		$output .= BLUE if ($color);
2371		$output .= "$type:";
2372	}
2373	$output .= RESET if ($color);
2374	$output .= ' ' . $msg . "\n";
2375
2376	if ($showfile) {
2377		my @lines = split("\n", $output, -1);
2378		splice(@lines, 1, 1);
2379		$output = join("\n", @lines);
2380	}
2381
2382	if ($terse) {
2383		$output = (split('\n', $output))[0] . "\n";
2384	}
2385
2386	if ($verbose && exists($verbose_messages{$type}) &&
2387	    !exists($verbose_emitted{$type})) {
2388		$output .= $verbose_messages{$type} . "\n\n";
2389		$verbose_emitted{$type} = 1;
2390	}
2391
2392	push(our @report, $output);
2393
2394	return 1;
2395}
2396
2397sub report_dump {
2398	our @report;
2399}
2400
2401sub fixup_current_range {
2402	my ($lineRef, $offset, $length) = @_;
2403
2404	if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2405		my $o = $1;
2406		my $l = $2;
2407		my $no = $o + $offset;
2408		my $nl = $l + $length;
2409		$$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2410	}
2411}
2412
2413sub fix_inserted_deleted_lines {
2414	my ($linesRef, $insertedRef, $deletedRef) = @_;
2415
2416	my $range_last_linenr = 0;
2417	my $delta_offset = 0;
2418
2419	my $old_linenr = 0;
2420	my $new_linenr = 0;
2421
2422	my $next_insert = 0;
2423	my $next_delete = 0;
2424
2425	my @lines = ();
2426
2427	my $inserted = @{$insertedRef}[$next_insert++];
2428	my $deleted = @{$deletedRef}[$next_delete++];
2429
2430	foreach my $old_line (@{$linesRef}) {
2431		my $save_line = 1;
2432		my $line = $old_line;	#don't modify the array
2433		if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) {	#new filename
2434			$delta_offset = 0;
2435		} elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) {	#new hunk
2436			$range_last_linenr = $new_linenr;
2437			fixup_current_range(\$line, $delta_offset, 0);
2438		}
2439
2440		while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2441			$deleted = @{$deletedRef}[$next_delete++];
2442			$save_line = 0;
2443			fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2444		}
2445
2446		while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2447			push(@lines, ${$inserted}{'LINE'});
2448			$inserted = @{$insertedRef}[$next_insert++];
2449			$new_linenr++;
2450			fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2451		}
2452
2453		if ($save_line) {
2454			push(@lines, $line);
2455			$new_linenr++;
2456		}
2457
2458		$old_linenr++;
2459	}
2460
2461	return @lines;
2462}
2463
2464sub fix_insert_line {
2465	my ($linenr, $line) = @_;
2466
2467	my $inserted = {
2468		LINENR => $linenr,
2469		LINE => $line,
2470	};
2471	push(@fixed_inserted, $inserted);
2472}
2473
2474sub fix_delete_line {
2475	my ($linenr, $line) = @_;
2476
2477	my $deleted = {
2478		LINENR => $linenr,
2479		LINE => $line,
2480	};
2481
2482	push(@fixed_deleted, $deleted);
2483}
2484
2485sub ERROR {
2486	my ($type, $msg) = @_;
2487
2488	if (report("ERROR", $type, $msg)) {
2489		our $clean = 0;
2490		our $cnt_error++;
2491		return 1;
2492	}
2493	return 0;
2494}
2495sub WARN {
2496	my ($type, $msg) = @_;
2497
2498	if (report("WARNING", $type, $msg)) {
2499		our $clean = 0;
2500		our $cnt_warn++;
2501		return 1;
2502	}
2503	return 0;
2504}
2505sub CHK {
2506	my ($type, $msg) = @_;
2507
2508	if ($check && report("CHECK", $type, $msg)) {
2509		our $clean = 0;
2510		our $cnt_chk++;
2511		return 1;
2512	}
2513	return 0;
2514}
2515
2516sub check_absolute_file {
2517	my ($absolute, $herecurr) = @_;
2518	my $file = $absolute;
2519
2520	##print "absolute<$absolute>\n";
2521
2522	# See if any suffix of this path is a path within the tree.
2523	while ($file =~ s@^[^/]*/@@) {
2524		if (-f "$root/$file") {
2525			##print "file<$file>\n";
2526			last;
2527		}
2528	}
2529	if (! -f _)  {
2530		return 0;
2531	}
2532
2533	# It is, so see if the prefix is acceptable.
2534	my $prefix = $absolute;
2535	substr($prefix, -length($file)) = '';
2536
2537	##print "prefix<$prefix>\n";
2538	if ($prefix ne ".../") {
2539		WARN("USE_RELATIVE_PATH",
2540		     "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2541	}
2542}
2543
2544sub trim {
2545	my ($string) = @_;
2546
2547	$string =~ s/^\s+|\s+$//g;
2548
2549	return $string;
2550}
2551
2552sub ltrim {
2553	my ($string) = @_;
2554
2555	$string =~ s/^\s+//;
2556
2557	return $string;
2558}
2559
2560sub rtrim {
2561	my ($string) = @_;
2562
2563	$string =~ s/\s+$//;
2564
2565	return $string;
2566}
2567
2568sub string_find_replace {
2569	my ($string, $find, $replace) = @_;
2570
2571	$string =~ s/$find/$replace/g;
2572
2573	return $string;
2574}
2575
2576sub tabify {
2577	my ($leading) = @_;
2578
2579	my $source_indent = $tabsize;
2580	my $max_spaces_before_tab = $source_indent - 1;
2581	my $spaces_to_tab = " " x $source_indent;
2582
2583	#convert leading spaces to tabs
2584	1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2585	#Remove spaces before a tab
2586	1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2587
2588	return "$leading";
2589}
2590
2591sub pos_last_openparen {
2592	my ($line) = @_;
2593
2594	my $pos = 0;
2595
2596	my $opens = $line =~ tr/\(/\(/;
2597	my $closes = $line =~ tr/\)/\)/;
2598
2599	my $last_openparen = 0;
2600
2601	if (($opens == 0) || ($closes >= $opens)) {
2602		return -1;
2603	}
2604
2605	my $len = length($line);
2606
2607	for ($pos = 0; $pos < $len; $pos++) {
2608		my $string = substr($line, $pos);
2609		if ($string =~ /^($FuncArg|$balanced_parens)/) {
2610			$pos += length($1) - 1;
2611		} elsif (substr($line, $pos, 1) eq '(') {
2612			$last_openparen = $pos;
2613		} elsif (index($string, '(') == -1) {
2614			last;
2615		}
2616	}
2617
2618	return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2619}
2620
2621sub get_raw_comment {
2622	my ($line, $rawline) = @_;
2623	my $comment = '';
2624
2625	for my $i (0 .. (length($line) - 1)) {
2626		if (substr($line, $i, 1) eq "$;") {
2627			$comment .= substr($rawline, $i, 1);
2628		}
2629	}
2630
2631	return $comment;
2632}
2633
2634sub exclude_global_initialisers {
2635	my ($realfile) = @_;
2636
2637	# Do not check for BPF programs (tools/testing/selftests/bpf/progs/*.c, samples/bpf/*_kern.c, *.bpf.c).
2638	return $realfile =~ m@^tools/testing/selftests/bpf/progs/.*\.c$@ ||
2639		$realfile =~ m@^samples/bpf/.*_kern\.c$@ ||
2640		$realfile =~ m@/bpf/.*\.bpf\.c$@;
2641}
2642
2643sub is_userspace {
2644    my ($realfile) = @_;
2645    return ($realfile =~ m@^tools/@ || $realfile =~ m@^scripts/@);
2646}
2647
2648sub process {
2649	my $filename = shift;
2650
2651	my $linenr=0;
2652	my $prevline="";
2653	my $prevrawline="";
2654	my $stashline="";
2655	my $stashrawline="";
2656
2657	my $length;
2658	my $indent;
2659	my $previndent=0;
2660	my $stashindent=0;
2661
2662	our $clean = 1;
2663	my $signoff = 0;
2664	my $fixes_tag = 0;
2665	my $is_revert = 0;
2666	my $needs_fixes_tag = "";
2667	my $author = '';
2668	my $authorsignoff = 0;
2669	my $author_sob = '';
2670	my $is_patch = 0;
2671	my $is_binding_patch = -1;
2672	my $in_header_lines = $file ? 0 : 1;
2673	my $in_commit_log = 0;		#Scanning lines before patch
2674	my $has_patch_separator = 0;	#Found a --- line
2675	my $has_commit_log = 0;		#Encountered lines before patch
2676	my $commit_log_lines = 0;	#Number of commit log lines
2677	my $commit_log_possible_stack_dump = 0;
2678	my $commit_log_long_line = 0;
2679	my $commit_log_has_diff = 0;
2680	my $reported_maintainer_file = 0;
2681	my $non_utf8_charset = 0;
2682
2683	my $last_git_commit_id_linenr = -1;
2684
2685	my $last_blank_line = 0;
2686	my $last_coalesced_string_linenr = -1;
2687
2688	our @report = ();
2689	our $cnt_lines = 0;
2690	our $cnt_error = 0;
2691	our $cnt_warn = 0;
2692	our $cnt_chk = 0;
2693
2694	# Trace the real file/line as we go.
2695	my $realfile = '';
2696	my $realline = 0;
2697	my $realcnt = 0;
2698	my $here = '';
2699	my $context_function;		#undef'd unless there's a known function
2700	my $in_comment = 0;
2701	my $comment_edge = 0;
2702	my $first_line = 0;
2703	my $p1_prefix = '';
2704
2705	my $prev_values = 'E';
2706
2707	# suppression flags
2708	my %suppress_ifbraces;
2709	my %suppress_whiletrailers;
2710	my %suppress_export;
2711	my $suppress_statement = 0;
2712
2713	my %signatures = ();
2714
2715	# Pre-scan the patch sanitizing the lines.
2716	# Pre-scan the patch looking for any __setup documentation.
2717	#
2718	my @setup_docs = ();
2719	my $setup_docs = 0;
2720
2721	my $camelcase_file_seeded = 0;
2722
2723	my $checklicenseline = 1;
2724
2725	sanitise_line_reset();
2726	my $line;
2727	foreach my $rawline (@rawlines) {
2728		$linenr++;
2729		$line = $rawline;
2730
2731		push(@fixed, $rawline) if ($fix);
2732
2733		if ($rawline=~/^\+\+\+\s+(\S+)/) {
2734			$setup_docs = 0;
2735			if ($1 =~ m@Documentation/admin-guide/kernel-parameters.txt$@) {
2736				$setup_docs = 1;
2737			}
2738			#next;
2739		}
2740		if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2741			$realline=$1-1;
2742			if (defined $2) {
2743				$realcnt=$3+1;
2744			} else {
2745				$realcnt=1+1;
2746			}
2747			$in_comment = 0;
2748
2749			# Guestimate if this is a continuing comment.  Run
2750			# the context looking for a comment "edge".  If this
2751			# edge is a close comment then we must be in a comment
2752			# at context start.
2753			my $edge;
2754			my $cnt = $realcnt;
2755			for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2756				next if (defined $rawlines[$ln - 1] &&
2757					 $rawlines[$ln - 1] =~ /^-/);
2758				$cnt--;
2759				#print "RAW<$rawlines[$ln - 1]>\n";
2760				last if (!defined $rawlines[$ln - 1]);
2761				if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2762				    $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2763					($edge) = $1;
2764					last;
2765				}
2766			}
2767			if (defined $edge && $edge eq '*/') {
2768				$in_comment = 1;
2769			}
2770
2771			# Guestimate if this is a continuing comment.  If this
2772			# is the start of a diff block and this line starts
2773			# ' *' then it is very likely a comment.
2774			if (!defined $edge &&
2775			    $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2776			{
2777				$in_comment = 1;
2778			}
2779
2780			##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2781			sanitise_line_reset($in_comment);
2782
2783		} elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2784			# Standardise the strings and chars within the input to
2785			# simplify matching -- only bother with positive lines.
2786			$line = sanitise_line($rawline);
2787		}
2788		push(@lines, $line);
2789
2790		if ($realcnt > 1) {
2791			$realcnt-- if ($line =~ /^(?:\+| |$)/);
2792		} else {
2793			$realcnt = 0;
2794		}
2795
2796		#print "==>$rawline\n";
2797		#print "-->$line\n";
2798
2799		if ($setup_docs && $line =~ /^\+/) {
2800			push(@setup_docs, $line);
2801		}
2802	}
2803
2804	$prefix = '';
2805
2806	$realcnt = 0;
2807	$linenr = 0;
2808	$fixlinenr = -1;
2809	foreach my $line (@lines) {
2810		$linenr++;
2811		$fixlinenr++;
2812		my $sline = $line;	#copy of $line
2813		$sline =~ s/$;/ /g;	#with comments as spaces
2814
2815		my $rawline = $rawlines[$linenr - 1];
2816		my $raw_comment = get_raw_comment($line, $rawline);
2817
2818# check if it's a mode change, rename or start of a patch
2819		if (!$in_commit_log &&
2820		    ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2821		    ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2822		     $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2823			$is_patch = 1;
2824		}
2825
2826#extract the line range in the file after the patch is applied
2827		if (!$in_commit_log &&
2828		    $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2829			my $context = $4;
2830			$is_patch = 1;
2831			$first_line = $linenr + 1;
2832			$realline=$1-1;
2833			if (defined $2) {
2834				$realcnt=$3+1;
2835			} else {
2836				$realcnt=1+1;
2837			}
2838			annotate_reset();
2839			$prev_values = 'E';
2840
2841			%suppress_ifbraces = ();
2842			%suppress_whiletrailers = ();
2843			%suppress_export = ();
2844			$suppress_statement = 0;
2845			if ($context =~ /\b(\w+)\s*\(/) {
2846				$context_function = $1;
2847			} else {
2848				undef $context_function;
2849			}
2850			next;
2851
2852# track the line number as we move through the hunk, note that
2853# new versions of GNU diff omit the leading space on completely
2854# blank context lines so we need to count that too.
2855		} elsif ($line =~ /^( |\+|$)/) {
2856			$realline++;
2857			$realcnt-- if ($realcnt != 0);
2858
2859			# Measure the line length and indent.
2860			($length, $indent) = line_stats($rawline);
2861
2862			# Track the previous line.
2863			($prevline, $stashline) = ($stashline, $line);
2864			($previndent, $stashindent) = ($stashindent, $indent);
2865			($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2866
2867			#warn "line<$line>\n";
2868
2869		} elsif ($realcnt == 1) {
2870			$realcnt--;
2871		}
2872
2873		my $hunk_line = ($realcnt != 0);
2874
2875		$here = "#$linenr: " if (!$file);
2876		$here = "#$realline: " if ($file);
2877
2878		my $found_file = 0;
2879		# extract the filename as it passes
2880		if ($line =~ /^diff --git.*?(\S+)$/) {
2881			$realfile = $1;
2882			$realfile =~ s@^([^/]*)/@@ if (!$file);
2883			$in_commit_log = 0;
2884			$found_file = 1;
2885		} elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2886			$realfile = $1;
2887			$realfile =~ s@^([^/]*)/@@ if (!$file);
2888			$in_commit_log = 0;
2889
2890			$p1_prefix = $1;
2891			if (!$file && $tree && $p1_prefix ne '' &&
2892			    -e "$root/$p1_prefix") {
2893				WARN("PATCH_PREFIX",
2894				     "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2895			}
2896
2897			if ($realfile =~ m@^include/asm/@) {
2898				ERROR("MODIFIED_INCLUDE_ASM",
2899				      "do not modify files in include/asm, change architecture specific files in arch/<architecture>/include/asm\n" . "$here$rawline\n");
2900			}
2901			$found_file = 1;
2902		}
2903
2904#make up the handle for any error we report on this line
2905		if ($showfile) {
2906			$prefix = "$realfile:$realline: "
2907		} elsif ($emacs) {
2908			if ($file) {
2909				$prefix = "$filename:$realline: ";
2910			} else {
2911				$prefix = "$filename:$linenr: ";
2912			}
2913		}
2914
2915		if ($found_file) {
2916			if (is_maintained_obsolete($realfile)) {
2917				WARN("OBSOLETE",
2918				     "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy.  No unnecessary modifications please.\n");
2919			}
2920			if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2921				$check = 1;
2922			} else {
2923				$check = $check_orig;
2924			}
2925			$checklicenseline = 1;
2926
2927			if ($realfile !~ /^MAINTAINERS/) {
2928				my $last_binding_patch = $is_binding_patch;
2929
2930				$is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2931
2932				if (($last_binding_patch != -1) &&
2933				    ($last_binding_patch ^ $is_binding_patch)) {
2934					WARN("DT_SPLIT_BINDING_PATCH",
2935					     "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.rst\n");
2936				}
2937			}
2938
2939			next;
2940		}
2941
2942		$here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2943
2944		my $hereline = "$here\n$rawline\n";
2945		my $herecurr = "$here\n$rawline\n";
2946		my $hereprev = "$here\n$prevrawline\n$rawline\n";
2947
2948		$cnt_lines++ if ($realcnt != 0);
2949
2950# Verify the existence of a commit log if appropriate
2951# 2 is used because a $signature is counted in $commit_log_lines
2952		if ($in_commit_log) {
2953			if ($line !~ /^\s*$/) {
2954				$commit_log_lines++;	#could be a $signature
2955			}
2956		} elsif ($has_commit_log && $commit_log_lines < 2) {
2957			WARN("COMMIT_MESSAGE",
2958			     "Missing commit description - Add an appropriate one\n");
2959			$commit_log_lines = 2;	#warn only once
2960		}
2961
2962# Check if the commit log has what seems like a diff which can confuse patch
2963		if ($in_commit_log && !$commit_log_has_diff &&
2964		    (($line =~ m@^\s+diff\b.*a/([\w/]+)@ &&
2965		      $line =~ m@^\s+diff\b.*a/[\w/]+\s+b/$1\b@) ||
2966		     $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2967		     $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2968			ERROR("DIFF_IN_COMMIT_MSG",
2969			      "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2970			$commit_log_has_diff = 1;
2971		}
2972
2973# Check for incorrect file permissions
2974		if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2975			my $permhere = $here . "FILE: $realfile\n";
2976			if ($realfile !~ m@scripts/@ &&
2977			    $realfile !~ /\.(py|pl|awk|sh)$/) {
2978				ERROR("EXECUTE_PERMISSIONS",
2979				      "do not set execute permissions for source files\n" . $permhere);
2980			}
2981		}
2982
2983# Check the patch for a From:
2984		if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2985			$author = $1;
2986			my $curline = $linenr;
2987			while(defined($rawlines[$curline]) && ($rawlines[$curline++] =~ /^[ \t]\s*(.*)/)) {
2988				$author .= $1;
2989			}
2990			$author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2991			$author =~ s/"//g;
2992			$author = reformat_email($author);
2993		}
2994
2995# Check the patch for a signoff:
2996		if ($line =~ /^\s*signed-off-by:\s*(.*)/i) {
2997			$signoff++;
2998			$in_commit_log = 0;
2999			if ($author ne ''  && $authorsignoff != 1) {
3000				if (same_email_addresses($1, $author)) {
3001					$authorsignoff = 1;
3002				} else {
3003					my $ctx = $1;
3004					my ($email_name, $email_comment, $email_address, $comment1) = parse_email($ctx);
3005					my ($author_name, $author_comment, $author_address, $comment2) = parse_email($author);
3006
3007					if (lc $email_address eq lc $author_address && $email_name eq $author_name) {
3008						$author_sob = $ctx;
3009						$authorsignoff = 2;
3010					} elsif (lc $email_address eq lc $author_address) {
3011						$author_sob = $ctx;
3012						$authorsignoff = 3;
3013					} elsif ($email_name eq $author_name) {
3014						$author_sob = $ctx;
3015						$authorsignoff = 4;
3016
3017						my $address1 = $email_address;
3018						my $address2 = $author_address;
3019
3020						if ($address1 =~ /(\S+)\+\S+(\@.*)/) {
3021							$address1 = "$1$2";
3022						}
3023						if ($address2 =~ /(\S+)\+\S+(\@.*)/) {
3024							$address2 = "$1$2";
3025						}
3026						if ($address1 eq $address2) {
3027							$authorsignoff = 5;
3028						}
3029					}
3030				}
3031			}
3032		}
3033
3034# Check for patch separator
3035		if ($line =~ /^---$/) {
3036			$has_patch_separator = 1;
3037			$in_commit_log = 0;
3038		}
3039
3040# Check if MAINTAINERS is being updated.  If so, there's probably no need to
3041# emit the "does MAINTAINERS need updating?" message on file add/move/delete
3042		if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3043			$reported_maintainer_file = 1;
3044		}
3045
3046# Check signature styles
3047		if (!$in_header_lines &&
3048		    $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3049			my $space_before = $1;
3050			my $sign_off = $2;
3051			my $space_after = $3;
3052			my $email = $4;
3053			my $ucfirst_sign_off = ucfirst(lc($sign_off));
3054
3055			if ($sign_off !~ /$signature_tags/) {
3056				my $suggested_signature = find_standard_signature($sign_off);
3057				if ($suggested_signature eq "") {
3058					WARN("BAD_SIGN_OFF",
3059					     "Non-standard signature: $sign_off\n" . $herecurr);
3060				} else {
3061					if (WARN("BAD_SIGN_OFF",
3062						 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3063					    $fix) {
3064						$fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3065					}
3066				}
3067			}
3068			if (defined $space_before && $space_before ne "") {
3069				if (WARN("BAD_SIGN_OFF",
3070					 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3071				    $fix) {
3072					$fixed[$fixlinenr] =
3073					    "$ucfirst_sign_off $email";
3074				}
3075			}
3076			if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3077				if (WARN("BAD_SIGN_OFF",
3078					 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3079				    $fix) {
3080					$fixed[$fixlinenr] =
3081					    "$ucfirst_sign_off $email";
3082				}
3083
3084			}
3085			if (!defined $space_after || $space_after ne " ") {
3086				if (WARN("BAD_SIGN_OFF",
3087					 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3088				    $fix) {
3089					$fixed[$fixlinenr] =
3090					    "$ucfirst_sign_off $email";
3091				}
3092			}
3093
3094			my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3095			my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3096			if ($suggested_email eq "") {
3097				ERROR("BAD_SIGN_OFF",
3098				      "Unrecognized email address: '$email'\n" . $herecurr);
3099			} else {
3100				my $dequoted = $suggested_email;
3101				$dequoted =~ s/^"//;
3102				$dequoted =~ s/" </ </;
3103				# Don't force email to have quotes
3104				# Allow just an angle bracketed address
3105				if (!same_email_addresses($email, $suggested_email)) {
3106					if (WARN("BAD_SIGN_OFF",
3107						 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3108					    $fix) {
3109						$fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3110					}
3111				}
3112
3113				# Address part shouldn't have comments
3114				my $stripped_address = $email_address;
3115				$stripped_address =~ s/\([^\(\)]*\)//g;
3116				if ($email_address ne $stripped_address) {
3117					if (WARN("BAD_SIGN_OFF",
3118						 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3119					    $fix) {
3120						$fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3121					}
3122				}
3123
3124				# Only one name comment should be allowed
3125				my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3126				if ($comment_count > 1) {
3127					WARN("BAD_SIGN_OFF",
3128					     "Use a single name comment in email: '$email'\n" . $herecurr);
3129				}
3130
3131
3132				# stable@vger.kernel.org or stable@kernel.org shouldn't
3133				# have an email name. In addition comments should strictly
3134				# begin with a #
3135				if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3136					if (($comment ne "" && $comment !~ /^#.+/) ||
3137					    ($email_name ne "")) {
3138						my $cur_name = $email_name;
3139						my $new_comment = $comment;
3140						$cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3141
3142						# Remove brackets enclosing comment text
3143						# and # from start of comments to get comment text
3144						$new_comment =~ s/^\((.*)\)$/$1/;
3145						$new_comment =~ s/^\[(.*)\]$/$1/;
3146						$new_comment =~ s/^[\s\#]+|\s+$//g;
3147
3148						$new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3149						$new_comment = " # $new_comment" if ($new_comment ne "");
3150						my $new_email = "$email_address$new_comment";
3151
3152						if (WARN("BAD_STABLE_ADDRESS_STYLE",
3153							 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3154						    $fix) {
3155							$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3156						}
3157					}
3158				} elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3159					my $new_comment = $comment;
3160
3161					# Extract comment text from within brackets or
3162					# c89 style /*...*/ comments
3163					$new_comment =~ s/^\[(.*)\]$/$1/;
3164					$new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3165
3166					$new_comment = trim($new_comment);
3167					$new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3168					$new_comment = "($new_comment)" if ($new_comment ne "");
3169					my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3170
3171					if (WARN("BAD_SIGN_OFF",
3172						 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3173					    $fix) {
3174						$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3175					}
3176				}
3177			}
3178
3179# Check for duplicate signatures
3180			my $sig_nospace = $line;
3181			$sig_nospace =~ s/\s//g;
3182			$sig_nospace = lc($sig_nospace);
3183			if (defined $signatures{$sig_nospace}) {
3184				WARN("BAD_SIGN_OFF",
3185				     "Duplicate signature\n" . $herecurr);
3186			} else {
3187				$signatures{$sig_nospace} = 1;
3188			}
3189
3190# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3191			if ($sign_off =~ /^co-developed-by:$/i) {
3192				if ($email eq $author) {
3193					WARN("BAD_SIGN_OFF",
3194					      "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
3195				}
3196				if (!defined $lines[$linenr]) {
3197					WARN("BAD_SIGN_OFF",
3198					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3199				} elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
3200					WARN("BAD_SIGN_OFF",
3201					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
3202				} elsif ($1 ne $email) {
3203					WARN("BAD_SIGN_OFF",
3204					     "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
3205				}
3206			}
3207
3208# check if Reported-by: is followed by a Closes: tag
3209			if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3210				if (!defined $lines[$linenr]) {
3211					WARN("BAD_REPORTED_BY_LINK",
3212					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
3213				} elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
3214					WARN("BAD_REPORTED_BY_LINK",
3215					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
3216				}
3217			}
3218		}
3219
3220# These indicate a bug fix
3221		if (!$in_header_lines && !$is_patch &&
3222			$line =~ /^This reverts commit/) {
3223			$is_revert = 1;
3224		}
3225
3226		if (!$in_header_lines && !$is_patch &&
3227		    $line =~ /((?:(?:BUG: K.|UB)SAN: |Call Trace:|stable\@|syzkaller))/) {
3228			$needs_fixes_tag = $1;
3229		}
3230
3231# Check Fixes: styles is correct
3232		if (!$in_header_lines &&
3233		    $line =~ /^\s*(fixes:?)\s*(?:commit\s*)?([0-9a-f]{5,40})(?:\s*($balanced_parens))?/i) {
3234			my $tag = $1;
3235			my $orig_commit = $2;
3236			my $title;
3237			my $title_has_quotes = 0;
3238			$fixes_tag = 1;
3239			if (defined $3) {
3240				# Always strip leading/trailing parens then double quotes if existing
3241				$title = substr($3, 1, -1);
3242				if ($title =~ /^".*"$/) {
3243					$title = substr($title, 1, -1);
3244					$title_has_quotes = 1;
3245				}
3246			} else {
3247				$title = "commit title"
3248			}
3249
3250
3251			my $tag_case = not ($tag eq "Fixes:");
3252			my $tag_space = not ($line =~ /^fixes:? [0-9a-f]{5,40} ($balanced_parens)/i);
3253
3254			my $id_length = not ($orig_commit =~ /^[0-9a-f]{12,40}$/i);
3255			my $id_case = not ($orig_commit !~ /[A-F]/);
3256
3257			my $id = "0123456789ab";
3258			my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3259							     $title);
3260
3261			if (defined($cid) && ($ctitle ne $title || $tag_case || $tag_space || $id_length || $id_case || !$title_has_quotes)) {
3262				my $fixed = "Fixes: $cid (\"$ctitle\")";
3263				if (WARN("BAD_FIXES_TAG",
3264				     "Please use correct Fixes: style 'Fixes: <12+ chars of sha1> (\"<title line>\")' - ie: '$fixed'\n" . $herecurr) &&
3265				    $fix) {
3266					$fixed[$fixlinenr] = $fixed;
3267				}
3268			}
3269		}
3270
3271# Check email subject for common tools that don't need to be mentioned
3272		if ($in_header_lines &&
3273		    $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3274			WARN("EMAIL_SUBJECT",
3275			     "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3276		}
3277
3278# Check for Gerrit Change-Ids not in any patch context
3279		if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3280			if (ERROR("GERRIT_CHANGE_ID",
3281			          "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3282			    $fix) {
3283				fix_delete_line($fixlinenr, $rawline);
3284			}
3285		}
3286
3287# Check if the commit log is in a possible stack dump
3288		if ($in_commit_log && !$commit_log_possible_stack_dump &&
3289		    ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3290		     $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3291					# timestamp
3292		     $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3293		     $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3294		     $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3295					# stack dump address styles
3296			$commit_log_possible_stack_dump = 1;
3297		}
3298
3299# Check for line lengths > 75 in commit log, warn once
3300		if ($in_commit_log && !$commit_log_long_line &&
3301		    length($line) > 75 &&
3302		    !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3303					# file delta changes
3304		      $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3305					# filename then :
3306		      $line =~ /^\s*(?:Fixes:|https?:|$link_tags_search|$signature_tags)/i ||
3307					# A Fixes:, link or signature tag line
3308		      $commit_log_possible_stack_dump)) {
3309			WARN("COMMIT_LOG_LONG_LINE",
3310			     "Prefer a maximum 75 chars per line (possible unwrapped commit description?)\n" . $herecurr);
3311			$commit_log_long_line = 1;
3312		}
3313
3314# Reset possible stack dump if a blank line is found
3315		if ($in_commit_log && $commit_log_possible_stack_dump &&
3316		    $line =~ /^\s*$/) {
3317			$commit_log_possible_stack_dump = 0;
3318		}
3319
3320# Check for odd tags before a URI/URL
3321		if ($in_commit_log &&
3322		    $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
3323			if ($1 =~ /^v(?:ersion)?\d+/i) {
3324				WARN("COMMIT_LOG_VERSIONING",
3325				     "Patch version information should be after the --- line\n" . $herecurr);
3326			} else {
3327				WARN("COMMIT_LOG_USE_LINK",
3328				     "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
3329			}
3330		}
3331
3332# Check for misuse of the link tags
3333		if ($in_commit_log &&
3334		    $line =~ /^\s*(\w+:)\s*(\S+)/) {
3335			my $tag = $1;
3336			my $value = $2;
3337			if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3338				WARN("COMMIT_LOG_WRONG_LINK",
3339				     "'$tag' should be followed by a public http(s) link\n" . $herecurr);
3340			}
3341		}
3342
3343# Check for lines starting with a #
3344		if ($in_commit_log && $line =~ /^#/) {
3345			if (WARN("COMMIT_COMMENT_SYMBOL",
3346				 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3347			    $fix) {
3348				$fixed[$fixlinenr] =~ s/^/ /;
3349			}
3350		}
3351
3352# Check for auto-generated unhandled placeholder text (mostly for cover letters)
3353		if (($in_commit_log || $in_header_lines) &&
3354		    $rawline =~ /(?:SUBJECT|BLURB) HERE/) {
3355			ERROR("PLACEHOLDER_USE",
3356			      "Placeholder text detected\n" . $herecurr);
3357		}
3358
3359# Check for git id commit length and improperly formed commit descriptions
3360# A correctly formed commit description is:
3361#    commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3362# with the commit subject '("' prefix and '")' suffix
3363# This is a fairly compilicated block as it tests for what appears to be
3364# bare SHA-1 hash with  minimum length of 5.  It also avoids several types of
3365# possible SHA-1 matches.
3366# A commit match can span multiple lines so this block attempts to find a
3367# complete typical commit on a maximum of 3 lines
3368		if ($perl_version_ok &&
3369		    $in_commit_log && !$commit_log_possible_stack_dump &&
3370		    $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3371		    $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3372		    (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3373		      ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3374		     ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3375		      $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3376		      $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3377			my $init_char = "c";
3378			my $orig_commit = "";
3379			my $short = 1;
3380			my $long = 0;
3381			my $case = 1;
3382			my $space = 1;
3383			my $id = '0123456789ab';
3384			my $orig_desc = "commit description";
3385			my $description = "";
3386			my $herectx = $herecurr;
3387			my $has_parens = 0;
3388			my $has_quotes = 0;
3389
3390			my $input = $line;
3391			if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3392				for (my $n = 0; $n < 2; $n++) {
3393					if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3394						$orig_desc = $1;
3395						$has_parens = 1;
3396						# Always strip leading/trailing parens then double quotes if existing
3397						$orig_desc = substr($orig_desc, 1, -1);
3398						if ($orig_desc =~ /^".*"$/) {
3399							$orig_desc = substr($orig_desc, 1, -1);
3400							$has_quotes = 1;
3401						}
3402						last;
3403					}
3404					last if ($#lines < $linenr + $n);
3405					$input .= " " . trim($rawlines[$linenr + $n]);
3406					$herectx .= "$rawlines[$linenr + $n]\n";
3407				}
3408				$herectx = $herecurr if (!$has_parens);
3409			}
3410
3411			if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3412				$init_char = $1;
3413				$orig_commit = lc($2);
3414				$short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3415				$long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3416				$space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3417				$case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3418			} elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3419				$orig_commit = lc($1);
3420			}
3421
3422			($id, $description) = git_commit_info($orig_commit,
3423							      $id, $orig_desc);
3424
3425			if (defined($id) &&
3426			    ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3427			    $last_git_commit_id_linenr != $linenr - 1) {
3428				ERROR("GIT_COMMIT_ID",
3429				      "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3430			}
3431			#don't report the next line if this line ends in commit and the sha1 hash is the next line
3432			$last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3433		}
3434
3435# Check for mailing list archives other than lore.kernel.org
3436		if ($rawline =~ m{http.*\b$obsolete_archives}) {
3437			WARN("PREFER_LORE_ARCHIVE",
3438			     "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3439		}
3440
3441# Check for added, moved or deleted files
3442		if (!$reported_maintainer_file && !$in_commit_log &&
3443		    ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3444		     $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3445		     ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3446		      (defined($1) || defined($2))))) {
3447			$is_patch = 1;
3448			$reported_maintainer_file = 1;
3449			WARN("FILE_PATH_CHANGES",
3450			     "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3451		}
3452
3453# Check for adding new DT bindings not in schema format
3454		if (!$in_commit_log &&
3455		    ($line =~ /^new file mode\s*\d+\s*$/) &&
3456		    ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3457			WARN("DT_SCHEMA_BINDING_PATCH",
3458			     "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3459		}
3460
3461# Check for wrappage within a valid hunk of the file
3462		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3463			ERROR("CORRUPTED_PATCH",
3464			      "patch seems to be corrupt (line wrapped?)\n" .
3465				$herecurr) if (!$emitted_corrupt++);
3466		}
3467
3468# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3469		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3470		    $rawline !~ m/^$UTF8*$/) {
3471			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3472
3473			my $blank = copy_spacing($rawline);
3474			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3475			my $hereptr = "$hereline$ptr\n";
3476
3477			CHK("INVALID_UTF8",
3478			    "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3479		}
3480
3481# Check if it's the start of a commit log
3482# (not a header line and we haven't seen the patch filename)
3483		if ($in_header_lines && $realfile =~ /^$/ &&
3484		    !($rawline =~ /^\s+(?:\S|$)/ ||
3485		      $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3486			$in_header_lines = 0;
3487			$in_commit_log = 1;
3488			$has_commit_log = 1;
3489		}
3490
3491# Check if there is UTF-8 in a commit log when a mail header has explicitly
3492# declined it, i.e defined some charset where it is missing.
3493		if ($in_header_lines &&
3494		    $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3495		    $1 !~ /utf-8/i) {
3496			$non_utf8_charset = 1;
3497		}
3498
3499		if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3500		    $rawline =~ /$NON_ASCII_UTF8/) {
3501			WARN("UTF8_BEFORE_PATCH",
3502			    "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3503		}
3504
3505# Check for absolute kernel paths in commit message
3506		if ($tree && $in_commit_log) {
3507			while ($line =~ m{(?:^|\s)(/\S*)}g) {
3508				my $file = $1;
3509
3510				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3511				    check_absolute_file($1, $herecurr)) {
3512					#
3513				} else {
3514					check_absolute_file($file, $herecurr);
3515				}
3516			}
3517		}
3518
3519# Check for various typo / spelling mistakes
3520		if (defined($misspellings) &&
3521		    ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3522			my $rawline_utf8 = decode("utf8", $rawline);
3523			while ($rawline_utf8 =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3524				my $typo = $1;
3525				my $blank = copy_spacing($rawline_utf8);
3526				my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3527				my $hereptr = "$hereline$ptr\n";
3528				my $typo_fix = $spelling_fix{lc($typo)};
3529				$typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3530				$typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3531				my $msg_level = \&WARN;
3532				$msg_level = \&CHK if ($file);
3533				if (&{$msg_level}("TYPO_SPELLING",
3534						  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3535				    $fix) {
3536					$fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3537				}
3538			}
3539		}
3540
3541# check for invalid commit id
3542		if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3543			my $id;
3544			my $description;
3545			($id, $description) = git_commit_info($2, undef, undef);
3546			if (!defined($id)) {
3547				WARN("UNKNOWN_COMMIT_ID",
3548				     "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3549			}
3550		}
3551
3552# check for repeated words separated by a single space
3553# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3554		if (($rawline =~ /^\+/ || $in_commit_log) &&
3555		    $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3556			pos($rawline) = 1 if (!$in_commit_log);
3557			while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3558
3559				my $first = $1;
3560				my $second = $2;
3561				my $start_pos = $-[1];
3562				my $end_pos = $+[2];
3563				if ($first =~ /(?:struct|union|enum)/) {
3564					pos($rawline) += length($first) + length($second) + 1;
3565					next;
3566				}
3567
3568				next if (lc($first) ne lc($second));
3569				next if ($first eq 'long');
3570
3571				# check for character before and after the word matches
3572				my $start_char = '';
3573				my $end_char = '';
3574				$start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3575				$end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3576
3577				next if ($start_char =~ /^\S$/);
3578				next if (index(" \t.,;?!", $end_char) == -1);
3579
3580				# avoid repeating hex occurrences like 'ff ff fe 09 ...'
3581				if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3582					next if (!exists($allow_repeated_words{lc($first)}));
3583				}
3584
3585				if (WARN("REPEATED_WORD",
3586					 "Possible repeated word: '$first'\n" . $herecurr) &&
3587				    $fix) {
3588					$fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3589				}
3590			}
3591
3592			# if it's a repeated word on consecutive lines in a comment block
3593			if ($prevline =~ /$;+\s*$/ &&
3594			    $prevrawline =~ /($word_pattern)\s*$/) {
3595				my $last_word = $1;
3596				if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3597					if (WARN("REPEATED_WORD",
3598						 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3599					    $fix) {
3600						$fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3601					}
3602				}
3603			}
3604		}
3605
3606# ignore non-hunk lines and lines being removed
3607		next if (!$hunk_line || $line =~ /^-/);
3608
3609#trailing whitespace
3610		if ($line =~ /^\+.*\015/) {
3611			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3612			if (ERROR("DOS_LINE_ENDINGS",
3613				  "DOS line endings\n" . $herevet) &&
3614			    $fix) {
3615				$fixed[$fixlinenr] =~ s/[\s\015]+$//;
3616			}
3617		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3618			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3619			if (ERROR("TRAILING_WHITESPACE",
3620				  "trailing whitespace\n" . $herevet) &&
3621			    $fix) {
3622				$fixed[$fixlinenr] =~ s/\s+$//;
3623			}
3624
3625			$rpt_cleaners = 1;
3626		}
3627
3628# Check for FSF mailing addresses.
3629		if ($rawline =~ /\bwrite to the Free/i ||
3630		    $rawline =~ /\b675\s+Mass\s+Ave/i ||
3631		    $rawline =~ /\b59\s+Temple\s+Pl/i ||
3632		    $rawline =~ /\b51\s+Franklin\s+St/i) {
3633			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3634			my $msg_level = \&ERROR;
3635			$msg_level = \&CHK if ($file);
3636			&{$msg_level}("FSF_MAILING_ADDRESS",
3637				      "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
3638		}
3639
3640# check for Kconfig help text having a real description
3641# Only applies when adding the entry originally, after that we do not have
3642# sufficient context to determine whether it is indeed long enough.
3643		if ($realfile =~ /Kconfig/ &&
3644		    # 'choice' is usually the last thing on the line (though
3645		    # Kconfig supports named choices), so use a word boundary
3646		    # (\b) rather than a whitespace character (\s)
3647		    $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3648			my $ln = $linenr;
3649			my $needs_help = 0;
3650			my $has_help = 0;
3651			my $help_length = 0;
3652			while (defined $lines[$ln]) {
3653				my $f = $lines[$ln++];
3654
3655				next if ($f =~ /^-/);
3656				last if ($f !~ /^[\+ ]/);	# !patch context
3657
3658				if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3659					$needs_help = 1;
3660					next;
3661				}
3662				if ($f =~ /^\+\s*help\s*$/) {
3663					$has_help = 1;
3664					next;
3665				}
3666
3667				$f =~ s/^.//;	# strip patch context [+ ]
3668				$f =~ s/#.*//;	# strip # directives
3669				$f =~ s/^\s+//;	# strip leading blanks
3670				next if ($f =~ /^$/);	# skip blank lines
3671
3672				# At the end of this Kconfig block:
3673				# This only checks context lines in the patch
3674				# and so hopefully shouldn't trigger false
3675				# positives, even though some of these are
3676				# common words in help texts
3677				if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3678					       if|endif|menu|endmenu|source)\b/x) {
3679					last;
3680				}
3681				$help_length++ if ($has_help);
3682			}
3683			if ($needs_help &&
3684			    $help_length < $min_conf_desc_length) {
3685				my $stat_real = get_stat_real($linenr, $ln - 1);
3686				WARN("CONFIG_DESCRIPTION",
3687				     "please write a help paragraph that fully describes the config symbol with at least $min_conf_desc_length lines\n" . "$here\n$stat_real\n");
3688			}
3689		}
3690
3691# check MAINTAINERS entries
3692		if ($realfile =~ /^MAINTAINERS$/) {
3693# check MAINTAINERS entries for the right form
3694			if ($rawline =~ /^\+[A-Z]:/ &&
3695			    $rawline !~ /^\+[A-Z]:\t\S/) {
3696				if (WARN("MAINTAINERS_STYLE",
3697					 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3698				    $fix) {
3699					$fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3700				}
3701			}
3702# check MAINTAINERS entries for the right ordering too
3703			my $preferred_order = 'MRLSWQBCPTFXNK';
3704			if ($rawline =~ /^\+[A-Z]:/ &&
3705			    $prevrawline =~ /^[\+ ][A-Z]:/) {
3706				$rawline =~ /^\+([A-Z]):\s*(.*)/;
3707				my $cur = $1;
3708				my $curval = $2;
3709				$prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3710				my $prev = $1;
3711				my $prevval = $2;
3712				my $curindex = index($preferred_order, $cur);
3713				my $previndex = index($preferred_order, $prev);
3714				if ($curindex < 0) {
3715					WARN("MAINTAINERS_STYLE",
3716					     "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3717				} else {
3718					if ($previndex >= 0 && $curindex < $previndex) {
3719						WARN("MAINTAINERS_STYLE",
3720						     "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3721					} elsif ((($prev eq 'F' && $cur eq 'F') ||
3722						  ($prev eq 'X' && $cur eq 'X')) &&
3723						 ($prevval cmp $curval) > 0) {
3724						WARN("MAINTAINERS_STYLE",
3725						     "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3726					}
3727				}
3728			}
3729		}
3730
3731# check for DT compatible documentation
3732		if (defined $root &&
3733			(($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3734			 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3735
3736			my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3737
3738			my $dt_path = $root . "/Documentation/devicetree/bindings/";
3739			my $vp_file = $dt_path . "vendor-prefixes.yaml";
3740
3741			foreach my $compat (@compats) {
3742				my $compat2 = $compat;
3743				$compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3744				my $compat3 = $compat;
3745				$compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3746				`grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3747				if ( $? >> 8 ) {
3748					WARN("UNDOCUMENTED_DT_STRING",
3749					     "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3750				}
3751
3752				next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3753				my $vendor = $1;
3754				`grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3755				if ( $? >> 8 ) {
3756					WARN("UNDOCUMENTED_DT_STRING",
3757					     "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3758				}
3759			}
3760		}
3761
3762# Check for RGMII phy-mode with delay on PCB
3763		if ($realfile =~ /\.(dts|dtsi|dtso)$/ &&
3764		    $line =~ /^\+\s*(phy-mode|phy-connection-type)\s*=\s*"/ &&
3765		    !ctx_has_comment($first_line, $linenr)) {
3766			my $prop = $1;
3767			my $mode = get_quoted_string($line, $rawline);
3768			if ($mode =~ /^"rgmii(?:|-rxid|-txid)"$/) {
3769				WARN("UNCOMMENTED_RGMII_MODE",
3770				     "$prop $mode without comment -- delays on the PCB should be described, otherwise use \"rgmii-id\"\n" . $herecurr);
3771			}
3772		}
3773
3774# check for using SPDX license tag at beginning of files
3775		if ($realline == $checklicenseline) {
3776			if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3777				$checklicenseline = 2;
3778			} elsif ($rawline =~ /^\+/) {
3779				my $comment = "";
3780				if ($realfile =~ /\.(h|s|S)$/) {
3781					$comment = '/*';
3782				} elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3783					$comment = '//';
3784				} elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3785					$comment = '#';
3786				} elsif ($realfile =~ /\.rst$/) {
3787					$comment = '..';
3788				}
3789
3790# check SPDX comment style for .[chsS] files
3791				if ($realfile =~ /\.[chsS]$/ &&
3792				    $rawline =~ /SPDX-License-Identifier:/ &&
3793				    $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3794					WARN("SPDX_LICENSE_TAG",
3795					     "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3796				}
3797
3798				if ($comment !~ /^$/ &&
3799				    $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3800					WARN("SPDX_LICENSE_TAG",
3801					     "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3802				} elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3803					my $spdx_license = $1;
3804					if (!is_SPDX_License_valid($spdx_license)) {
3805						WARN("SPDX_LICENSE_TAG",
3806						     "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3807					}
3808					if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3809					    $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
3810						my $msg_level = \&WARN;
3811						$msg_level = \&CHK if ($file);
3812						if (&{$msg_level}("SPDX_LICENSE_TAG",
3813
3814								  "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3815						    $fix) {
3816							$fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3817						}
3818					}
3819					if ($realfile =~ m@^include/dt-bindings/@ &&
3820					    $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3821						WARN("SPDX_LICENSE_TAG",
3822						     "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3823					}
3824				}
3825			}
3826		}
3827
3828# check for embedded filenames
3829		if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
3830			WARN("EMBEDDED_FILENAME",
3831			     "It's generally not useful to have the filename in the file\n" . $herecurr);
3832		}
3833
3834# check we are in a valid source file if not then ignore this hunk
3835		next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3836
3837# check for using SPDX-License-Identifier on the wrong line number
3838		if ($realline != $checklicenseline &&
3839		    $rawline =~ /\bSPDX-License-Identifier:/ &&
3840		    substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3841			WARN("SPDX_LICENSE_TAG",
3842			     "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3843		}
3844
3845# line length limit (with some exclusions)
3846#
3847# There are a few types of lines that may extend beyond $max_line_length:
3848#	logging functions like pr_info that end in a string
3849#	lines with a single string
3850#	#defines that are a single string
3851#	lines with an RFC3986 like URL
3852#
3853# There are 3 different line length message types:
3854# LONG_LINE_COMMENT	a comment starts before but extends beyond $max_line_length
3855# LONG_LINE_STRING	a string starts before but extends beyond $max_line_length
3856# LONG_LINE		all other lines longer than $max_line_length
3857#
3858# if LONG_LINE is ignored, the other 2 types are also ignored
3859#
3860
3861		if ($line =~ /^\+/ && $length > $max_line_length) {
3862			my $msg_type = "LONG_LINE";
3863
3864			# Check the allowed long line types first
3865
3866			# logging functions that end in a string that starts
3867			# before $max_line_length
3868			if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3869			    length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3870				$msg_type = "";
3871
3872			# lines with only strings (w/ possible termination)
3873			# #defines with only strings
3874			} elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3875				 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3876				$msg_type = "";
3877
3878			# More special cases
3879			} elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3880				 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3881				$msg_type = "";
3882
3883			# URL ($rawline is used in case the URL is in a comment)
3884			} elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3885				$msg_type = "";
3886
3887			# Otherwise set the alternate message types
3888
3889			# a comment starts before $max_line_length
3890			} elsif ($line =~ /($;[\s$;]*)$/ &&
3891				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3892				$msg_type = "LONG_LINE_COMMENT"
3893
3894			# a quoted string starts before $max_line_length
3895			} elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3896				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3897				$msg_type = "LONG_LINE_STRING"
3898			}
3899
3900			if ($msg_type ne "" &&
3901			    show_type("LONG_LINE") && show_type($msg_type)) {
3902				my $msg_level = \&WARN;
3903				$msg_level = \&CHK if ($file);
3904				&{$msg_level}($msg_type,
3905					      "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3906			}
3907		}
3908
3909# check for adding lines without a newline.
3910		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3911			if (WARN("MISSING_EOF_NEWLINE",
3912			         "adding a line without newline at end of file\n" . $herecurr) &&
3913			    $fix) {
3914				fix_delete_line($fixlinenr+1, "No newline at end of file");
3915			}
3916		}
3917
3918# check for .L prefix local symbols in .S files
3919		if ($realfile =~ /\.S$/ &&
3920		    $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3921			WARN("AVOID_L_PREFIX",
3922			     "Avoid using '.L' prefixed local symbol names for denoting a range of code via 'SYM_*_START/END' annotations; see Documentation/core-api/asm-annotations.rst\n" . $herecurr);
3923		}
3924
3925# check we are in a valid source file C or perl if not then ignore this hunk
3926		next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3927
3928# at the beginning of a line any tabs must come first and anything
3929# more than $tabsize must use tabs.
3930		if ($rawline =~ /^\+\s* \t\s*\S/ ||
3931		    $rawline =~ /^\+\s*        \s*/) {
3932			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3933			$rpt_cleaners = 1;
3934			if (ERROR("CODE_INDENT",
3935				  "code indent should use tabs where possible\n" . $herevet) &&
3936			    $fix) {
3937				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3938			}
3939		}
3940
3941# check for space before tabs.
3942		if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3943			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3944			if (WARN("SPACE_BEFORE_TAB",
3945				"please, no space before tabs\n" . $herevet) &&
3946			    $fix) {
3947				while ($fixed[$fixlinenr] =~
3948					   s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3949				while ($fixed[$fixlinenr] =~
3950					   s/(^\+.*) +\t/$1\t/) {}
3951			}
3952		}
3953
3954# check for assignments on the start of a line
3955		if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3956			my $operator = $1;
3957			if (CHK("ASSIGNMENT_CONTINUATIONS",
3958				"Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3959			    $fix && $prevrawline =~ /^\+/) {
3960				# add assignment operator to the previous line, remove from current line
3961				$fixed[$fixlinenr - 1] .= " $operator";
3962				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3963			}
3964		}
3965
3966# check for && or || at the start of a line
3967		if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3968			my $operator = $1;
3969			if (CHK("LOGICAL_CONTINUATIONS",
3970				"Logical continuations should be on the previous line\n" . $hereprev) &&
3971			    $fix && $prevrawline =~ /^\+/) {
3972				# insert logical operator at last non-comment, non-whitepsace char on previous line
3973				$prevline =~ /[\s$;]*$/;
3974				my $line_end = substr($prevrawline, $-[0]);
3975				$fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3976				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3977			}
3978		}
3979
3980# check indentation starts on a tab stop
3981		if ($perl_version_ok &&
3982		    $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3983			my $indent = length($1);
3984			if ($indent % $tabsize) {
3985				if (WARN("TABSTOP",
3986					 "Statements should start on a tabstop\n" . $herecurr) &&
3987				    $fix) {
3988					$fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3989				}
3990			}
3991		}
3992
3993# check multi-line statement indentation matches previous line
3994		if ($perl_version_ok &&
3995		    $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3996			$prevline =~ /^\+(\t*)(.*)$/;
3997			my $oldindent = $1;
3998			my $rest = $2;
3999
4000			my $pos = pos_last_openparen($rest);
4001			if ($pos >= 0) {
4002				$line =~ /^(\+| )([ \t]*)/;
4003				my $newindent = $2;
4004
4005				my $goodtabindent = $oldindent .
4006					"\t" x ($pos / $tabsize) .
4007					" "  x ($pos % $tabsize);
4008				my $goodspaceindent = $oldindent . " "  x $pos;
4009
4010				if ($newindent ne $goodtabindent &&
4011				    $newindent ne $goodspaceindent) {
4012
4013					if (CHK("PARENTHESIS_ALIGNMENT",
4014						"Alignment should match open parenthesis\n" . $hereprev) &&
4015					    $fix && $line =~ /^\+/) {
4016						$fixed[$fixlinenr] =~
4017						    s/^\+[ \t]*/\+$goodtabindent/;
4018					}
4019				}
4020			}
4021		}
4022
4023# check for space after cast like "(int) foo" or "(struct foo) bar"
4024# avoid checking a few false positives:
4025#   "sizeof(<type>)" or "__alignof__(<type>)"
4026#   function pointer declarations like "(*foo)(int) = bar;"
4027#   structure definitions like "(struct foo) { 0 };"
4028#   multiline macros that define functions
4029#   known attributes or the __attribute__ keyword
4030		if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
4031		    (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
4032			if (CHK("SPACING",
4033				"No space is necessary after a cast\n" . $herecurr) &&
4034			    $fix) {
4035				$fixed[$fixlinenr] =~
4036				    s/(\(\s*$Type\s*\))[ \t]+/$1/;
4037			}
4038		}
4039
4040# Block comments use * on subsequent lines
4041		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4042		    $prevrawline =~ /^\+.*?\/\*/ &&		#starting /*
4043		    $prevrawline !~ /\*\/[ \t]*$/ &&		#no trailing */
4044		    $rawline =~ /^\+/ &&			#line is new
4045		    $rawline !~ /^\+[ \t]*\*/) {		#no leading *
4046			WARN("BLOCK_COMMENT_STYLE",
4047			     "Block comments use * on subsequent lines\n" . $hereprev);
4048		}
4049
4050# Block comments use */ on trailing lines
4051		if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&	#trailing */
4052		    $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&	#inline /*...*/
4053		    $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&	#trailing **/
4054		    $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {	#non blank */
4055			WARN("BLOCK_COMMENT_STYLE",
4056			     "Block comments use a trailing */ on a separate line\n" . $herecurr);
4057		}
4058
4059# Block comment * alignment
4060		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4061		    $line =~ /^\+[ \t]*$;/ &&			#leading comment
4062		    $rawline =~ /^\+[ \t]*\*/ &&		#leading *
4063		    (($prevrawline =~ /^\+.*?\/\*/ &&		#leading /*
4064		      $prevrawline !~ /\*\/[ \t]*$/) ||		#no trailing */
4065		     $prevrawline =~ /^\+[ \t]*\*/)) {		#leading *
4066			my $oldindent;
4067			$prevrawline =~ m@^\+([ \t]*/?)\*@;
4068			if (defined($1)) {
4069				$oldindent = expand_tabs($1);
4070			} else {
4071				$prevrawline =~ m@^\+(.*/?)\*@;
4072				$oldindent = expand_tabs($1);
4073			}
4074			$rawline =~ m@^\+([ \t]*)\*@;
4075			my $newindent = $1;
4076			$newindent = expand_tabs($newindent);
4077			if (length($oldindent) ne length($newindent)) {
4078				WARN("BLOCK_COMMENT_STYLE",
4079				     "Block comments should align the * on each line\n" . $hereprev);
4080			}
4081		}
4082
4083# check for missing blank lines after struct/union declarations
4084# with exceptions for various attributes and macros
4085		if ($prevline =~ /^[\+ ]};?\s*$/ &&
4086		    $line =~ /^\+/ &&
4087		    !($line =~ /^\+\s*$/ ||
4088		      $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param|ALLOW_ERROR_INJECTION)/ ||
4089		      $line =~ /^\+\s*MODULE_/i ||
4090		      $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4091		      $line =~ /^\+[a-z_]*init/ ||
4092		      $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4093		      $line =~ /^\+\s*DECLARE/ ||
4094		      $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4095		      $line =~ /^\+\s*__setup/)) {
4096			if (CHK("LINE_SPACING",
4097				"Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4098			    $fix) {
4099				fix_insert_line($fixlinenr, "\+");
4100			}
4101		}
4102
4103# check for multiple consecutive blank lines
4104		if ($prevline =~ /^[\+ ]\s*$/ &&
4105		    $line =~ /^\+\s*$/ &&
4106		    $last_blank_line != ($linenr - 1)) {
4107			if (CHK("LINE_SPACING",
4108				"Please don't use multiple blank lines\n" . $hereprev) &&
4109			    $fix) {
4110				fix_delete_line($fixlinenr, $rawline);
4111			}
4112
4113			$last_blank_line = $linenr;
4114		}
4115
4116# check for missing blank lines after declarations
4117# (declarations must have the same indentation and not be at the start of line)
4118		if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4119			# use temporaries
4120			my $sl = $sline;
4121			my $pl = $prevline;
4122			# remove $Attribute/$Sparse uses to simplify comparisons
4123			$sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4124			$pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4125			if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4126			# function pointer declarations
4127			     $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4128			# foo bar; where foo is some local typedef or #define
4129			     $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4130			# known declaration macros
4131			     $pl =~ /^\+\s+$declaration_macros/) &&
4132			# for "else if" which can look like "$Ident $Ident"
4133			    !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4134			# other possible extensions of declaration lines
4135			      $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4136			# not starting a section or a macro "\" extended line
4137			      $pl =~ /(?:\{\s*|\\)$/) &&
4138			# looks like a declaration
4139			    !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4140			# function pointer declarations
4141			      $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4142			# foo bar; where foo is some local typedef or #define
4143			      $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4144			# known declaration macros
4145			      $sl =~ /^\+\s+$declaration_macros/ ||
4146			# start of struct or union or enum
4147			      $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4148			# start or end of block or continuation of declaration
4149			      $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4150			# bitfield continuation
4151			      $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4152			# other possible extensions of declaration lines
4153			      $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4154				if (WARN("LINE_SPACING",
4155					 "Missing a blank line after declarations\n" . $hereprev) &&
4156				    $fix) {
4157					fix_insert_line($fixlinenr, "\+");
4158				}
4159			}
4160		}
4161
4162# check for spaces at the beginning of a line.
4163# Exceptions:
4164#  1) within comments
4165#  2) indented preprocessor commands
4166#  3) hanging labels
4167		if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
4168			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4169			if (WARN("LEADING_SPACE",
4170				 "please, no spaces at the start of a line\n" . $herevet) &&
4171			    $fix) {
4172				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4173			}
4174		}
4175
4176# check we are in a valid C source file if not then ignore this hunk
4177		next if ($realfile !~ /\.(h|c)$/);
4178
4179# check for unusual line ending [ or (
4180		if ($line =~ /^\+.*([\[\(])\s*$/) {
4181			CHK("OPEN_ENDED_LINE",
4182			    "Lines should not end with a '$1'\n" . $herecurr);
4183		}
4184
4185# check if this appears to be the start function declaration, save the name
4186		if ($sline =~ /^\+\{\s*$/ &&
4187		    $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4188			$context_function = $1;
4189		}
4190
4191# check if this appears to be the end of function declaration
4192		if ($sline =~ /^\+\}\s*$/) {
4193			undef $context_function;
4194		}
4195
4196# check indentation of any line with a bare else
4197# (but not if it is a multiple line "if (foo) return bar; else return baz;")
4198# if the previous line is a break or return and is indented 1 tab more...
4199		if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4200			my $tabs = length($1) + 1;
4201			if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4202			    ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4203			     defined $lines[$linenr] &&
4204			     $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4205				WARN("UNNECESSARY_ELSE",
4206				     "else is not generally useful after a break or return\n" . $hereprev);
4207			}
4208		}
4209
4210# check indentation of a line with a break;
4211# if the previous line is a goto, return or break
4212# and is indented the same # of tabs
4213		if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4214			my $tabs = $1;
4215			if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4216				if (WARN("UNNECESSARY_BREAK",
4217					 "break is not useful after a $1\n" . $hereprev) &&
4218				    $fix) {
4219					fix_delete_line($fixlinenr, $rawline);
4220				}
4221			}
4222		}
4223
4224# check for RCS/CVS revision markers
4225		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4226			WARN("CVS_KEYWORD",
4227			     "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4228		}
4229
4230# check for old HOTPLUG __dev<foo> section markings
4231		if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4232			WARN("HOTPLUG_SECTION",
4233			     "Using $1 is unnecessary\n" . $herecurr);
4234		}
4235
4236# Check for potential 'bare' types
4237		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4238		    $realline_next);
4239#print "LINE<$line>\n";
4240		if ($linenr > $suppress_statement &&
4241		    $realcnt && $sline =~ /.\s*\S/) {
4242			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4243				ctx_statement_block($linenr, $realcnt, 0);
4244			$stat =~ s/\n./\n /g;
4245			$cond =~ s/\n./\n /g;
4246
4247#print "linenr<$linenr> <$stat>\n";
4248			# If this statement has no statement boundaries within
4249			# it there is no point in retrying a statement scan
4250			# until we hit end of it.
4251			my $frag = $stat; $frag =~ s/;+\s*$//;
4252			if ($frag !~ /(?:{|;)/) {
4253#print "skip<$line_nr_next>\n";
4254				$suppress_statement = $line_nr_next;
4255			}
4256
4257			# Find the real next line.
4258			$realline_next = $line_nr_next;
4259			if (defined $realline_next &&
4260			    (!defined $lines[$realline_next - 1] ||
4261			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4262				$realline_next++;
4263			}
4264
4265			my $s = $stat;
4266			$s =~ s/{.*$//s;
4267
4268			# Ignore goto labels.
4269			if ($s =~ /$Ident:\*$/s) {
4270
4271			# Ignore functions being called
4272			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4273
4274			} elsif ($s =~ /^.\s*else\b/s) {
4275
4276			# declarations always start with types
4277			} elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
4278				my $type = $1;
4279				$type =~ s/\s+/ /g;
4280				possible($type, "A:" . $s);
4281
4282			# definitions in global scope can only start with types
4283			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4284				possible($1, "B:" . $s);
4285			}
4286
4287			# any (foo ... *) is a pointer cast, and foo is a type
4288			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4289				possible($1, "C:" . $s);
4290			}
4291
4292			# Check for any sort of function declaration.
4293			# int foo(something bar, other baz);
4294			# void (*store_gdt)(x86_descr_ptr *);
4295			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4296				my ($name_len) = length($1);
4297
4298				my $ctx = $s;
4299				substr($ctx, 0, $name_len + 1, '');
4300				$ctx =~ s/\)[^\)]*$//;
4301
4302				for my $arg (split(/\s*,\s*/, $ctx)) {
4303					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4304
4305						possible($1, "D:" . $s);
4306					}
4307				}
4308			}
4309
4310		}
4311
4312#
4313# Checks which may be anchored in the context.
4314#
4315
4316# Check for switch () and associated case and default
4317# statements should be at the same indent.
4318		if ($line=~/\bswitch\s*\(.*\)/) {
4319			my $err = '';
4320			my $sep = '';
4321			my @ctx = ctx_block_outer($linenr, $realcnt);
4322			shift(@ctx);
4323			for my $ctx (@ctx) {
4324				my ($clen, $cindent) = line_stats($ctx);
4325				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4326							$indent != $cindent) {
4327					$err .= "$sep$ctx\n";
4328					$sep = '';
4329				} else {
4330					$sep = "[...]\n";
4331				}
4332			}
4333			if ($err ne '') {
4334				ERROR("SWITCH_CASE_INDENT_LEVEL",
4335				      "switch and case should be at the same indent\n$hereline$err");
4336			}
4337		}
4338
4339# if/while/etc brace do not go on next line, unless defining a do while loop,
4340# or if that brace on the next line is for something else
4341		if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4342			my $pre_ctx = "$1$2";
4343
4344			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4345
4346			if ($line =~ /^\+\t{6,}/) {
4347				WARN("DEEP_INDENTATION",
4348				     "Too many leading tabs - consider code refactoring\n" . $herecurr);
4349			}
4350
4351			my $ctx_cnt = $realcnt - $#ctx - 1;
4352			my $ctx = join("\n", @ctx);
4353
4354			my $ctx_ln = $linenr;
4355			my $ctx_skip = $realcnt;
4356
4357			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4358					defined $lines[$ctx_ln - 1] &&
4359					$lines[$ctx_ln - 1] =~ /^-/)) {
4360				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4361				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4362				$ctx_ln++;
4363			}
4364
4365			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4366			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4367
4368			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4369				ERROR("OPEN_BRACE",
4370				      "that open brace { should be on the previous line\n" .
4371					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4372			}
4373			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4374			    $ctx =~ /\)\s*\;\s*$/ &&
4375			    defined $lines[$ctx_ln - 1])
4376			{
4377				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4378				if ($nindent > $indent) {
4379					WARN("TRAILING_SEMICOLON",
4380					     "trailing semicolon indicates no statements, indent implies otherwise\n" .
4381						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4382				}
4383			}
4384		}
4385
4386# Check relative indent for conditionals and blocks.
4387		if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4388			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4389				ctx_statement_block($linenr, $realcnt, 0)
4390					if (!defined $stat);
4391			my ($s, $c) = ($stat, $cond);
4392
4393			substr($s, 0, length($c), '');
4394
4395			# remove inline comments
4396			$s =~ s/$;/ /g;
4397			$c =~ s/$;/ /g;
4398
4399			# Find out how long the conditional actually is.
4400			my @newlines = ($c =~ /\n/gs);
4401			my $cond_lines = 1 + $#newlines;
4402
4403			# Make sure we remove the line prefixes as we have
4404			# none on the first line, and are going to readd them
4405			# where necessary.
4406			$s =~ s/\n./\n/gs;
4407			while ($s =~ /\n\s+\\\n/) {
4408				$cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4409			}
4410
4411			# We want to check the first line inside the block
4412			# starting at the end of the conditional, so remove:
4413			#  1) any blank line termination
4414			#  2) any opening brace { on end of the line
4415			#  3) any do (...) {
4416			my $continuation = 0;
4417			my $check = 0;
4418			$s =~ s/^.*\bdo\b//;
4419			$s =~ s/^\s*{//;
4420			if ($s =~ s/^\s*\\//) {
4421				$continuation = 1;
4422			}
4423			if ($s =~ s/^\s*?\n//) {
4424				$check = 1;
4425				$cond_lines++;
4426			}
4427
4428			# Also ignore a loop construct at the end of a
4429			# preprocessor statement.
4430			if (($prevline =~ /^.\s*#\s*define\s/ ||
4431			    $prevline =~ /\\\s*$/) && $continuation == 0) {
4432				$check = 0;
4433			}
4434
4435			my $cond_ptr = -1;
4436			$continuation = 0;
4437			while ($cond_ptr != $cond_lines) {
4438				$cond_ptr = $cond_lines;
4439
4440				# If we see an #else/#elif then the code
4441				# is not linear.
4442				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4443					$check = 0;
4444				}
4445
4446				# Ignore:
4447				#  1) blank lines, they should be at 0,
4448				#  2) preprocessor lines, and
4449				#  3) labels.
4450				if ($continuation ||
4451				    $s =~ /^\s*?\n/ ||
4452				    $s =~ /^\s*#\s*?/ ||
4453				    $s =~ /^\s*$Ident\s*:/) {
4454					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4455					if ($s =~ s/^.*?\n//) {
4456						$cond_lines++;
4457					}
4458				}
4459			}
4460
4461			my (undef, $sindent) = line_stats("+" . $s);
4462			my $stat_real = raw_line($linenr, $cond_lines);
4463
4464			# Check if either of these lines are modified, else
4465			# this is not this patch's fault.
4466			if (!defined($stat_real) ||
4467			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4468				$check = 0;
4469			}
4470			if (defined($stat_real) && $cond_lines > 1) {
4471				$stat_real = "[...]\n$stat_real";
4472			}
4473
4474			#print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
4475
4476			if ($check && $s ne '' &&
4477			    (($sindent % $tabsize) != 0 ||
4478			     ($sindent < $indent) ||
4479			     ($sindent == $indent &&
4480			      ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4481			     ($sindent > $indent + $tabsize))) {
4482				WARN("SUSPECT_CODE_INDENT",
4483				     "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4484			}
4485		}
4486
4487		# Track the 'values' across context and added lines.
4488		my $opline = $line; $opline =~ s/^./ /;
4489		my ($curr_values, $curr_vars) =
4490				annotate_values($opline . "\n", $prev_values);
4491		$curr_values = $prev_values . $curr_values;
4492		if ($dbg_values) {
4493			my $outline = $opline; $outline =~ s/\t/ /g;
4494			print "$linenr > .$outline\n";
4495			print "$linenr > $curr_values\n";
4496			print "$linenr >  $curr_vars\n";
4497		}
4498		$prev_values = substr($curr_values, -1);
4499
4500#ignore lines not being added
4501		next if ($line =~ /^[^\+]/);
4502
4503# check for self assignments used to avoid compiler warnings
4504# e.g.:	int foo = foo, *bar = NULL;
4505#	struct foo bar = *(&(bar));
4506		if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4507			my $var = $1;
4508			if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4509				WARN("SELF_ASSIGNMENT",
4510				     "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4511			}
4512		}
4513
4514# check for dereferences that span multiple lines
4515		if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4516		    $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4517			$prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4518			my $ref = $1;
4519			$line =~ /^.\s*($Lval)/;
4520			$ref .= $1;
4521			$ref =~ s/\s//g;
4522			WARN("MULTILINE_DEREFERENCE",
4523			     "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4524		}
4525
4526# check for declarations of signed or unsigned without int
4527		while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4528			my $type = $1;
4529			my $var = $2;
4530			$var = "" if (!defined $var);
4531			if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4532				my $sign = $1;
4533				my $pointer = $2;
4534
4535				$pointer = "" if (!defined $pointer);
4536
4537				if (WARN("UNSPECIFIED_INT",
4538					 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4539				    $fix) {
4540					my $decl = trim($sign) . " int ";
4541					my $comp_pointer = $pointer;
4542					$comp_pointer =~ s/\s//g;
4543					$decl .= $comp_pointer;
4544					$decl = rtrim($decl) if ($var eq "");
4545					$fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4546				}
4547			}
4548		}
4549
4550# TEST: allow direct testing of the type matcher.
4551		if ($dbg_type) {
4552			if ($line =~ /^.\s*$Declare\s*$/) {
4553				ERROR("TEST_TYPE",
4554				      "TEST: is type\n" . $herecurr);
4555			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4556				ERROR("TEST_NOT_TYPE",
4557				      "TEST: is not type ($1 is)\n". $herecurr);
4558			}
4559			next;
4560		}
4561# TEST: allow direct testing of the attribute matcher.
4562		if ($dbg_attr) {
4563			if ($line =~ /^.\s*$Modifier\s*$/) {
4564				ERROR("TEST_ATTR",
4565				      "TEST: is attr\n" . $herecurr);
4566			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4567				ERROR("TEST_NOT_ATTR",
4568				      "TEST: is not attr ($1 is)\n". $herecurr);
4569			}
4570			next;
4571		}
4572
4573# check for initialisation to aggregates open brace on the next line
4574		if ($line =~ /^.\s*{/ &&
4575		    $prevline =~ /(?:^|[^=])=\s*$/) {
4576			if (ERROR("OPEN_BRACE",
4577				  "that open brace { should be on the previous line\n" . $hereprev) &&
4578			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4579				fix_delete_line($fixlinenr - 1, $prevrawline);
4580				fix_delete_line($fixlinenr, $rawline);
4581				my $fixedline = $prevrawline;
4582				$fixedline =~ s/\s*=\s*$/ = {/;
4583				fix_insert_line($fixlinenr, $fixedline);
4584				$fixedline = $line;
4585				$fixedline =~ s/^(.\s*)\{\s*/$1/;
4586				fix_insert_line($fixlinenr, $fixedline);
4587			}
4588		}
4589
4590#
4591# Checks which are anchored on the added line.
4592#
4593
4594# check for malformed paths in #include statements (uses RAW line)
4595		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4596			my $path = $1;
4597			if ($path =~ m{//}) {
4598				ERROR("MALFORMED_INCLUDE",
4599				      "malformed #include filename\n" . $herecurr);
4600			}
4601			if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4602				ERROR("UAPI_INCLUDE",
4603				      "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4604			}
4605		}
4606
4607# no C99 // comments
4608		if ($line =~ m{//}) {
4609			if (ERROR("C99_COMMENTS",
4610				  "do not use C99 // comments\n" . $herecurr) &&
4611			    $fix) {
4612				my $line = $fixed[$fixlinenr];
4613				if ($line =~ /\/\/(.*)$/) {
4614					my $comment = trim($1);
4615					$fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4616				}
4617			}
4618		}
4619		# Remove C99 comments.
4620		$line =~ s@//.*@@;
4621		$opline =~ s@//.*@@;
4622
4623# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4624# the whole statement.
4625#print "APW <$lines[$realline_next - 1]>\n";
4626		if (defined $realline_next &&
4627		    exists $lines[$realline_next - 1] &&
4628		    !defined $suppress_export{$realline_next} &&
4629		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4630			# Handle definitions which produce identifiers with
4631			# a prefix:
4632			#   XXX(foo);
4633			#   EXPORT_SYMBOL(something_foo);
4634			my $name = $1;
4635			$name =~ s/^\s*($Ident).*/$1/;
4636			if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4637			    $name =~ /^${Ident}_$2/) {
4638#print "FOO C name<$name>\n";
4639				$suppress_export{$realline_next} = 1;
4640
4641			} elsif ($stat !~ /(?:
4642				\n.}\s*$|
4643				^.DEFINE_$Ident\(\Q$name\E\)|
4644				^.DECLARE_$Ident\(\Q$name\E\)|
4645				^.LIST_HEAD\(\Q$name\E\)|
4646				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4647				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4648			    )/x) {
4649#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4650				$suppress_export{$realline_next} = 2;
4651			} else {
4652				$suppress_export{$realline_next} = 1;
4653			}
4654		}
4655		if (!defined $suppress_export{$linenr} &&
4656		    $prevline =~ /^.\s*$/ &&
4657		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4658#print "FOO B <$lines[$linenr - 1]>\n";
4659			$suppress_export{$linenr} = 2;
4660		}
4661		if (defined $suppress_export{$linenr} &&
4662		    $suppress_export{$linenr} == 2) {
4663			WARN("EXPORT_SYMBOL",
4664			     "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4665		}
4666
4667# check for global initialisers.
4668		if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4669		    !exclude_global_initialisers($realfile)) {
4670			if (ERROR("GLOBAL_INITIALISERS",
4671				  "do not initialise globals to $1\n" . $herecurr) &&
4672			    $fix) {
4673				$fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4674			}
4675		}
4676# check for static initialisers.
4677		if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4678			if (ERROR("INITIALISED_STATIC",
4679				  "do not initialise statics to $1\n" .
4680				      $herecurr) &&
4681			    $fix) {
4682				$fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4683			}
4684		}
4685
4686# check for misordered declarations of char/short/int/long with signed/unsigned
4687		while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4688			my $tmp = trim($1);
4689			WARN("MISORDERED_TYPE",
4690			     "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4691		}
4692
4693# check for unnecessary <signed> int declarations of short/long/long long
4694		while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4695			my $type = trim($1);
4696			next if ($type !~ /\bint\b/);
4697			next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4698			my $new_type = $type;
4699			$new_type =~ s/\b\s*int\s*\b/ /;
4700			$new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4701			$new_type =~ s/^const\s+//;
4702			$new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4703			$new_type = "const $new_type" if ($type =~ /^const\b/);
4704			$new_type =~ s/\s+/ /g;
4705			$new_type = trim($new_type);
4706			if (WARN("UNNECESSARY_INT",
4707				 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4708			    $fix) {
4709				$fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4710			}
4711		}
4712
4713# check for static const char * arrays.
4714		if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4715			WARN("STATIC_CONST_CHAR_ARRAY",
4716			     "static const char * array should probably be static const char * const\n" .
4717				$herecurr);
4718		}
4719
4720# check for initialized const char arrays that should be static const
4721		if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4722			if (WARN("STATIC_CONST_CHAR_ARRAY",
4723				 "const array should probably be static const\n" . $herecurr) &&
4724			    $fix) {
4725				$fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4726			}
4727		}
4728
4729# check for static char foo[] = "bar" declarations.
4730		if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4731			WARN("STATIC_CONST_CHAR_ARRAY",
4732			     "static char array declaration should probably be static const char\n" .
4733				$herecurr);
4734		}
4735
4736# check for const <foo> const where <foo> is not a pointer or array type
4737		if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4738			my $found = $1;
4739			if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4740				WARN("CONST_CONST",
4741				     "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4742			} elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4743				WARN("CONST_CONST",
4744				     "'const $found const' should probably be 'const $found'\n" . $herecurr);
4745			}
4746		}
4747
4748# check for const static or static <non ptr type> const declarations
4749# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4750		if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4751		    $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4752			if (WARN("STATIC_CONST",
4753				 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4754			    $fix) {
4755				$fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4756				$fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4757			}
4758		}
4759
4760# check for non-global char *foo[] = {"bar", ...} declarations.
4761		if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4762			WARN("STATIC_CONST_CHAR_ARRAY",
4763			     "char * array declaration might be better as static const\n" .
4764				$herecurr);
4765		}
4766
4767# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4768		if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4769			my $array = $1;
4770			if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4771				my $array_div = $1;
4772				if (WARN("ARRAY_SIZE",
4773					 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4774				    $fix) {
4775					$fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4776				}
4777			}
4778		}
4779
4780# check for function declarations without arguments like "int foo()"
4781		if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4782			if (ERROR("FUNCTION_WITHOUT_ARGS",
4783				  "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4784			    $fix) {
4785				$fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4786			}
4787		}
4788
4789# check for new typedefs, only function parameters and sparse annotations
4790# make sense.
4791		if ($line =~ /\btypedef\s/ &&
4792		    $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4793		    $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4794		    $line !~ /\b$typeTypedefs\b/ &&
4795		    $line !~ /\b__bitwise\b/) {
4796			WARN("NEW_TYPEDEFS",
4797			     "do not add new typedefs\n" . $herecurr);
4798		}
4799
4800# * goes on variable not on type
4801		# (char*[ const])
4802		while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4803			#print "AA<$1>\n";
4804			my ($ident, $from, $to) = ($1, $2, $2);
4805
4806			# Should start with a space.
4807			$to =~ s/^(\S)/ $1/;
4808			# Should not end with a space.
4809			$to =~ s/\s+$//;
4810			# '*'s should not have spaces between.
4811			while ($to =~ s/\*\s+\*/\*\*/) {
4812			}
4813
4814##			print "1: from<$from> to<$to> ident<$ident>\n";
4815			if ($from ne $to) {
4816				if (ERROR("POINTER_LOCATION",
4817					  "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4818				    $fix) {
4819					my $sub_from = $ident;
4820					my $sub_to = $ident;
4821					$sub_to =~ s/\Q$from\E/$to/;
4822					$fixed[$fixlinenr] =~
4823					    s@\Q$sub_from\E@$sub_to@;
4824				}
4825			}
4826		}
4827		while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4828			#print "BB<$1>\n";
4829			my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4830
4831			# Should start with a space.
4832			$to =~ s/^(\S)/ $1/;
4833			# Should not end with a space.
4834			$to =~ s/\s+$//;
4835			# '*'s should not have spaces between.
4836			while ($to =~ s/\*\s+\*/\*\*/) {
4837			}
4838			# Modifiers should have spaces.
4839			$to =~ s/(\b$Modifier$)/$1 /;
4840
4841##			print "2: from<$from> to<$to> ident<$ident>\n";
4842			if ($from ne $to && $ident !~ /^$Modifier$/) {
4843				if (ERROR("POINTER_LOCATION",
4844					  "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4845				    $fix) {
4846
4847					my $sub_from = $match;
4848					my $sub_to = $match;
4849					$sub_to =~ s/\Q$from\E/$to/;
4850					$fixed[$fixlinenr] =~
4851					    s@\Q$sub_from\E@$sub_to@;
4852				}
4853			}
4854		}
4855
4856# do not use BUG() or variants
4857		if ($line =~ /\b(?!AA_|BUILD_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4858			my $msg_level = \&WARN;
4859			$msg_level = \&CHK if ($file);
4860			&{$msg_level}("AVOID_BUG",
4861				      "Do not crash the kernel unless it is absolutely unavoidable--use WARN_ON_ONCE() plus recovery code (if feasible) instead of BUG() or variants\n" . $herecurr);
4862		}
4863
4864# avoid LINUX_VERSION_CODE
4865		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4866			WARN("LINUX_VERSION_CODE",
4867			     "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4868		}
4869
4870# check for uses of printk_ratelimit
4871		if ($line =~ /\bprintk_ratelimit\s*\(/) {
4872			WARN("PRINTK_RATELIMITED",
4873			     "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4874		}
4875
4876# printk should use KERN_* levels
4877		if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4878			WARN("PRINTK_WITHOUT_KERN_LEVEL",
4879			     "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4880		}
4881
4882# prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4883		if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4884			my $printk = $1;
4885			my $modifier = $2;
4886			my $orig = $3;
4887			$modifier = "" if (!defined($modifier));
4888			my $level = lc($orig);
4889			$level = "warn" if ($level eq "warning");
4890			my $level2 = $level;
4891			$level2 = "dbg" if ($level eq "debug");
4892			$level .= $modifier;
4893			$level2 .= $modifier;
4894			WARN("PREFER_PR_LEVEL",
4895			     "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to $printk(KERN_$orig ...\n" . $herecurr);
4896		}
4897
4898# prefer dev_<level> to dev_printk(KERN_<LEVEL>
4899		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4900			my $orig = $1;
4901			my $level = lc($orig);
4902			$level = "warn" if ($level eq "warning");
4903			$level = "dbg" if ($level eq "debug");
4904			WARN("PREFER_DEV_LEVEL",
4905			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4906		}
4907
4908# trace_printk should not be used in production code.
4909		if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4910			WARN("TRACE_PRINTK",
4911			     "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4912		}
4913
4914# ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4915# number of false positives, but assembly files are not checked, so at
4916# least the arch entry code will not trigger this warning.
4917		if ($line =~ /\bENOSYS\b/) {
4918			WARN("ENOSYS",
4919			     "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4920		}
4921
4922# ENOTSUPP is not a standard error code and should be avoided in new patches.
4923# Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4924# Similarly to ENOSYS warning a small number of false positives is expected.
4925		if (!$file && $line =~ /\bENOTSUPP\b/) {
4926			if (WARN("ENOTSUPP",
4927				 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4928			    $fix) {
4929				$fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4930			}
4931		}
4932
4933# function brace can't be on same line, except for #defines of do while,
4934# or if closed on same line
4935		if ($perl_version_ok &&
4936		    $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4937		    $sline !~ /\#\s*define\b.*do\s*\{/ &&
4938		    $sline !~ /}/) {
4939			if (ERROR("OPEN_BRACE",
4940				  "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4941			    $fix) {
4942				fix_delete_line($fixlinenr, $rawline);
4943				my $fixed_line = $rawline;
4944				$fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4945				my $line1 = $1;
4946				my $line2 = $2;
4947				fix_insert_line($fixlinenr, ltrim($line1));
4948				fix_insert_line($fixlinenr, "\+{");
4949				if ($line2 !~ /^\s*$/) {
4950					fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4951				}
4952			}
4953		}
4954
4955# open braces for enum, union and struct go on the same line.
4956		if ($line =~ /^.\s*{/ &&
4957		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4958			if (ERROR("OPEN_BRACE",
4959				  "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4960			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4961				fix_delete_line($fixlinenr - 1, $prevrawline);
4962				fix_delete_line($fixlinenr, $rawline);
4963				my $fixedline = rtrim($prevrawline) . " {";
4964				fix_insert_line($fixlinenr, $fixedline);
4965				$fixedline = $rawline;
4966				$fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4967				if ($fixedline !~ /^\+\s*$/) {
4968					fix_insert_line($fixlinenr, $fixedline);
4969				}
4970			}
4971		}
4972
4973# missing space after union, struct or enum definition
4974		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4975			if (WARN("SPACING",
4976				 "missing space after $1 definition\n" . $herecurr) &&
4977			    $fix) {
4978				$fixed[$fixlinenr] =~
4979				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4980			}
4981		}
4982
4983# Function pointer declarations
4984# check spacing between type, funcptr, and args
4985# canonical declaration is "type (*funcptr)(args...)"
4986		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4987			my $declare = $1;
4988			my $pre_pointer_space = $2;
4989			my $post_pointer_space = $3;
4990			my $funcname = $4;
4991			my $post_funcname_space = $5;
4992			my $pre_args_space = $6;
4993
4994# the $Declare variable will capture all spaces after the type
4995# so check it for a missing trailing missing space but pointer return types
4996# don't need a space so don't warn for those.
4997			my $post_declare_space = "";
4998			if ($declare =~ /(\s+)$/) {
4999				$post_declare_space = $1;
5000				$declare = rtrim($declare);
5001			}
5002			if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
5003				WARN("SPACING",
5004				     "missing space after return type\n" . $herecurr);
5005				$post_declare_space = " ";
5006			}
5007
5008# unnecessary space "type  (*funcptr)(args...)"
5009# This test is not currently implemented because these declarations are
5010# equivalent to
5011#	int  foo(int bar, ...)
5012# and this is form shouldn't/doesn't generate a checkpatch warning.
5013#
5014#			elsif ($declare =~ /\s{2,}$/) {
5015#				WARN("SPACING",
5016#				     "Multiple spaces after return type\n" . $herecurr);
5017#			}
5018
5019# unnecessary space "type ( *funcptr)(args...)"
5020			if (defined $pre_pointer_space &&
5021			    $pre_pointer_space =~ /^\s/) {
5022				WARN("SPACING",
5023				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
5024			}
5025
5026# unnecessary space "type (* funcptr)(args...)"
5027			if (defined $post_pointer_space &&
5028			    $post_pointer_space =~ /^\s/) {
5029				WARN("SPACING",
5030				     "Unnecessary space before function pointer name\n" . $herecurr);
5031			}
5032
5033# unnecessary space "type (*funcptr )(args...)"
5034			if (defined $post_funcname_space &&
5035			    $post_funcname_space =~ /^\s/) {
5036				WARN("SPACING",
5037				     "Unnecessary space after function pointer name\n" . $herecurr);
5038			}
5039
5040# unnecessary space "type (*funcptr) (args...)"
5041			if (defined $pre_args_space &&
5042			    $pre_args_space =~ /^\s/) {
5043				WARN("SPACING",
5044				     "Unnecessary space before function pointer arguments\n" . $herecurr);
5045			}
5046
5047			if (show_type("SPACING") && $fix) {
5048				$fixed[$fixlinenr] =~
5049				    s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5050			}
5051		}
5052
5053# check for spacing round square brackets; allowed:
5054#  1. with a type on the left -- int [] a;
5055#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5056#  3. inside a curly brace -- = { [0...10] = 5 }
5057		while ($line =~ /(.*?\s)\[/g) {
5058			my ($where, $prefix) = ($-[1], $1);
5059			if ($prefix !~ /$Type\s+$/ &&
5060			    ($where != 0 || $prefix !~ /^.\s+$/) &&
5061			    $prefix !~ /[{,:]\s+$/) {
5062				if (ERROR("BRACKET_SPACE",
5063					  "space prohibited before open square bracket '['\n" . $herecurr) &&
5064				    $fix) {
5065				    $fixed[$fixlinenr] =~
5066					s/^(\+.*?)\s+\[/$1\[/;
5067				}
5068			}
5069		}
5070
5071# check for spaces between functions and their parentheses.
5072		while ($line =~ /($Ident)\s+\(/g) {
5073			my $name = $1;
5074			my $ctx_before = substr($line, 0, $-[1]);
5075			my $ctx = "$ctx_before$name";
5076
5077			# Ignore those directives where spaces _are_ permitted.
5078			if ($name =~ /^(?:
5079				if|for|while|switch|return|case|
5080				volatile|__volatile__|
5081				__attribute__|format|__extension__|
5082				asm|__asm__|scoped_guard)$/x)
5083			{
5084			# cpp #define statements have non-optional spaces, ie
5085			# if there is a space between the name and the open
5086			# parenthesis it is simply not a parameter group.
5087			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5088
5089			# cpp #elif statement condition may start with a (
5090			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5091
5092			# If this whole things ends with a type its most
5093			# likely a typedef for a function.
5094			} elsif ($ctx =~ /$Type$/) {
5095
5096			} else {
5097				if (WARN("SPACING",
5098					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5099					     $fix) {
5100					$fixed[$fixlinenr] =~
5101					    s/\b$name\s+\(/$name\(/;
5102				}
5103			}
5104		}
5105
5106# Check operator spacing.
5107		if (!($line=~/\#\s*include/)) {
5108			my $fixed_line = "";
5109			my $line_fixed = 0;
5110
5111			my $ops = qr{
5112				<<=|>>=|<=|>=|==|!=|
5113				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5114				=>|->|<<|>>|<|>|=|!|~|
5115				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5116				\?:|\?|:
5117			}x;
5118			my @elements = split(/($ops|;)/, $opline);
5119
5120##			print("element count: <" . $#elements . ">\n");
5121##			foreach my $el (@elements) {
5122##				print("el: <$el>\n");
5123##			}
5124
5125			my @fix_elements = ();
5126			my $off = 0;
5127
5128			foreach my $el (@elements) {
5129				push(@fix_elements, substr($rawline, $off, length($el)));
5130				$off += length($el);
5131			}
5132
5133			$off = 0;
5134
5135			my $blank = copy_spacing($opline);
5136			my $last_after = -1;
5137
5138			for (my $n = 0; $n < $#elements; $n += 2) {
5139
5140				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5141
5142##				print("n: <$n> good: <$good>\n");
5143
5144				$off += length($elements[$n]);
5145
5146				# Pick up the preceding and succeeding characters.
5147				my $ca = substr($opline, 0, $off);
5148				my $cc = '';
5149				if (length($opline) >= ($off + length($elements[$n + 1]))) {
5150					$cc = substr($opline, $off + length($elements[$n + 1]));
5151				}
5152				my $cb = "$ca$;$cc";
5153
5154				my $a = '';
5155				$a = 'V' if ($elements[$n] ne '');
5156				$a = 'W' if ($elements[$n] =~ /\s$/);
5157				$a = 'C' if ($elements[$n] =~ /$;$/);
5158				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5159				$a = 'O' if ($elements[$n] eq '');
5160				$a = 'E' if ($ca =~ /^\s*$/);
5161
5162				my $op = $elements[$n + 1];
5163
5164				my $c = '';
5165				if (defined $elements[$n + 2]) {
5166					$c = 'V' if ($elements[$n + 2] ne '');
5167					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
5168					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
5169					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5170					$c = 'O' if ($elements[$n + 2] eq '');
5171					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5172				} else {
5173					$c = 'E';
5174				}
5175
5176				my $ctx = "${a}x${c}";
5177
5178				my $at = "(ctx:$ctx)";
5179
5180				my $ptr = substr($blank, 0, $off) . "^";
5181				my $hereptr = "$hereline$ptr\n";
5182
5183				# Pull out the value of this operator.
5184				my $op_type = substr($curr_values, $off + 1, 1);
5185
5186				# Get the full operator variant.
5187				my $opv = $op . substr($curr_vars, $off, 1);
5188
5189				# Ignore operators passed as parameters.
5190				if ($op_type ne 'V' &&
5191				    $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5192
5193#				# Ignore comments
5194#				} elsif ($op =~ /^$;+$/) {
5195
5196				# ; should have either the end of line or a space or \ after it
5197				} elsif ($op eq ';') {
5198					if ($ctx !~ /.x[WEBC]/ &&
5199					    $cc !~ /^\\/ && $cc !~ /^;/) {
5200						if (ERROR("SPACING",
5201							  "space required after that '$op' $at\n" . $hereptr)) {
5202							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5203							$line_fixed = 1;
5204						}
5205					}
5206
5207				# // is a comment
5208				} elsif ($op eq '//') {
5209
5210				#   :   when part of a bitfield
5211				} elsif ($opv eq ':B') {
5212					# skip the bitfield test for now
5213
5214				# No spaces for:
5215				#   ->
5216				} elsif ($op eq '->') {
5217					if ($ctx =~ /Wx.|.xW/) {
5218						if (ERROR("SPACING",
5219							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5220							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5221							if (defined $fix_elements[$n + 2]) {
5222								$fix_elements[$n + 2] =~ s/^\s+//;
5223							}
5224							$line_fixed = 1;
5225						}
5226					}
5227
5228				# , must not have a space before and must have a space on the right.
5229				} elsif ($op eq ',') {
5230					my $rtrim_before = 0;
5231					my $space_after = 0;
5232					if ($ctx =~ /Wx./) {
5233						if (ERROR("SPACING",
5234							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5235							$line_fixed = 1;
5236							$rtrim_before = 1;
5237						}
5238					}
5239					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5240						if (ERROR("SPACING",
5241							  "space required after that '$op' $at\n" . $hereptr)) {
5242							$line_fixed = 1;
5243							$last_after = $n;
5244							$space_after = 1;
5245						}
5246					}
5247					if ($rtrim_before || $space_after) {
5248						if ($rtrim_before) {
5249							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5250						} else {
5251							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5252						}
5253						if ($space_after) {
5254							$good .= " ";
5255						}
5256					}
5257
5258				# '*' as part of a type definition -- reported already.
5259				} elsif ($opv eq '*_') {
5260					#warn "'*' is part of type\n";
5261
5262				# unary operators should have a space before and
5263				# none after.  May be left adjacent to another
5264				# unary operator, or a cast
5265				} elsif ($op eq '!' || $op eq '~' ||
5266					 $opv eq '*U' || $opv eq '-U' ||
5267					 $opv eq '&U' || $opv eq '&&U') {
5268					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5269						if (ERROR("SPACING",
5270							  "space required before that '$op' $at\n" . $hereptr)) {
5271							if ($n != $last_after + 2) {
5272								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5273								$line_fixed = 1;
5274							}
5275						}
5276					}
5277					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5278						# A unary '*' may be const
5279
5280					} elsif ($ctx =~ /.xW/) {
5281						if (ERROR("SPACING",
5282							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5283							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5284							if (defined $fix_elements[$n + 2]) {
5285								$fix_elements[$n + 2] =~ s/^\s+//;
5286							}
5287							$line_fixed = 1;
5288						}
5289					}
5290
5291				# unary ++ and unary -- are allowed no space on one side.
5292				} elsif ($op eq '++' or $op eq '--') {
5293					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5294						if (ERROR("SPACING",
5295							  "space required one side of that '$op' $at\n" . $hereptr)) {
5296							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5297							$line_fixed = 1;
5298						}
5299					}
5300					if ($ctx =~ /Wx[BE]/ ||
5301					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5302						if (ERROR("SPACING",
5303							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5304							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5305							$line_fixed = 1;
5306						}
5307					}
5308					if ($ctx =~ /ExW/) {
5309						if (ERROR("SPACING",
5310							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5311							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5312							if (defined $fix_elements[$n + 2]) {
5313								$fix_elements[$n + 2] =~ s/^\s+//;
5314							}
5315							$line_fixed = 1;
5316						}
5317					}
5318
5319				# << and >> may either have or not have spaces both sides
5320				} elsif ($op eq '<<' or $op eq '>>' or
5321					 $op eq '&' or $op eq '^' or $op eq '|' or
5322					 $op eq '+' or $op eq '-' or
5323					 $op eq '*' or $op eq '/' or
5324					 $op eq '%')
5325				{
5326					if ($check) {
5327						if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5328							if (CHK("SPACING",
5329								"spaces preferred around that '$op' $at\n" . $hereptr)) {
5330								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5331								$fix_elements[$n + 2] =~ s/^\s+//;
5332								$line_fixed = 1;
5333							}
5334						} elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5335							if (CHK("SPACING",
5336								"space preferred before that '$op' $at\n" . $hereptr)) {
5337								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5338								$line_fixed = 1;
5339							}
5340						}
5341					} elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5342						if (ERROR("SPACING",
5343							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
5344							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5345							if (defined $fix_elements[$n + 2]) {
5346								$fix_elements[$n + 2] =~ s/^\s+//;
5347							}
5348							$line_fixed = 1;
5349						}
5350					}
5351
5352				# A colon needs no spaces before when it is
5353				# terminating a case value or a label.
5354				} elsif ($opv eq ':C' || $opv eq ':L') {
5355					if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5356						if (ERROR("SPACING",
5357							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5358							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5359							$line_fixed = 1;
5360						}
5361					}
5362
5363				# All the others need spaces both sides.
5364				} elsif ($ctx !~ /[EWC]x[CWE]/) {
5365					my $ok = 0;
5366
5367					# Ignore email addresses <foo@bar>
5368					if (($op eq '<' &&
5369					     $cc =~ /^\S+\@\S+>/) ||
5370					    ($op eq '>' &&
5371					     $ca =~ /<\S+\@\S+$/))
5372					{
5373						$ok = 1;
5374					}
5375
5376					# for asm volatile statements
5377					# ignore a colon with another
5378					# colon immediately before or after
5379					if (($op eq ':') &&
5380					    ($ca =~ /:$/ || $cc =~ /^:/)) {
5381						$ok = 1;
5382					}
5383
5384					# messages are ERROR, but ?: are CHK
5385					if ($ok == 0) {
5386						my $msg_level = \&ERROR;
5387						$msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5388
5389						if (&{$msg_level}("SPACING",
5390								  "spaces required around that '$op' $at\n" . $hereptr)) {
5391							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5392							if (defined $fix_elements[$n + 2]) {
5393								$fix_elements[$n + 2] =~ s/^\s+//;
5394							}
5395							$line_fixed = 1;
5396						}
5397					}
5398				}
5399				$off += length($elements[$n + 1]);
5400
5401##				print("n: <$n> GOOD: <$good>\n");
5402
5403				$fixed_line = $fixed_line . $good;
5404			}
5405
5406			if (($#elements % 2) == 0) {
5407				$fixed_line = $fixed_line . $fix_elements[$#elements];
5408			}
5409
5410			if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5411				$fixed[$fixlinenr] = $fixed_line;
5412			}
5413
5414
5415		}
5416
5417# check for whitespace before a non-naked semicolon
5418		if ($line =~ /^\+.*\S\s+;\s*$/) {
5419			if (WARN("SPACING",
5420				 "space prohibited before semicolon\n" . $herecurr) &&
5421			    $fix) {
5422				1 while $fixed[$fixlinenr] =~
5423				    s/^(\+.*\S)\s+;/$1;/;
5424			}
5425		}
5426
5427# check for multiple assignments
5428		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5429			CHK("MULTIPLE_ASSIGNMENTS",
5430			    "multiple assignments should be avoided\n" . $herecurr);
5431		}
5432
5433## # check for multiple declarations, allowing for a function declaration
5434## # continuation.
5435## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5436## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5437##
5438## 			# Remove any bracketed sections to ensure we do not
5439## 			# falsely report the parameters of functions.
5440## 			my $ln = $line;
5441## 			while ($ln =~ s/\([^\(\)]*\)//g) {
5442## 			}
5443## 			if ($ln =~ /,/) {
5444## 				WARN("MULTIPLE_DECLARATION",
5445##				     "declaring multiple variables together should be avoided\n" . $herecurr);
5446## 			}
5447## 		}
5448
5449#need space before brace following if, while, etc
5450		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5451		    $line =~ /\b(?:else|do)\{/) {
5452			if (ERROR("SPACING",
5453				  "space required before the open brace '{'\n" . $herecurr) &&
5454			    $fix) {
5455				$fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5456			}
5457		}
5458
5459## # check for blank lines before declarations
5460##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5461##		    $prevrawline =~ /^.\s*$/) {
5462##			WARN("SPACING",
5463##			     "No blank lines before declarations\n" . $hereprev);
5464##		}
5465##
5466
5467# closing brace should have a space following it when it has anything
5468# on the line
5469		if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5470			if (ERROR("SPACING",
5471				  "space required after that close brace '}'\n" . $herecurr) &&
5472			    $fix) {
5473				$fixed[$fixlinenr] =~
5474				    s/}((?!(?:,|;|\)))\S)/} $1/;
5475			}
5476		}
5477
5478# check spacing on square brackets
5479		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5480			if (ERROR("SPACING",
5481				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
5482			    $fix) {
5483				$fixed[$fixlinenr] =~
5484				    s/\[\s+/\[/;
5485			}
5486		}
5487		if ($line =~ /\s\]/) {
5488			if (ERROR("SPACING",
5489				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5490			    $fix) {
5491				$fixed[$fixlinenr] =~
5492				    s/\s+\]/\]/;
5493			}
5494		}
5495
5496# check spacing on parentheses
5497		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5498		    $line !~ /for\s*\(\s+;/) {
5499			if (ERROR("SPACING",
5500				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5501			    $fix) {
5502				$fixed[$fixlinenr] =~
5503				    s/\(\s+/\(/;
5504			}
5505		}
5506		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5507		    $line !~ /for\s*\(.*;\s+\)/ &&
5508		    $line !~ /:\s+\)/) {
5509			if (ERROR("SPACING",
5510				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5511			    $fix) {
5512				$fixed[$fixlinenr] =~
5513				    s/\s+\)/\)/;
5514			}
5515		}
5516
5517# check unnecessary parentheses around addressof/dereference single $Lvals
5518# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5519
5520		while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5521			my $var = $1;
5522			if (CHK("UNNECESSARY_PARENTHESES",
5523				"Unnecessary parentheses around $var\n" . $herecurr) &&
5524			    $fix) {
5525				$fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5526			}
5527		}
5528
5529# check for unnecessary parentheses around function pointer uses
5530# ie: (foo->bar)(); should be foo->bar();
5531# but not "if (foo->bar) (" to avoid some false positives
5532		if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5533			my $var = $2;
5534			if (CHK("UNNECESSARY_PARENTHESES",
5535				"Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5536			    $fix) {
5537				my $var2 = deparenthesize($var);
5538				$var2 =~ s/\s//g;
5539				$fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5540			}
5541		}
5542
5543# check for unnecessary parentheses around comparisons
5544# except in drivers/staging
5545		if (($realfile !~ m@^(?:drivers/staging/)@) &&
5546		    $perl_version_ok && defined($stat) &&
5547		    $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5548			my $if_stat = $1;
5549			my $test = substr($2, 1, -1);
5550			my $herectx;
5551			while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5552				my $match = $1;
5553				# avoid parentheses around potential macro args
5554				next if ($match =~ /^\s*\w+\s*$/);
5555				if (!defined($herectx)) {
5556					$herectx = $here . "\n";
5557					my $cnt = statement_rawlines($if_stat);
5558					for (my $n = 0; $n < $cnt; $n++) {
5559						my $rl = raw_line($linenr, $n);
5560						$herectx .=  $rl . "\n";
5561						last if $rl =~ /^[ \+].*\{/;
5562					}
5563				}
5564				CHK("UNNECESSARY_PARENTHESES",
5565				    "Unnecessary parentheses around '$match'\n" . $herectx);
5566			}
5567		}
5568
5569# check that goto labels aren't indented (allow a single space indentation)
5570# and ignore bitfield definitions like foo:1
5571# Strictly, labels can have whitespace after the identifier and before the :
5572# but this is not allowed here as many ?: uses would appear to be labels
5573		if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5574		    $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5575		    $sline !~ /^.\s+default:/) {
5576			if (WARN("INDENTED_LABEL",
5577				 "labels should not be indented\n" . $herecurr) &&
5578			    $fix) {
5579				$fixed[$fixlinenr] =~
5580				    s/^(.)\s+/$1/;
5581			}
5582		}
5583
5584# check if a statement with a comma should be two statements like:
5585#	foo = bar(),	/* comma should be semicolon */
5586#	bar = baz();
5587		if (defined($stat) &&
5588		    $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5589			my $cnt = statement_rawlines($stat);
5590			my $herectx = get_stat_here($linenr, $cnt, $here);
5591			WARN("SUSPECT_COMMA_SEMICOLON",
5592			     "Possible comma where semicolon could be used\n" . $herectx);
5593		}
5594
5595# return is not a function
5596		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5597			my $spacing = $1;
5598			if ($perl_version_ok &&
5599			    $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5600				my $value = $1;
5601				$value = deparenthesize($value);
5602				if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5603					ERROR("RETURN_PARENTHESES",
5604					      "return is not a function, parentheses are not required\n" . $herecurr);
5605				}
5606			} elsif ($spacing !~ /\s+/) {
5607				ERROR("SPACING",
5608				      "space required before the open parenthesis '('\n" . $herecurr);
5609			}
5610		}
5611
5612# unnecessary return in a void function
5613# at end-of-function, with the previous line a single leading tab, then return;
5614# and the line before that not a goto label target like "out:"
5615		if ($sline =~ /^[ \+]}\s*$/ &&
5616		    $prevline =~ /^\+\treturn\s*;\s*$/ &&
5617		    $linenr >= 3 &&
5618		    $lines[$linenr - 3] =~ /^[ +]/ &&
5619		    $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5620			WARN("RETURN_VOID",
5621			     "void function return statements are not generally useful\n" . $hereprev);
5622		}
5623
5624# if statements using unnecessary parentheses - ie: if ((foo == bar))
5625		if ($perl_version_ok &&
5626		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
5627			my $openparens = $1;
5628			my $count = $openparens =~ tr@\(@\(@;
5629			my $msg = "";
5630			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5631				my $comp = $4;	#Not $1 because of $LvalOrFunc
5632				$msg = " - maybe == should be = ?" if ($comp eq "==");
5633				WARN("UNNECESSARY_PARENTHESES",
5634				     "Unnecessary parentheses$msg\n" . $herecurr);
5635			}
5636		}
5637
5638# comparisons with a constant or upper case identifier on the left
5639#	avoid cases like "foo + BAR < baz"
5640#	only fix matches surrounded by parentheses to avoid incorrect
5641#	conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5642		if ($perl_version_ok &&
5643		    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5644			my $lead = $1;
5645			my $const = $2;
5646			my $comp = $3;
5647			my $to = $4;
5648			my $newcomp = $comp;
5649			if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5650			    $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5651			    WARN("CONSTANT_COMPARISON",
5652				 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5653			    $fix) {
5654				if ($comp eq "<") {
5655					$newcomp = ">";
5656				} elsif ($comp eq "<=") {
5657					$newcomp = ">=";
5658				} elsif ($comp eq ">") {
5659					$newcomp = "<";
5660				} elsif ($comp eq ">=") {
5661					$newcomp = "<=";
5662				}
5663				$fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5664			}
5665		}
5666
5667# Return of what appears to be an errno should normally be negative
5668		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5669			my $name = $1;
5670			if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5671				WARN("USE_NEGATIVE_ERRNO",
5672				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5673			}
5674		}
5675
5676# Need a space before open parenthesis after if, while etc
5677		if ($line =~ /\b(if|while|for|switch)\(/) {
5678			if (ERROR("SPACING",
5679				  "space required before the open parenthesis '('\n" . $herecurr) &&
5680			    $fix) {
5681				$fixed[$fixlinenr] =~
5682				    s/\b(if|while|for|switch)\(/$1 \(/;
5683			}
5684		}
5685
5686# Check for illegal assignment in if conditional -- and check for trailing
5687# statements after the conditional.
5688		if ($line =~ /do\s*(?!{)/) {
5689			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5690				ctx_statement_block($linenr, $realcnt, 0)
5691					if (!defined $stat);
5692			my ($stat_next) = ctx_statement_block($line_nr_next,
5693						$remain_next, $off_next);
5694			$stat_next =~ s/\n./\n /g;
5695			##print "stat<$stat> stat_next<$stat_next>\n";
5696
5697			if ($stat_next =~ /^\s*while\b/) {
5698				# If the statement carries leading newlines,
5699				# then count those as offsets.
5700				my ($whitespace) =
5701					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5702				my $offset =
5703					statement_rawlines($whitespace) - 1;
5704
5705				$suppress_whiletrailers{$line_nr_next +
5706								$offset} = 1;
5707			}
5708		}
5709		if (!defined $suppress_whiletrailers{$linenr} &&
5710		    defined($stat) && defined($cond) &&
5711		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5712			my ($s, $c) = ($stat, $cond);
5713			my $fixed_assign_in_if = 0;
5714
5715			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5716				if (ERROR("ASSIGN_IN_IF",
5717					  "do not use assignment in if condition\n" . $herecurr) &&
5718				    $fix && $perl_version_ok) {
5719					if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5720						my $space = $1;
5721						my $not = $2;
5722						my $statement = $3;
5723						my $assigned = $4;
5724						my $test = $8;
5725						my $against = $9;
5726						my $brace = $15;
5727						fix_delete_line($fixlinenr, $rawline);
5728						fix_insert_line($fixlinenr, "$space$statement;");
5729						my $newline = "${space}if (";
5730						$newline .= '!' if defined($not);
5731						$newline .= '(' if (defined $not && defined($test) && defined($against));
5732						$newline .= "$assigned";
5733						$newline .= " $test $against" if (defined($test) && defined($against));
5734						$newline .= ')' if (defined $not && defined($test) && defined($against));
5735						$newline .= ')';
5736						$newline .= " {" if (defined($brace));
5737						fix_insert_line($fixlinenr + 1, $newline);
5738						$fixed_assign_in_if = 1;
5739					}
5740				}
5741			}
5742
5743			# Find out what is on the end of the line after the
5744			# conditional.
5745			substr($s, 0, length($c), '');
5746			$s =~ s/\n.*//g;
5747			$s =~ s/$;//g;	# Remove any comments
5748			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5749			    $c !~ /}\s*while\s*/)
5750			{
5751				# Find out how long the conditional actually is.
5752				my @newlines = ($c =~ /\n/gs);
5753				my $cond_lines = 1 + $#newlines;
5754				my $stat_real = '';
5755
5756				$stat_real = raw_line($linenr, $cond_lines)
5757							. "\n" if ($cond_lines);
5758				if (defined($stat_real) && $cond_lines > 1) {
5759					$stat_real = "[...]\n$stat_real";
5760				}
5761
5762				if (ERROR("TRAILING_STATEMENTS",
5763					  "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5764				    !$fixed_assign_in_if &&
5765				    $cond_lines == 0 &&
5766				    $fix && $perl_version_ok &&
5767				    $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5768					my $indent = $1;
5769					my $test = $2;
5770					my $rest = rtrim($4);
5771					if ($rest =~ /;$/) {
5772						$fixed[$fixlinenr] = "\+$indent$test";
5773						fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5774					}
5775				}
5776			}
5777		}
5778
5779# Check for bitwise tests written as boolean
5780		if ($line =~ /
5781			(?:
5782				(?:\[|\(|\&\&|\|\|)
5783				\s*0[xX][0-9]+\s*
5784				(?:\&\&|\|\|)
5785			|
5786				(?:\&\&|\|\|)
5787				\s*0[xX][0-9]+\s*
5788				(?:\&\&|\|\||\)|\])
5789			)/x)
5790		{
5791			WARN("HEXADECIMAL_BOOLEAN_TEST",
5792			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5793		}
5794
5795# if and else should not have general statements after it
5796		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5797			my $s = $1;
5798			$s =~ s/$;//g;	# Remove any comments
5799			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5800				ERROR("TRAILING_STATEMENTS",
5801				      "trailing statements should be on next line\n" . $herecurr);
5802			}
5803		}
5804# if should not continue a brace
5805		if ($line =~ /}\s*if\b/) {
5806			ERROR("TRAILING_STATEMENTS",
5807			      "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5808				$herecurr);
5809		}
5810# case and default should not have general statements after them
5811		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5812		    $line !~ /\G(?:
5813			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5814			\s*return\s+
5815		    )/xg)
5816		{
5817			ERROR("TRAILING_STATEMENTS",
5818			      "trailing statements should be on next line\n" . $herecurr);
5819		}
5820
5821		# Check for }<nl>else {, these must be at the same
5822		# indent level to be relevant to each other.
5823		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5824		    $previndent == $indent) {
5825			if (ERROR("ELSE_AFTER_BRACE",
5826				  "else should follow close brace '}'\n" . $hereprev) &&
5827			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5828				fix_delete_line($fixlinenr - 1, $prevrawline);
5829				fix_delete_line($fixlinenr, $rawline);
5830				my $fixedline = $prevrawline;
5831				$fixedline =~ s/}\s*$//;
5832				if ($fixedline !~ /^\+\s*$/) {
5833					fix_insert_line($fixlinenr, $fixedline);
5834				}
5835				$fixedline = $rawline;
5836				$fixedline =~ s/^(.\s*)else/$1} else/;
5837				fix_insert_line($fixlinenr, $fixedline);
5838			}
5839		}
5840
5841		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5842		    $previndent == $indent) {
5843			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5844
5845			# Find out what is on the end of the line after the
5846			# conditional.
5847			substr($s, 0, length($c), '');
5848			$s =~ s/\n.*//g;
5849
5850			if ($s =~ /^\s*;/) {
5851				if (ERROR("WHILE_AFTER_BRACE",
5852					  "while should follow close brace '}'\n" . $hereprev) &&
5853				    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5854					fix_delete_line($fixlinenr - 1, $prevrawline);
5855					fix_delete_line($fixlinenr, $rawline);
5856					my $fixedline = $prevrawline;
5857					my $trailing = $rawline;
5858					$trailing =~ s/^\+//;
5859					$trailing = trim($trailing);
5860					$fixedline =~ s/}\s*$/} $trailing/;
5861					fix_insert_line($fixlinenr, $fixedline);
5862				}
5863			}
5864		}
5865
5866#Specific variable tests
5867		while ($line =~ m{($Constant|$Lval)}g) {
5868			my $var = $1;
5869
5870#CamelCase
5871			if ($var !~ /^$Constant$/ &&
5872			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5873#Ignore C keywords
5874			    $var !~ /^_Generic$/ &&
5875#Ignore some autogenerated defines and enum values
5876			    $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5877#Ignore Page<foo> variants
5878			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5879#Ignore ETHTOOL_LINK_MODE_<foo> variants
5880			    $var !~ /^ETHTOOL_LINK_MODE_/ &&
5881#Ignore SI style variants like nS, mV and dB
5882#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5883			    $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5884#Ignore some three character SI units explicitly, like MiB and KHz
5885			    $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5886				while ($var =~ m{\b($Ident)}g) {
5887					my $word = $1;
5888					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5889					if ($check) {
5890						seed_camelcase_includes();
5891						if (!$file && !$camelcase_file_seeded) {
5892							seed_camelcase_file($realfile);
5893							$camelcase_file_seeded = 1;
5894						}
5895					}
5896					if (!defined $camelcase{$word}) {
5897						$camelcase{$word} = 1;
5898						CHK("CAMELCASE",
5899						    "Avoid CamelCase: <$word>\n" . $herecurr);
5900					}
5901				}
5902			}
5903		}
5904
5905#no spaces allowed after \ in define
5906		if ($line =~ /\#\s*define.*\\\s+$/) {
5907			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5908				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5909			    $fix) {
5910				$fixed[$fixlinenr] =~ s/\s+$//;
5911			}
5912		}
5913
5914# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5915# itself <asm/foo.h> (uses RAW line)
5916		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5917			my $file = "$1.h";
5918			my $checkfile = "include/linux/$file";
5919			if (-f "$root/$checkfile" &&
5920			    $realfile ne $checkfile &&
5921			    $1 !~ /$allowed_asm_includes/)
5922			{
5923				my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5924				if ($asminclude > 0) {
5925					if ($realfile =~ m{^arch/}) {
5926						CHK("ARCH_INCLUDE_LINUX",
5927						    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5928					} else {
5929						WARN("INCLUDE_LINUX",
5930						     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5931					}
5932				}
5933			}
5934		}
5935
5936# Usually multi-statement macros should be enclosed in a do {} while
5937# (0) loop.  Grab the first statement and ensure its the whole macro
5938# if its not enclosed in a known good container
5939		if ($realfile !~ m@/vmlinux.lds.h$@ &&
5940		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5941			my $ln = $linenr;
5942			my $cnt = $realcnt;
5943			my ($off, $dstat, $dcond, $rest);
5944			my $ctx = '';
5945			my $has_flow_statement = 0;
5946			my $has_arg_concat = 0;
5947			($dstat, $dcond, $ln, $cnt, $off) =
5948				ctx_statement_block($linenr, $realcnt, 0);
5949			$ctx = $dstat;
5950			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5951			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5952
5953			$has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5954			$has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5955
5956			$dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5957			my $define_args = $1;
5958			my $define_stmt = $dstat;
5959			my @def_args = ();
5960
5961			if (defined $define_args && $define_args ne "") {
5962				$define_args = substr($define_args, 1, length($define_args) - 2);
5963				$define_args =~ s/\s*//g;
5964				$define_args =~ s/\\\+?//g;
5965				@def_args = split(",", $define_args);
5966			}
5967
5968			$dstat =~ s/$;//g;
5969			$dstat =~ s/\\\n.//g;
5970			$dstat =~ s/^\s*//s;
5971			$dstat =~ s/\s*$//s;
5972
5973			# Flatten any parentheses and braces
5974			while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5975			       $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5976			       $dstat =~ s/.\[[^\[\]]*\]/1u/)
5977			{
5978			}
5979
5980			# Flatten any obvious string concatenation.
5981			while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5982			       $dstat =~ s/$Ident\s*($String)/$1/)
5983			{
5984			}
5985
5986			# Make asm volatile uses seem like a generic function
5987			$dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5988
5989			my $exceptions = qr{
5990				$Declare|
5991				# named exceptions
5992				module_param_named|
5993				MODULE_PARM_DESC|
5994				DECLARE_PER_CPU|
5995				DEFINE_PER_CPU|
5996				static_assert|
5997				# declaration primitives
5998				__typeof__\(|
5999				union|
6000				struct|
6001				\.$Ident\s*=\s*|
6002				^\"|\"$|
6003				^\[
6004			}x;
6005			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
6006
6007			$ctx =~ s/\n*$//;
6008			my $stmt_cnt = statement_rawlines($ctx);
6009			my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
6010
6011			if ($dstat ne '' &&
6012			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
6013			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
6014			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
6015			    $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&			# character constants
6016			    $dstat !~ /$exceptions/ &&
6017			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
6018			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
6019			    $dstat !~ /^case\b/ &&					# case ...
6020			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
6021			    $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ &&		# while (...) {...}
6022			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
6023			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
6024			    $dstat !~ /^do\s*{/ &&					# do {...
6025			    $dstat !~ /^\(\{/ &&						# ({...
6026			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
6027			{
6028				if ($dstat =~ /^\s*if\b/) {
6029					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6030					      "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
6031				} elsif ($dstat =~ /;/) {
6032					WARN("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6033					      "Non-declarative macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6034				} else {
6035					ERROR("COMPLEX_MACRO",
6036					      "Macros with complex values should be enclosed in parentheses\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6037				}
6038
6039			}
6040
6041			# Make $define_stmt single line, comment-free, etc
6042			my @stmt_array = split('\n', $define_stmt);
6043			my $first = 1;
6044			$define_stmt = "";
6045			foreach my $l (@stmt_array) {
6046				$l =~ s/\\$//;
6047				if ($first) {
6048					$define_stmt = $l;
6049					$first = 0;
6050				} elsif ($l =~ /^[\+ ]/) {
6051					$define_stmt .= substr($l, 1);
6052				}
6053			}
6054			$define_stmt =~ s/$;//g;
6055			$define_stmt =~ s/\s+/ /g;
6056			$define_stmt = trim($define_stmt);
6057
6058# check if any macro arguments are reused (ignore '...' and 'type')
6059			foreach my $arg (@def_args) {
6060			        next if ($arg =~ /\.\.\./);
6061			        next if ($arg =~ /^type$/i);
6062				my $tmp_stmt = $define_stmt;
6063				$tmp_stmt =~ s/\b(__must_be_array|offsetof|sizeof|sizeof_field|__stringify|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
6064				$tmp_stmt =~ s/\#+\s*$arg\b//g;
6065				$tmp_stmt =~ s/\b$arg\s*\#\#//g;
6066				my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6067				if ($use_cnt > 1) {
6068					CHK("MACRO_ARG_REUSE",
6069					    "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6070				    }
6071# check if any macro arguments may have other precedence issues
6072				if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6073				    ((defined($1) && $1 ne ',') ||
6074				     (defined($2) && $2 ne ','))) {
6075					CHK("MACRO_ARG_PRECEDENCE",
6076					    "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6077				}
6078
6079# check if this is an unused argument
6080				if ($define_stmt !~ /\b$arg\b/ && $define_stmt) {
6081					WARN("MACRO_ARG_UNUSED",
6082					     "Argument '$arg' is not used in function-like macro\n" . "$herectx");
6083				}
6084			}
6085
6086# check for macros with flow control, but without ## concatenation
6087# ## concatenation is commonly a macro that defines a function so ignore those
6088			if ($has_flow_statement && !$has_arg_concat) {
6089				my $cnt = statement_rawlines($ctx);
6090				my $herectx = get_stat_here($linenr, $cnt, $here);
6091
6092				WARN("MACRO_WITH_FLOW_CONTROL",
6093				     "Macros with flow control statements should be avoided\n" . "$herectx");
6094			}
6095
6096# check for line continuations outside of #defines, preprocessor #, and asm
6097
6098		} elsif ($realfile =~ m@/vmlinux.lds.h$@) {
6099		    $line =~ s/(\w+)/$maybe_linker_symbol{$1}++/ge;
6100		    #print "REAL: $realfile\nln: $line\nkeys:", sort keys %maybe_linker_symbol;
6101		} else {
6102			if ($prevline !~ /^..*\\$/ &&
6103			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
6104			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
6105			    $line =~ /^\+.*\\$/) {
6106				WARN("LINE_CONTINUATIONS",
6107				     "Avoid unnecessary line continuations\n" . $herecurr);
6108			}
6109		}
6110
6111# do {} while (0) macro tests:
6112# single-statement macros do not need to be enclosed in do while (0) loop,
6113# macro should not end with a semicolon
6114		if ($perl_version_ok &&
6115		    $realfile !~ m@/vmlinux.lds.h$@ &&
6116		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6117			my $ln = $linenr;
6118			my $cnt = $realcnt;
6119			my ($off, $dstat, $dcond, $rest);
6120			my $ctx = '';
6121			($dstat, $dcond, $ln, $cnt, $off) =
6122				ctx_statement_block($linenr, $realcnt, 0);
6123			$ctx = $dstat;
6124
6125			$dstat =~ s/\\\n.//g;
6126			$dstat =~ s/$;/ /g;
6127
6128			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6129				my $stmts = $2;
6130				my $semis = $3;
6131
6132				$ctx =~ s/\n*$//;
6133				my $cnt = statement_rawlines($ctx);
6134				my $herectx = get_stat_here($linenr, $cnt, $here);
6135
6136				if (($stmts =~ tr/;/;/) == 1 &&
6137				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
6138					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6139					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6140				}
6141				if (defined $semis && $semis ne "") {
6142					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6143					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6144				}
6145			} elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6146				$ctx =~ s/\n*$//;
6147				my $cnt = statement_rawlines($ctx);
6148				my $herectx = get_stat_here($linenr, $cnt, $here);
6149
6150				WARN("TRAILING_SEMICOLON",
6151				     "macros should not use a trailing semicolon\n" . "$herectx");
6152			}
6153		}
6154
6155# check for redundant bracing round if etc
6156		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6157			my ($level, $endln, @chunks) =
6158				ctx_statement_full($linenr, $realcnt, 1);
6159			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6160			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6161			if ($#chunks > 0 && $level == 0) {
6162				my @allowed = ();
6163				my $allow = 0;
6164				my $seen = 0;
6165				my $herectx = $here . "\n";
6166				my $ln = $linenr - 1;
6167				for my $chunk (@chunks) {
6168					my ($cond, $block) = @{$chunk};
6169
6170					# If the condition carries leading newlines, then count those as offsets.
6171					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6172					my $offset = statement_rawlines($whitespace) - 1;
6173
6174					$allowed[$allow] = 0;
6175					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6176
6177					# We have looked at and allowed this specific line.
6178					$suppress_ifbraces{$ln + $offset} = 1;
6179
6180					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6181					$ln += statement_rawlines($block) - 1;
6182
6183					substr($block, 0, length($cond), '');
6184
6185					$seen++ if ($block =~ /^\s*{/);
6186
6187					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6188					if (statement_lines($cond) > 1) {
6189						#print "APW: ALLOWED: cond<$cond>\n";
6190						$allowed[$allow] = 1;
6191					}
6192					if ($block =~/\b(?:if|for|while)\b/) {
6193						#print "APW: ALLOWED: block<$block>\n";
6194						$allowed[$allow] = 1;
6195					}
6196					if (statement_block_size($block) > 1) {
6197						#print "APW: ALLOWED: lines block<$block>\n";
6198						$allowed[$allow] = 1;
6199					}
6200					$allow++;
6201				}
6202				if ($seen) {
6203					my $sum_allowed = 0;
6204					foreach (@allowed) {
6205						$sum_allowed += $_;
6206					}
6207					if ($sum_allowed == 0) {
6208						WARN("BRACES",
6209						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
6210					} elsif ($sum_allowed != $allow &&
6211						 $seen != $allow) {
6212						CHK("BRACES",
6213						    "braces {} should be used on all arms of this statement\n" . $herectx);
6214					}
6215				}
6216			}
6217		}
6218		if (!defined $suppress_ifbraces{$linenr - 1} &&
6219					$line =~ /\b(if|while|for|else)\b/) {
6220			my $allowed = 0;
6221
6222			# Check the pre-context.
6223			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6224				#print "APW: ALLOWED: pre<$1>\n";
6225				$allowed = 1;
6226			}
6227
6228			my ($level, $endln, @chunks) =
6229				ctx_statement_full($linenr, $realcnt, $-[0]);
6230
6231			# Check the condition.
6232			my ($cond, $block) = @{$chunks[0]};
6233			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6234			if (defined $cond) {
6235				substr($block, 0, length($cond), '');
6236			}
6237			if (statement_lines($cond) > 1) {
6238				#print "APW: ALLOWED: cond<$cond>\n";
6239				$allowed = 1;
6240			}
6241			if ($block =~/\b(?:if|for|while)\b/) {
6242				#print "APW: ALLOWED: block<$block>\n";
6243				$allowed = 1;
6244			}
6245			if (statement_block_size($block) > 1) {
6246				#print "APW: ALLOWED: lines block<$block>\n";
6247				$allowed = 1;
6248			}
6249			# Check the post-context.
6250			if (defined $chunks[1]) {
6251				my ($cond, $block) = @{$chunks[1]};
6252				if (defined $cond) {
6253					substr($block, 0, length($cond), '');
6254				}
6255				if ($block =~ /^\s*\{/) {
6256					#print "APW: ALLOWED: chunk-1 block<$block>\n";
6257					$allowed = 1;
6258				}
6259			}
6260			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6261				my $cnt = statement_rawlines($block);
6262				my $herectx = get_stat_here($linenr, $cnt, $here);
6263
6264				WARN("BRACES",
6265				     "braces {} are not necessary for single statement blocks\n" . $herectx);
6266			}
6267		}
6268
6269# check for single line unbalanced braces
6270		if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6271		    $sline =~ /^.\s*else\s*\{\s*$/) {
6272			CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6273		}
6274
6275# check for unnecessary blank lines around braces
6276		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6277			if (CHK("BRACES",
6278				"Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6279			    $fix && $prevrawline =~ /^\+/) {
6280				fix_delete_line($fixlinenr - 1, $prevrawline);
6281			}
6282		}
6283		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6284			if (CHK("BRACES",
6285				"Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6286			    $fix) {
6287				fix_delete_line($fixlinenr, $rawline);
6288			}
6289		}
6290
6291# no volatiles please
6292		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6293		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6294			WARN("VOLATILE",
6295			     "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6296		}
6297
6298# Check for user-visible strings broken across lines, which breaks the ability
6299# to grep for the string.  Make exceptions when the previous string ends in a
6300# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6301# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6302		if ($line =~ /^\+\s*$String/ &&
6303		    $prevline =~ /"\s*$/ &&
6304		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6305			if (WARN("SPLIT_STRING",
6306				 "quoted string split across lines\n" . $hereprev) &&
6307				     $fix &&
6308				     $prevrawline =~ /^\+.*"\s*$/ &&
6309				     $last_coalesced_string_linenr != $linenr - 1) {
6310				my $extracted_string = get_quoted_string($line, $rawline);
6311				my $comma_close = "";
6312				if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6313					$comma_close = $1;
6314				}
6315
6316				fix_delete_line($fixlinenr - 1, $prevrawline);
6317				fix_delete_line($fixlinenr, $rawline);
6318				my $fixedline = $prevrawline;
6319				$fixedline =~ s/"\s*$//;
6320				$fixedline .= substr($extracted_string, 1) . trim($comma_close);
6321				fix_insert_line($fixlinenr - 1, $fixedline);
6322				$fixedline = $rawline;
6323				$fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6324				if ($fixedline !~ /\+\s*$/) {
6325					fix_insert_line($fixlinenr, $fixedline);
6326				}
6327				$last_coalesced_string_linenr = $linenr;
6328			}
6329		}
6330
6331# check for missing a space in a string concatenation
6332		if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6333			WARN('MISSING_SPACE',
6334			     "break quoted strings at a space character\n" . $hereprev);
6335		}
6336
6337# check for an embedded function name in a string when the function is known
6338# This does not work very well for -f --file checking as it depends on patch
6339# context providing the function name or a single line form for in-file
6340# function declarations
6341		if ($line =~ /^\+.*$String/ &&
6342		    defined($context_function) &&
6343		    get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6344		    length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6345			WARN("EMBEDDED_FUNCTION_NAME",
6346			     "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6347		}
6348
6349# check for unnecessary function tracing like uses
6350# This does not use $logFunctions because there are many instances like
6351# 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6352		if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6353			if (WARN("TRACING_LOGGING",
6354				 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6355			    $fix) {
6356                                fix_delete_line($fixlinenr, $rawline);
6357			}
6358		}
6359
6360# check for spaces before a quoted newline
6361		if ($rawline =~ /^.*\".*\s\\n/) {
6362			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6363				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6364			    $fix) {
6365				$fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6366			}
6367
6368		}
6369
6370# concatenated string without spaces between elements
6371		if ($line =~ /$String[A-Z_]/ ||
6372		    ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6373			if (CHK("CONCATENATED_STRING",
6374				"Concatenated strings should use spaces between elements\n" . $herecurr) &&
6375			    $fix) {
6376				while ($line =~ /($String)/g) {
6377					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6378					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6379					$fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6380				}
6381			}
6382		}
6383
6384# uncoalesced string fragments
6385		if ($line =~ /$String\s*[Lu]?"/) {
6386			if (WARN("STRING_FRAGMENTS",
6387				 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6388			    $fix) {
6389				while ($line =~ /($String)(?=\s*")/g) {
6390					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6391					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6392				}
6393			}
6394		}
6395
6396# check for non-standard and hex prefixed decimal printf formats
6397		my $show_L = 1;	#don't show the same defect twice
6398		my $show_Z = 1;
6399		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6400			my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6401			$string =~ s/%%/__/g;
6402			# check for %L
6403			if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6404				WARN("PRINTF_L",
6405				     "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6406				$show_L = 0;
6407			}
6408			# check for %Z
6409			if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6410				WARN("PRINTF_Z",
6411				     "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6412				$show_Z = 0;
6413			}
6414			# check for 0x<decimal>
6415			if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6416				ERROR("PRINTF_0XDECIMAL",
6417				      "Prefixing 0x with decimal output is defective\n" . $herecurr);
6418			}
6419		}
6420
6421# check for line continuations in quoted strings with odd counts of "
6422		if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6423			WARN("LINE_CONTINUATIONS",
6424			     "Avoid line continuations in quoted strings\n" . $herecurr);
6425		}
6426
6427# warn about #if 0
6428		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6429			WARN("IF_0",
6430			     "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6431		}
6432
6433# warn about #if 1
6434		if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6435			WARN("IF_1",
6436			     "Consider removing the #if 1 and its #endif\n" . $herecurr);
6437		}
6438
6439# check for needless "if (<foo>) fn(<foo>)" uses
6440		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6441			my $tested = quotemeta($1);
6442			my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6443			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6444				my $func = $1;
6445				if (WARN('NEEDLESS_IF',
6446					 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6447				    $fix) {
6448					my $do_fix = 1;
6449					my $leading_tabs = "";
6450					my $new_leading_tabs = "";
6451					if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6452						$leading_tabs = $1;
6453					} else {
6454						$do_fix = 0;
6455					}
6456					if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6457						$new_leading_tabs = $1;
6458						if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6459							$do_fix = 0;
6460						}
6461					} else {
6462						$do_fix = 0;
6463					}
6464					if ($do_fix) {
6465						fix_delete_line($fixlinenr - 1, $prevrawline);
6466						$fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6467					}
6468				}
6469			}
6470		}
6471
6472# check for unnecessary "Out of Memory" messages
6473		if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6474		    $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6475		    (defined $1 || defined $3) &&
6476		    $linenr > 3) {
6477			my $testval = $2;
6478			my $testline = $lines[$linenr - 3];
6479
6480			my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6481#			print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6482
6483			if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6484			    $s !~ /\b__GFP_NOWARN\b/ ) {
6485				WARN("OOM_MESSAGE",
6486				     "Possible unnecessary 'out of memory' message\n" . $hereprev);
6487			}
6488		}
6489
6490# check for logging functions with KERN_<LEVEL>
6491		if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6492		    $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6493			my $level = $1;
6494			if (WARN("UNNECESSARY_KERN_LEVEL",
6495				 "Possible unnecessary $level\n" . $herecurr) &&
6496			    $fix) {
6497				$fixed[$fixlinenr] =~ s/\s*$level\s*//;
6498			}
6499		}
6500
6501# check for logging continuations
6502		if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6503			WARN("LOGGING_CONTINUATION",
6504			     "Avoid logging continuation uses where feasible\n" . $herecurr);
6505		}
6506
6507# check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6508		if (defined $stat &&
6509		    $line =~ /\b$logFunctions\s*\(/ &&
6510		    index($stat, '"') >= 0) {
6511			my $lc = $stat =~ tr@\n@@;
6512			$lc = $lc + $linenr;
6513			my $stat_real = get_stat_real($linenr, $lc);
6514			pos($stat_real) = index($stat_real, '"');
6515			while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6516				my $pspec = $1;
6517				my $h = $2;
6518				my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6519				if (WARN("UNNECESSARY_MODIFIER",
6520					 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6521				    $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6522					my $nspec = $pspec;
6523					$nspec =~ s/h//g;
6524					$fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6525				}
6526			}
6527		}
6528
6529# check for mask then right shift without a parentheses
6530		if ($perl_version_ok &&
6531		    $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6532		    $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6533			WARN("MASK_THEN_SHIFT",
6534			     "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6535		}
6536
6537# check for pointer comparisons to NULL
6538		if ($perl_version_ok) {
6539			while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6540				my $val = $1;
6541				my $equal = "!";
6542				$equal = "" if ($4 eq "!=");
6543				if (CHK("COMPARISON_TO_NULL",
6544					"Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6545					    $fix) {
6546					$fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6547				}
6548			}
6549		}
6550
6551# check for bad placement of section $InitAttribute (e.g.: __initdata)
6552		if ($line =~ /(\b$InitAttribute\b)/) {
6553			my $attr = $1;
6554			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6555				my $ptr = $1;
6556				my $var = $2;
6557				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6558				      ERROR("MISPLACED_INIT",
6559					    "$attr should be placed after $var\n" . $herecurr)) ||
6560				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6561				      WARN("MISPLACED_INIT",
6562					   "$attr should be placed after $var\n" . $herecurr))) &&
6563				    $fix) {
6564					$fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
6565				}
6566			}
6567		}
6568
6569# check for $InitAttributeData (ie: __initdata) with const
6570		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6571			my $attr = $1;
6572			$attr =~ /($InitAttributePrefix)(.*)/;
6573			my $attr_prefix = $1;
6574			my $attr_type = $2;
6575			if (ERROR("INIT_ATTRIBUTE",
6576				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6577			    $fix) {
6578				$fixed[$fixlinenr] =~
6579				    s/$InitAttributeData/${attr_prefix}initconst/;
6580			}
6581		}
6582
6583# check for $InitAttributeConst (ie: __initconst) without const
6584		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6585			my $attr = $1;
6586			if (ERROR("INIT_ATTRIBUTE",
6587				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
6588			    $fix) {
6589				my $lead = $fixed[$fixlinenr] =~
6590				    /(^\+\s*(?:static\s+))/;
6591				$lead = rtrim($1);
6592				$lead = "$lead " if ($lead !~ /^\+$/);
6593				$lead = "${lead}const ";
6594				$fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6595			}
6596		}
6597
6598# check for __read_mostly with const non-pointer (should just be const)
6599		if ($line =~ /\b__read_mostly\b/ &&
6600		    $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6601			if (ERROR("CONST_READ_MOSTLY",
6602				  "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6603			    $fix) {
6604				$fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6605			}
6606		}
6607
6608# don't use __constant_<foo> functions outside of include/uapi/
6609		if ($realfile !~ m@^include/uapi/@ &&
6610		    $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6611			my $constant_func = $1;
6612			my $func = $constant_func;
6613			$func =~ s/^__constant_//;
6614			if (WARN("CONSTANT_CONVERSION",
6615				 "$constant_func should be $func\n" . $herecurr) &&
6616			    $fix) {
6617				$fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6618			}
6619		}
6620
6621# prefer usleep_range over udelay
6622		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6623			my $delay = $1;
6624			# ignore udelay's < 10, however
6625			if (! ($delay < 10) ) {
6626				CHK("USLEEP_RANGE",
6627				    "usleep_range is preferred over udelay; see function description of usleep_range() and udelay().\n" . $herecurr);
6628			}
6629			if ($delay > 2000) {
6630				WARN("LONG_UDELAY",
6631				     "long udelay - prefer mdelay; see function description of mdelay().\n" . $herecurr);
6632			}
6633		}
6634
6635# warn about unexpectedly long msleep's
6636		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6637			if ($1 < 20) {
6638				WARN("MSLEEP",
6639				     "msleep < 20ms can sleep for up to 20ms; see function description of msleep().\n" . $herecurr);
6640			}
6641		}
6642
6643# check for comparisons of jiffies
6644		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6645			WARN("JIFFIES_COMPARISON",
6646			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6647		}
6648
6649# check for comparisons of get_jiffies_64()
6650		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6651			WARN("JIFFIES_COMPARISON",
6652			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6653		}
6654
6655# warn about #ifdefs in C files
6656#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6657#			print "#ifdef in C files should be avoided\n";
6658#			print "$herecurr";
6659#			$clean = 0;
6660#		}
6661
6662# warn about spacing in #ifdefs
6663		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6664			if (ERROR("SPACING",
6665				  "exactly one space required after that #$1\n" . $herecurr) &&
6666			    $fix) {
6667				$fixed[$fixlinenr] =~
6668				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6669			}
6670
6671		}
6672
6673# check for spinlock_t definitions without a comment.
6674		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6675		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6676			my $which = $1;
6677			if (!ctx_has_comment($first_line, $linenr)) {
6678				CHK("UNCOMMENTED_DEFINITION",
6679				    "$1 definition without comment\n" . $herecurr);
6680			}
6681		}
6682# check for memory barriers without a comment.
6683
6684		my $barriers = qr{
6685			mb|
6686			rmb|
6687			wmb
6688		}x;
6689		my $barrier_stems = qr{
6690			mb__before_atomic|
6691			mb__after_atomic|
6692			store_release|
6693			load_acquire|
6694			store_mb|
6695			(?:$barriers)
6696		}x;
6697		my $all_barriers = qr{
6698			(?:$barriers)|
6699			smp_(?:$barrier_stems)|
6700			virt_(?:$barrier_stems)
6701		}x;
6702
6703		if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6704			if (!ctx_has_comment($first_line, $linenr)) {
6705				WARN("MEMORY_BARRIER",
6706				     "memory barrier without comment\n" . $herecurr);
6707			}
6708		}
6709
6710		my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6711
6712		if ($realfile !~ m@^include/asm-generic/@ &&
6713		    $realfile !~ m@/barrier\.h$@ &&
6714		    $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6715		    $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6716			WARN("MEMORY_BARRIER",
6717			     "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6718		}
6719
6720# check for waitqueue_active without a comment.
6721		if ($line =~ /\bwaitqueue_active\s*\(/) {
6722			if (!ctx_has_comment($first_line, $linenr)) {
6723				WARN("WAITQUEUE_ACTIVE",
6724				     "waitqueue_active without comment\n" . $herecurr);
6725			}
6726		}
6727
6728# check for data_race without a comment.
6729		if ($line =~ /\bdata_race\s*\(/) {
6730			if (!ctx_has_comment($first_line, $linenr)) {
6731				WARN("DATA_RACE",
6732				     "data_race without comment\n" . $herecurr);
6733			}
6734		}
6735
6736# check of hardware specific defines
6737		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6738			CHK("ARCH_DEFINES",
6739			    "architecture specific defines should be avoided\n" .  $herecurr);
6740		}
6741
6742# check that the storage class is not after a type
6743		if ($line =~ /\b($Type)\s+($Storage)\b/) {
6744			WARN("STORAGE_CLASS",
6745			     "storage class '$2' should be located before type '$1'\n" . $herecurr);
6746		}
6747# Check that the storage class is at the beginning of a declaration
6748		if ($line =~ /\b$Storage\b/ &&
6749		    $line !~ /^.\s*$Storage/ &&
6750		    $line =~ /^.\s*(.+?)\$Storage\s/ &&
6751		    $1 !~ /[\,\)]\s*$/) {
6752			WARN("STORAGE_CLASS",
6753			     "storage class should be at the beginning of the declaration\n" . $herecurr);
6754		}
6755
6756# check the location of the inline attribute, that it is between
6757# storage class and type.
6758		if ($line =~ /\b$Type\s+$Inline\b/ ||
6759		    $line =~ /\b$Inline\s+$Storage\b/) {
6760			ERROR("INLINE_LOCATION",
6761			      "inline keyword should sit between storage class and type\n" . $herecurr);
6762		}
6763
6764# Check for __inline__ and __inline, prefer inline
6765		if ($realfile !~ m@\binclude/uapi/@ &&
6766		    $line =~ /\b(__inline__|__inline)\b/) {
6767			if (WARN("INLINE",
6768				 "plain inline is preferred over $1\n" . $herecurr) &&
6769			    $fix) {
6770				$fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6771
6772			}
6773		}
6774
6775# Check for compiler attributes
6776		if ($realfile !~ m@\binclude/uapi/@ &&
6777		    $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6778			my $attr = $1;
6779			$attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6780
6781			my %attr_list = (
6782				"alias"				=> "__alias",
6783				"aligned"			=> "__aligned",
6784				"always_inline"			=> "__always_inline",
6785				"assume_aligned"		=> "__assume_aligned",
6786				"cold"				=> "__cold",
6787				"const"				=> "__attribute_const__",
6788				"copy"				=> "__copy",
6789				"designated_init"		=> "__designated_init",
6790				"externally_visible"		=> "__visible",
6791				"format"			=> "printf|scanf",
6792				"gnu_inline"			=> "__gnu_inline",
6793				"malloc"			=> "__malloc",
6794				"mode"				=> "__mode",
6795				"no_caller_saved_registers"	=> "__no_caller_saved_registers",
6796				"noclone"			=> "__noclone",
6797				"noinline"			=> "noinline",
6798				"nonstring"			=> "__nonstring",
6799				"noreturn"			=> "__noreturn",
6800				"packed"			=> "__packed",
6801				"pure"				=> "__pure",
6802				"section"			=> "__section",
6803				"used"				=> "__used",
6804				"weak"				=> "__weak"
6805			);
6806
6807			while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6808				my $orig_attr = $1;
6809				my $params = '';
6810				$params = $2 if defined($2);
6811				my $curr_attr = $orig_attr;
6812				$curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6813				if (exists($attr_list{$curr_attr})) {
6814					my $new = $attr_list{$curr_attr};
6815					if ($curr_attr eq "format" && $params) {
6816						$params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6817						$new = "__$1\($2";
6818					} else {
6819						$new = "$new$params";
6820					}
6821					if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6822						 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6823					    $fix) {
6824						my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6825						$fixed[$fixlinenr] =~ s/$remove//;
6826						$fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6827						$fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6828						$fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6829					}
6830				}
6831			}
6832
6833			# Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6834			if ($attr =~ /^_*unused/) {
6835				WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6836				     "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6837			}
6838		}
6839
6840# Check for __attribute__ weak, or __weak declarations (may have link issues)
6841		if ($perl_version_ok &&
6842		    $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6843		    ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6844		     $line =~ /\b__weak\b/)) {
6845			ERROR("WEAK_DECLARATION",
6846			      "Using weak declarations can have unintended link defects\n" . $herecurr);
6847		}
6848
6849# check for c99 types like uint8_t used outside of uapi/ and tools/
6850		if ($realfile !~ m@\binclude/uapi/@ &&
6851		    $realfile !~ m@\btools/@ &&
6852		    $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6853			my $type = $1;
6854			if ($type =~ /\b($typeC99Typedefs)\b/) {
6855				$type = $1;
6856				my $kernel_type = 'u';
6857				$kernel_type = 's' if ($type =~ /^_*[si]/);
6858				$type =~ /(\d+)/;
6859				$kernel_type .= $1;
6860				if (CHK("PREFER_KERNEL_TYPES",
6861					"Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6862				    $fix) {
6863					$fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6864				}
6865			}
6866		}
6867
6868# check for cast of C90 native int or longer types constants
6869		if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6870			my $cast = $1;
6871			my $const = $2;
6872			my $suffix = "";
6873			my $newconst = $const;
6874			$newconst =~ s/${Int_type}$//;
6875			$suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6876			if ($cast =~ /\blong\s+long\b/) {
6877			    $suffix .= 'LL';
6878			} elsif ($cast =~ /\blong\b/) {
6879			    $suffix .= 'L';
6880			}
6881			if (WARN("TYPECAST_INT_CONSTANT",
6882				 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6883			    $fix) {
6884				$fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6885			}
6886		}
6887
6888# check for sizeof(&)
6889		if ($line =~ /\bsizeof\s*\(\s*\&/) {
6890			WARN("SIZEOF_ADDRESS",
6891			     "sizeof(& should be avoided\n" . $herecurr);
6892		}
6893
6894# check for sizeof without parenthesis
6895		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6896			if (WARN("SIZEOF_PARENTHESIS",
6897				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6898			    $fix) {
6899				$fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6900			}
6901		}
6902
6903# check for struct spinlock declarations
6904		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6905			WARN("USE_SPINLOCK_T",
6906			     "struct spinlock should be spinlock_t\n" . $herecurr);
6907		}
6908
6909# check for seq_printf uses that could be seq_puts
6910		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6911			my $fmt = get_quoted_string($line, $rawline);
6912			$fmt =~ s/%%//g;
6913			if ($fmt !~ /%/) {
6914				if (WARN("PREFER_SEQ_PUTS",
6915					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6916				    $fix) {
6917					$fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6918				}
6919			}
6920		}
6921
6922# check for vsprintf extension %p<foo> misuses
6923		if ($perl_version_ok &&
6924		    defined $stat &&
6925		    $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6926		    $1 !~ /^_*volatile_*$/) {
6927			my $stat_real;
6928
6929			my $lc = $stat =~ tr@\n@@;
6930			$lc = $lc + $linenr;
6931		        for (my $count = $linenr; $count <= $lc; $count++) {
6932				my $specifier;
6933				my $extension;
6934				my $qualifier;
6935				my $bad_specifier = "";
6936				my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6937				$fmt =~ s/%%//g;
6938
6939				while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6940					$specifier = $1;
6941					$extension = $2;
6942					$qualifier = $3;
6943					if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6944					    ($extension eq "f" &&
6945					     defined $qualifier && $qualifier !~ /^w/) ||
6946					    ($extension eq "4" &&
6947					     defined $qualifier && $qualifier !~ /^c(?:[hlbc]|hR)$/)) {
6948						$bad_specifier = $specifier;
6949						last;
6950					}
6951					if ($extension eq "x" && !defined($stat_real)) {
6952						if (!defined($stat_real)) {
6953							$stat_real = get_stat_real($linenr, $lc);
6954						}
6955						WARN("VSPRINTF_SPECIFIER_PX",
6956						     "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n");
6957					}
6958				}
6959				if ($bad_specifier ne "") {
6960					my $stat_real = get_stat_real($linenr, $lc);
6961					my $msg_level = \&WARN;
6962					my $ext_type = "Invalid";
6963					my $use = "";
6964					if ($bad_specifier =~ /p[Ff]/) {
6965						$use = " - use %pS instead";
6966						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6967					} elsif ($bad_specifier =~ /pA/) {
6968						$use =  " - '%pA' is only intended to be used from Rust code";
6969						$msg_level = \&ERROR;
6970					}
6971
6972					&{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6973						      "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6974				}
6975			}
6976		}
6977
6978# Check for misused memsets
6979		if ($perl_version_ok &&
6980		    defined $stat &&
6981		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6982
6983			my $ms_addr = $2;
6984			my $ms_val = $7;
6985			my $ms_size = $12;
6986
6987			if ($ms_size =~ /^(0x|)0$/i) {
6988				ERROR("MEMSET",
6989				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6990			} elsif ($ms_size =~ /^(0x|)1$/i) {
6991				WARN("MEMSET",
6992				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6993			}
6994		}
6995
6996# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6997#		if ($perl_version_ok &&
6998#		    defined $stat &&
6999#		    $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7000#			if (WARN("PREFER_ETHER_ADDR_COPY",
7001#				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
7002#			    $fix) {
7003#				$fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
7004#			}
7005#		}
7006
7007# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
7008#		if ($perl_version_ok &&
7009#		    defined $stat &&
7010#		    $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7011#			WARN("PREFER_ETHER_ADDR_EQUAL",
7012#			     "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
7013#		}
7014
7015# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
7016# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
7017#		if ($perl_version_ok &&
7018#		    defined $stat &&
7019#		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7020#
7021#			my $ms_val = $7;
7022#
7023#			if ($ms_val =~ /^(?:0x|)0+$/i) {
7024#				if (WARN("PREFER_ETH_ZERO_ADDR",
7025#					 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
7026#				    $fix) {
7027#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
7028#				}
7029#			} elsif ($ms_val =~ /^(?:0xff|255)$/i) {
7030#				if (WARN("PREFER_ETH_BROADCAST_ADDR",
7031#					 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
7032#				    $fix) {
7033#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
7034#				}
7035#			}
7036#		}
7037# strcpy uses that should likely be strscpy
7038		if ($line =~ /\bstrcpy\s*\(/ && !is_userspace($realfile)) {
7039			WARN("STRCPY",
7040			     "Prefer strscpy over strcpy - see: https://github.com/KSPP/linux/issues/88\n" . $herecurr);
7041		}
7042
7043# strlcpy uses that should likely be strscpy
7044		if ($line =~ /\bstrlcpy\s*\(/ && !is_userspace($realfile)) {
7045			WARN("STRLCPY",
7046			     "Prefer strscpy over strlcpy - see: https://github.com/KSPP/linux/issues/89\n" . $herecurr);
7047		}
7048
7049# strncpy uses that should likely be strscpy or strscpy_pad
7050		if ($line =~ /\bstrncpy\s*\(/ && !is_userspace($realfile)) {
7051			WARN("STRNCPY",
7052			     "Prefer strscpy, strscpy_pad, or __nonstring over strncpy - see: https://github.com/KSPP/linux/issues/90\n" . $herecurr);
7053		}
7054
7055# ethtool_sprintf uses that should likely be ethtool_puts
7056		if ($line =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7057			if (WARN("PREFER_ETHTOOL_PUTS",
7058				 "Prefer ethtool_puts over ethtool_sprintf with only two arguments\n" . $herecurr) &&
7059			    $fix) {
7060				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7061			}
7062		}
7063
7064		# use $rawline because $line loses %s via sanitization and thus we can't match against it.
7065		if ($rawline =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*\"\%s\"\s*,\s*$FuncArg\s*\)/) {
7066			if (WARN("PREFER_ETHTOOL_PUTS",
7067				 "Prefer ethtool_puts over ethtool_sprintf with standalone \"%s\" specifier\n" . $herecurr) &&
7068			    $fix) {
7069				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*"\%s"\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7070			}
7071		}
7072
7073
7074# typecasts on min/max could be min_t/max_t
7075		if ($perl_version_ok &&
7076		    defined $stat &&
7077		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7078			if (defined $2 || defined $7) {
7079				my $call = $1;
7080				my $cast1 = deparenthesize($2);
7081				my $arg1 = $3;
7082				my $cast2 = deparenthesize($7);
7083				my $arg2 = $8;
7084				my $cast;
7085
7086				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7087					$cast = "$cast1 or $cast2";
7088				} elsif ($cast1 ne "") {
7089					$cast = $cast1;
7090				} else {
7091					$cast = $cast2;
7092				}
7093				WARN("MINMAX",
7094				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7095			}
7096		}
7097
7098# check usleep_range arguments
7099		if ($perl_version_ok &&
7100		    defined $stat &&
7101		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7102			my $min = $1;
7103			my $max = $7;
7104			if ($min eq $max) {
7105				WARN("USLEEP_RANGE",
7106				     "usleep_range should not use min == max args;  see function description of usleep_range().\n" . "$here\n$stat\n");
7107			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7108				 $min > $max) {
7109				WARN("USLEEP_RANGE",
7110				     "usleep_range args reversed, use min then max;  see function description of usleep_range().\n" . "$here\n$stat\n");
7111			}
7112		}
7113
7114# check for naked sscanf
7115		if ($perl_version_ok &&
7116		    defined $stat &&
7117		    $line =~ /\bsscanf\b/ &&
7118		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7119		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7120		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7121			my $lc = $stat =~ tr@\n@@;
7122			$lc = $lc + $linenr;
7123			my $stat_real = get_stat_real($linenr, $lc);
7124			WARN("NAKED_SSCANF",
7125			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7126		}
7127
7128# check for simple sscanf that should be kstrto<foo>
7129		if ($perl_version_ok &&
7130		    defined $stat &&
7131		    $line =~ /\bsscanf\b/) {
7132			my $lc = $stat =~ tr@\n@@;
7133			$lc = $lc + $linenr;
7134			my $stat_real = get_stat_real($linenr, $lc);
7135			if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7136				my $format = $6;
7137				my $count = $format =~ tr@%@%@;
7138				if ($count == 1 &&
7139				    $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7140					WARN("SSCANF_TO_KSTRTO",
7141					     "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7142				}
7143			}
7144		}
7145
7146# check for new externs in .h files.
7147		if ($realfile =~ /\.h$/ &&
7148		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7149			if (CHK("AVOID_EXTERNS",
7150				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
7151			    $fix) {
7152				$fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7153			}
7154		}
7155
7156# check for new externs in .c files.
7157		if ($realfile =~ /\.c$/ && defined $stat &&
7158		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7159		{
7160			my $function_name = $1;
7161			my $paren_space = $2;
7162
7163			my $s = $stat;
7164			if (defined $cond) {
7165				substr($s, 0, length($cond), '');
7166			}
7167			if ($s =~ /^\s*;/)
7168			{
7169				WARN("AVOID_EXTERNS",
7170				     "externs should be avoided in .c files\n" .  $herecurr);
7171			}
7172
7173			if ($paren_space =~ /\n/) {
7174				WARN("FUNCTION_ARGUMENTS",
7175				     "arguments for function declarations should follow identifier\n" . $herecurr);
7176			}
7177
7178		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7179		    $stat =~ /^\+extern struct\s+(\w+)\s+(\w+)\[\];/)
7180		{
7181			my ($st_type, $st_name) = ($1, $2);
7182
7183			for my $s (keys %maybe_linker_symbol) {
7184			    #print "Linker symbol? $st_name : $s\n";
7185			    goto LIKELY_LINKER_SYMBOL
7186				if $st_name =~ /$s/;
7187			}
7188			WARN("AVOID_EXTERNS",
7189			     "found a file-scoped extern type:$st_type name:$st_name in .c file\n"
7190			     . "is this a linker symbol ?\n" . $herecurr);
7191		  LIKELY_LINKER_SYMBOL:
7192
7193		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7194		    $stat =~ /^.\s*extern\s+/)
7195		{
7196			WARN("AVOID_EXTERNS",
7197			     "externs should be avoided in .c files\n" .  $herecurr);
7198		}
7199
7200# check for function declarations that have arguments without identifier names
7201		if (defined $stat &&
7202		    $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7203		    $1 ne "void") {
7204			my $args = trim($1);
7205			while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7206				my $arg = trim($1);
7207				if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7208					WARN("FUNCTION_ARGUMENTS",
7209					     "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7210				}
7211			}
7212		}
7213
7214# check for function definitions
7215		if ($perl_version_ok &&
7216		    defined $stat &&
7217		    $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7218			$context_function = $1;
7219
7220# check for multiline function definition with misplaced open brace
7221			my $ok = 0;
7222			my $cnt = statement_rawlines($stat);
7223			my $herectx = $here . "\n";
7224			for (my $n = 0; $n < $cnt; $n++) {
7225				my $rl = raw_line($linenr, $n);
7226				$herectx .=  $rl . "\n";
7227				$ok = 1 if ($rl =~ /^[ \+]\{/);
7228				$ok = 1 if ($rl =~ /\{/ && $n == 0);
7229				last if $rl =~ /^[ \+].*\{/;
7230			}
7231			if (!$ok) {
7232				ERROR("OPEN_BRACE",
7233				      "open brace '{' following function definitions go on the next line\n" . $herectx);
7234			}
7235		}
7236
7237# checks for new __setup's
7238		if ($rawline =~ /\b__setup\("([^"]*)"/) {
7239			my $name = $1;
7240
7241			if (!grep(/$name/, @setup_docs)) {
7242				CHK("UNDOCUMENTED_SETUP",
7243				    "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7244			}
7245		}
7246
7247# check for pointless casting of alloc functions
7248		if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7249			WARN("UNNECESSARY_CASTS",
7250			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7251		}
7252
7253# alloc style
7254# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7255		if ($perl_version_ok &&
7256		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7257			CHK("ALLOC_SIZEOF_STRUCT",
7258			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7259		}
7260
7261# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7262		if ($perl_version_ok &&
7263		    defined $stat &&
7264		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7265			my $oldfunc = $3;
7266			my $a1 = $4;
7267			my $a2 = $10;
7268			my $newfunc = "kmalloc_array";
7269			$newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7270			$newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7271			$newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7272			my $r1 = $a1;
7273			my $r2 = $a2;
7274			if ($a1 =~ /^sizeof\s*\S/) {
7275				$r1 = $a2;
7276				$r2 = $a1;
7277			}
7278			if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7279			    !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7280				my $cnt = statement_rawlines($stat);
7281				my $herectx = get_stat_here($linenr, $cnt, $here);
7282
7283				if (WARN("ALLOC_WITH_MULTIPLY",
7284					 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7285				    $cnt == 1 &&
7286				    $fix) {
7287					$fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
7288				}
7289			}
7290		}
7291
7292# check for krealloc arg reuse
7293		if ($perl_version_ok &&
7294		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7295		    $1 eq $3) {
7296			WARN("KREALLOC_ARG_REUSE",
7297			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7298		}
7299
7300# check for alloc argument mismatch
7301		if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
7302			WARN("ALLOC_ARRAY_ARGS",
7303			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7304		}
7305
7306# check for multiple semicolons
7307		if ($line =~ /;\s*;\s*$/) {
7308			if (WARN("ONE_SEMICOLON",
7309				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7310			    $fix) {
7311				$fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7312			}
7313		}
7314
7315# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7316		if ($realfile !~ m@^include/uapi/@ &&
7317		    $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7318			my $ull = "";
7319			$ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7320			if (CHK("BIT_MACRO",
7321				"Prefer using the BIT$ull macro\n" . $herecurr) &&
7322			    $fix) {
7323				$fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7324			}
7325		}
7326
7327# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7328		if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7329			WARN("IS_ENABLED_CONFIG",
7330			     "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7331		}
7332
7333# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7334		if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7335			my $config = $1;
7336			if (WARN("PREFER_IS_ENABLED",
7337				 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7338			    $fix) {
7339				$fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7340			}
7341		}
7342
7343# check for /* fallthrough */ like comment, prefer fallthrough;
7344		my @fallthroughs = (
7345			'fallthrough',
7346			'@fallthrough@',
7347			'lint -fallthrough[ \t]*',
7348			'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7349			'(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7350			'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7351			'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7352		    );
7353		if ($raw_comment ne '') {
7354			foreach my $ft (@fallthroughs) {
7355				if ($raw_comment =~ /$ft/) {
7356					my $msg_level = \&WARN;
7357					$msg_level = \&CHK if ($file);
7358					&{$msg_level}("PREFER_FALLTHROUGH",
7359						      "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7360					last;
7361				}
7362			}
7363		}
7364
7365# check for switch/default statements without a break;
7366		if ($perl_version_ok &&
7367		    defined $stat &&
7368		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7369			my $cnt = statement_rawlines($stat);
7370			my $herectx = get_stat_here($linenr, $cnt, $here);
7371
7372			WARN("DEFAULT_NO_BREAK",
7373			     "switch default: should use break\n" . $herectx);
7374		}
7375
7376# check for gcc specific __FUNCTION__
7377		if ($line =~ /\b__FUNCTION__\b/) {
7378			if (WARN("USE_FUNC",
7379				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
7380			    $fix) {
7381				$fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7382			}
7383		}
7384
7385# check for uses of __DATE__, __TIME__, __TIMESTAMP__
7386		while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7387			ERROR("DATE_TIME",
7388			      "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7389		}
7390
7391# check for use of yield()
7392		if ($line =~ /\byield\s*\(\s*\)/) {
7393			WARN("YIELD",
7394			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
7395		}
7396
7397# check for comparisons against true and false
7398		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7399			my $lead = $1;
7400			my $arg = $2;
7401			my $test = $3;
7402			my $otype = $4;
7403			my $trail = $5;
7404			my $op = "!";
7405
7406			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7407
7408			my $type = lc($otype);
7409			if ($type =~ /^(?:true|false)$/) {
7410				if (("$test" eq "==" && "$type" eq "true") ||
7411				    ("$test" eq "!=" && "$type" eq "false")) {
7412					$op = "";
7413				}
7414
7415				CHK("BOOL_COMPARISON",
7416				    "Using comparison to $otype is error prone\n" . $herecurr);
7417
7418## maybe suggesting a correct construct would better
7419##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7420
7421			}
7422		}
7423
7424# check for semaphores initialized locked
7425		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7426			WARN("CONSIDER_COMPLETION",
7427			     "consider using a completion\n" . $herecurr);
7428		}
7429
7430# recommend kstrto* over simple_strto* and strict_strto*
7431		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7432			WARN("CONSIDER_KSTRTO",
7433			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
7434		}
7435
7436# check for __initcall(), use device_initcall() explicitly or more appropriate function please
7437		if ($line =~ /^.\s*__initcall\s*\(/) {
7438			WARN("USE_DEVICE_INITCALL",
7439			     "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7440		}
7441
7442# check for spin_is_locked(), suggest lockdep instead
7443		if ($line =~ /\bspin_is_locked\(/) {
7444			WARN("USE_LOCKDEP",
7445			     "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7446		}
7447
7448# check for deprecated apis
7449		if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7450			my $deprecated_api = $1;
7451			my $new_api = $deprecated_apis{$deprecated_api};
7452			WARN("DEPRECATED_API",
7453			     "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7454		}
7455
7456# check for various structs that are normally const (ops, kgdb, device_tree)
7457# and avoid what seem like struct definitions 'struct foo {'
7458		if (defined($const_structs) &&
7459		    $line !~ /\bconst\b/ &&
7460		    $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7461			WARN("CONST_STRUCT",
7462			     "struct $1 should normally be const\n" . $herecurr);
7463		}
7464
7465# use of NR_CPUS is usually wrong
7466# ignore definitions of NR_CPUS and usage to define arrays as likely right
7467# ignore designated initializers using NR_CPUS
7468		if ($line =~ /\bNR_CPUS\b/ &&
7469		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7470		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7471		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7472		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7473		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7474		    $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7475		{
7476			WARN("NR_CPUS",
7477			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7478		}
7479
7480# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7481		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7482			ERROR("DEFINE_ARCH_HAS",
7483			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7484		}
7485
7486# likely/unlikely comparisons similar to "(likely(foo) > 0)"
7487		if ($perl_version_ok &&
7488		    $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7489			WARN("LIKELY_MISUSE",
7490			     "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7491		}
7492
7493# return sysfs_emit(foo, fmt, ...) fmt without newline
7494		if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7495		    substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7496			my $offset = $+[6] - 1;
7497			if (WARN("SYSFS_EMIT",
7498				 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7499			    $fix) {
7500				substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7501			}
7502		}
7503
7504# check for array definition/declarations that should use flexible arrays instead
7505		if ($sline =~ /^[\+ ]\s*\}(?:\s*__packed)?\s*;\s*$/ &&
7506		    $prevline =~ /^\+\s*(?:\}(?:\s*__packed\s*)?|$Type)\s*$Ident\s*\[\s*(0|1)\s*\]\s*;\s*$/) {
7507			if (ERROR("FLEXIBLE_ARRAY",
7508				  "Use C99 flexible arrays - see https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays\n" . $hereprev) &&
7509			    $1 == '0' && $fix) {
7510				$fixed[$fixlinenr - 1] =~ s/\[\s*0\s*\]/[]/;
7511			}
7512		}
7513
7514# nested likely/unlikely calls
7515		if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7516			WARN("LIKELY_MISUSE",
7517			     "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7518		}
7519
7520# whine mightly about in_atomic
7521		if ($line =~ /\bin_atomic\s*\(/) {
7522			if ($realfile =~ m@^drivers/@) {
7523				ERROR("IN_ATOMIC",
7524				      "do not use in_atomic in drivers\n" . $herecurr);
7525			} elsif ($realfile !~ m@^kernel/@) {
7526				WARN("IN_ATOMIC",
7527				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7528			}
7529		}
7530
7531# Complain about RCU Tasks Trace used outside of BPF (and of course, RCU).
7532		our $rcu_trace_funcs = qr{(?x:
7533			rcu_read_lock_trace |
7534			rcu_read_lock_trace_held |
7535			rcu_read_unlock_trace |
7536			call_rcu_tasks_trace |
7537			synchronize_rcu_tasks_trace |
7538			rcu_barrier_tasks_trace |
7539			rcu_request_urgent_qs_task
7540		)};
7541		our $rcu_trace_paths = qr{(?x:
7542			kernel/bpf/ |
7543			include/linux/bpf |
7544			net/bpf/ |
7545			kernel/rcu/ |
7546			include/linux/rcu
7547		)};
7548		if ($line =~ /\b($rcu_trace_funcs)\s*\(/) {
7549			if ($realfile !~ m{^$rcu_trace_paths}) {
7550				WARN("RCU_TASKS_TRACE",
7551				     "use of RCU tasks trace is incorrect outside BPF or core RCU code\n" . $herecurr);
7552			}
7553		}
7554
7555# check for lockdep_set_novalidate_class
7556		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7557		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
7558			if ($realfile !~ m@^kernel/lockdep@ &&
7559			    $realfile !~ m@^include/linux/lockdep@ &&
7560			    $realfile !~ m@^drivers/base/core@) {
7561				ERROR("LOCKDEP",
7562				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7563			}
7564		}
7565
7566		if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7567		    $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7568			WARN("EXPORTED_WORLD_WRITABLE",
7569			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7570		}
7571
7572# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7573# and whether or not function naming is typical and if
7574# DEVICE_ATTR permissions uses are unusual too
7575		if ($perl_version_ok &&
7576		    defined $stat &&
7577		    $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) {
7578			my $var = $1;
7579			my $perms = $2;
7580			my $show = $3;
7581			my $store = $4;
7582			my $octal_perms = perms_to_octal($perms);
7583			if ($show =~ /^${var}_show$/ &&
7584			    $store =~ /^${var}_store$/ &&
7585			    $octal_perms eq "0644") {
7586				if (WARN("DEVICE_ATTR_RW",
7587					 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7588				    $fix) {
7589					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7590				}
7591			} elsif ($show =~ /^${var}_show$/ &&
7592				 $store =~ /^NULL$/ &&
7593				 $octal_perms eq "0444") {
7594				if (WARN("DEVICE_ATTR_RO",
7595					 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7596				    $fix) {
7597					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7598				}
7599			} elsif ($show =~ /^NULL$/ &&
7600				 $store =~ /^${var}_store$/ &&
7601				 $octal_perms eq "0200") {
7602				if (WARN("DEVICE_ATTR_WO",
7603					 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7604				    $fix) {
7605					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7606				}
7607			} elsif ($octal_perms eq "0644" ||
7608				 $octal_perms eq "0444" ||
7609				 $octal_perms eq "0200") {
7610				my $newshow = "$show";
7611				$newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7612				my $newstore = $store;
7613				$newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7614				my $rename = "";
7615				if ($show ne $newshow) {
7616					$rename .= " '$show' to '$newshow'";
7617				}
7618				if ($store ne $newstore) {
7619					$rename .= " '$store' to '$newstore'";
7620				}
7621				WARN("DEVICE_ATTR_FUNCTIONS",
7622				     "Consider renaming function(s)$rename\n" . $herecurr);
7623			} else {
7624				WARN("DEVICE_ATTR_PERMS",
7625				     "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7626			}
7627		}
7628
7629# Mode permission misuses where it seems decimal should be octal
7630# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7631# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7632#   specific definition of not visible in sysfs.
7633# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7634#   use the default permissions
7635		if ($perl_version_ok &&
7636		    defined $stat &&
7637		    $line =~ /$mode_perms_search/) {
7638			foreach my $entry (@mode_permission_funcs) {
7639				my $func = $entry->[0];
7640				my $arg_pos = $entry->[1];
7641
7642				my $lc = $stat =~ tr@\n@@;
7643				$lc = $lc + $linenr;
7644				my $stat_real = get_stat_real($linenr, $lc);
7645
7646				my $skip_args = "";
7647				if ($arg_pos > 1) {
7648					$arg_pos--;
7649					$skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7650				}
7651				my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7652				if ($stat =~ /$test/) {
7653					my $val = $1;
7654					$val = $6 if ($skip_args ne "");
7655					if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7656					    (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7657					     ($val =~ /^$Octal$/ && length($val) ne 4))) {
7658						ERROR("NON_OCTAL_PERMISSIONS",
7659						      "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7660					}
7661					if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7662						ERROR("EXPORTED_WORLD_WRITABLE",
7663						      "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7664					}
7665				}
7666			}
7667		}
7668
7669# check for uses of S_<PERMS> that could be octal for readability
7670		while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7671			my $oval = $1;
7672			my $octal = perms_to_octal($oval);
7673			if (WARN("SYMBOLIC_PERMS",
7674				 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7675			    $fix) {
7676				$fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7677			}
7678		}
7679
7680# validate content of MODULE_LICENSE against list from include/linux/module.h
7681		if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7682			my $extracted_string = get_quoted_string($line, $rawline);
7683			my $valid_licenses = qr{
7684						GPL|
7685						GPL\ v2|
7686						GPL\ and\ additional\ rights|
7687						Dual\ BSD/GPL|
7688						Dual\ MIT/GPL|
7689						Dual\ MPL/GPL|
7690						Proprietary
7691					}x;
7692			if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7693				WARN("MODULE_LICENSE",
7694				     "unknown module license " . $extracted_string . "\n" . $herecurr);
7695			}
7696			if (!$file && $extracted_string eq '"GPL v2"') {
7697				if (WARN("MODULE_LICENSE",
7698				     "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7699				    $fix) {
7700					$fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7701				}
7702			}
7703		}
7704
7705# check for sysctl duplicate constants
7706		if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7707			WARN("DUPLICATED_SYSCTL_CONST",
7708				"duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7709		}
7710
7711# Check that *_device_id tables have sentinel entries.
7712		if (defined $stat && $line =~ /struct\s+$dev_id_types\s+\w+\s*\[\s*\]\s*=\s*\{/) {
7713			my $stripped = $stat;
7714
7715			# Strip diff line prefixes.
7716			$stripped =~ s/(^|\n)./$1/g;
7717			# Line continuations.
7718			$stripped =~ s/\\\n/\n/g;
7719			# Strip whitespace, empty strings, zeroes, and commas.
7720			$stripped =~ s/""//g;
7721			$stripped =~ s/0x0//g;
7722			$stripped =~ s/[\s$;,0]//g;
7723			# Strip field assignments.
7724			$stripped =~ s/\.$Ident=//g;
7725
7726			if (!(substr($stripped, -4) eq "{}};" ||
7727			      substr($stripped, -6) eq "{{}}};" ||
7728			      $stripped =~ /ISAPNP_DEVICE_SINGLE_END}};$/ ||
7729			      $stripped =~ /ISAPNP_CARD_END}};$/ ||
7730			      $stripped =~ /NULL};$/ ||
7731			      $stripped =~ /PCMCIA_DEVICE_NULL};$/)) {
7732				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
7733			}
7734		}
7735	}
7736
7737	# If we have no input at all, then there is nothing to report on
7738	# so just keep quiet.
7739	if ($#rawlines == -1) {
7740		exit(0);
7741	}
7742
7743	# In mailback mode only produce a report in the negative, for
7744	# things that appear to be patches.
7745	if ($mailback && ($clean == 1 || !$is_patch)) {
7746		exit(0);
7747	}
7748
7749	# This is not a patch, and we are in 'no-patch' mode so
7750	# just keep quiet.
7751	if (!$chk_patch && !$is_patch) {
7752		exit(0);
7753	}
7754
7755	if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7756		ERROR("NOT_UNIFIED_DIFF",
7757		      "Does not appear to be a unified-diff format patch\n");
7758	}
7759	if ($is_patch && $has_commit_log && $chk_fixes_tag) {
7760		if ($needs_fixes_tag ne "" && !$is_revert && !$fixes_tag) {
7761			WARN("MISSING_FIXES_TAG",
7762				 "The commit message has '$needs_fixes_tag', perhaps it also needs a 'Fixes:' tag?\n");
7763		}
7764	}
7765	if ($is_patch && $has_commit_log && $chk_signoff) {
7766		if ($signoff == 0) {
7767			ERROR("MISSING_SIGN_OFF",
7768			      "Missing Signed-off-by: line(s)\n");
7769		} elsif ($authorsignoff != 1) {
7770			# authorsignoff values:
7771			# 0 -> missing sign off
7772			# 1 -> sign off identical
7773			# 2 -> names and addresses match, comments mismatch
7774			# 3 -> addresses match, names different
7775			# 4 -> names match, addresses different
7776			# 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7777
7778			my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7779
7780			if ($authorsignoff == 0) {
7781				ERROR("NO_AUTHOR_SIGN_OFF",
7782				      "Missing Signed-off-by: line by nominal patch author '$author'\n");
7783			} elsif ($authorsignoff == 2) {
7784				CHK("FROM_SIGN_OFF_MISMATCH",
7785				    "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7786			} elsif ($authorsignoff == 3) {
7787				WARN("FROM_SIGN_OFF_MISMATCH",
7788				     "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7789			} elsif ($authorsignoff == 4) {
7790				WARN("FROM_SIGN_OFF_MISMATCH",
7791				     "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7792			} elsif ($authorsignoff == 5) {
7793				WARN("FROM_SIGN_OFF_MISMATCH",
7794				     "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7795			}
7796		}
7797	}
7798
7799	print report_dump();
7800	if ($summary && !($clean == 1 && $quiet == 1)) {
7801		print "$filename " if ($summary_file);
7802		print "total: $cnt_error errors, $cnt_warn warnings, " .
7803			(($check)? "$cnt_chk checks, " : "") .
7804			"$cnt_lines lines checked\n";
7805	}
7806
7807	if ($quiet == 0) {
7808		# If there were any defects found and not already fixing them
7809		if (!$clean and !$fix) {
7810			print << "EOM"
7811
7812NOTE: For some of the reported defects, checkpatch may be able to
7813      mechanically convert to the typical style using --fix or --fix-inplace.
7814EOM
7815		}
7816		# If there were whitespace errors which cleanpatch can fix
7817		# then suggest that.
7818		if ($rpt_cleaners) {
7819			$rpt_cleaners = 0;
7820			print << "EOM"
7821
7822NOTE: Whitespace errors detected.
7823      You may wish to use scripts/cleanpatch or scripts/cleanfile
7824EOM
7825		}
7826	}
7827
7828	if ($clean == 0 && $fix &&
7829	    ("@rawlines" ne "@fixed" ||
7830	     $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7831		my $newfile = $filename;
7832		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7833		my $linecount = 0;
7834		my $f;
7835
7836		@fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7837
7838		open($f, '>', $newfile)
7839		    or die "$P: Can't open $newfile for write\n";
7840		foreach my $fixed_line (@fixed) {
7841			$linecount++;
7842			if ($file) {
7843				if ($linecount > 3) {
7844					$fixed_line =~ s/^\+//;
7845					print $f $fixed_line . "\n";
7846				}
7847			} else {
7848				print $f $fixed_line . "\n";
7849			}
7850		}
7851		close($f);
7852
7853		if (!$quiet) {
7854			print << "EOM";
7855
7856Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7857
7858Do _NOT_ trust the results written to this file.
7859Do _NOT_ submit these changes without inspecting them for correctness.
7860
7861This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7862No warranties, expressed or implied...
7863EOM
7864		}
7865	}
7866
7867	if ($quiet == 0) {
7868		print "\n";
7869		if ($clean == 1) {
7870			print "$vname has no obvious style problems and is ready for submission.\n";
7871		} else {
7872			print "$vname has style problems, please review.\n";
7873		}
7874	}
7875	return $clean;
7876}
7877