xref: /linux/scripts/checkpatch.pl (revision 66bd8501ceb4782b10dfa009085d9b3f4efecad6)
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 invalid patch separator
3035		if ($in_commit_log &&
3036		    $line =~ /^---.+/) {
3037			if (ERROR("BAD_COMMIT_SEPARATOR",
3038				  "Invalid commit separator - some tools may have problems applying this\n" . $herecurr) &&
3039			    $fix) {
3040				$fixed[$fixlinenr] =~ s/-/=/g;
3041			}
3042		}
3043
3044# Check for patch separator
3045		if ($line =~ /^---$/) {
3046			$has_patch_separator = 1;
3047			$in_commit_log = 0;
3048		}
3049
3050# Check if MAINTAINERS is being updated.  If so, there's probably no need to
3051# emit the "does MAINTAINERS need updating?" message on file add/move/delete
3052		if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3053			$reported_maintainer_file = 1;
3054		}
3055
3056# Check signature styles
3057		if (!$in_header_lines &&
3058		    $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3059			my $space_before = $1;
3060			my $sign_off = $2;
3061			my $space_after = $3;
3062			my $email = $4;
3063			my $ucfirst_sign_off = ucfirst(lc($sign_off));
3064
3065			if ($sign_off !~ /$signature_tags/) {
3066				my $suggested_signature = find_standard_signature($sign_off);
3067				if ($suggested_signature eq "") {
3068					WARN("BAD_SIGN_OFF",
3069					     "Non-standard signature: $sign_off\n" . $herecurr);
3070				} else {
3071					if (WARN("BAD_SIGN_OFF",
3072						 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3073					    $fix) {
3074						$fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3075					}
3076				}
3077			}
3078			if (defined $space_before && $space_before ne "") {
3079				if (WARN("BAD_SIGN_OFF",
3080					 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3081				    $fix) {
3082					$fixed[$fixlinenr] =
3083					    "$ucfirst_sign_off $email";
3084				}
3085			}
3086			if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3087				if (WARN("BAD_SIGN_OFF",
3088					 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3089				    $fix) {
3090					$fixed[$fixlinenr] =
3091					    "$ucfirst_sign_off $email";
3092				}
3093
3094			}
3095			if (!defined $space_after || $space_after ne " ") {
3096				if (WARN("BAD_SIGN_OFF",
3097					 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3098				    $fix) {
3099					$fixed[$fixlinenr] =
3100					    "$ucfirst_sign_off $email";
3101				}
3102			}
3103
3104			my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3105			my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3106			if ($suggested_email eq "") {
3107				ERROR("BAD_SIGN_OFF",
3108				      "Unrecognized email address: '$email'\n" . $herecurr);
3109			} else {
3110				my $dequoted = $suggested_email;
3111				$dequoted =~ s/^"//;
3112				$dequoted =~ s/" </ </;
3113				# Don't force email to have quotes
3114				# Allow just an angle bracketed address
3115				if (!same_email_addresses($email, $suggested_email)) {
3116					if (WARN("BAD_SIGN_OFF",
3117						 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3118					    $fix) {
3119						$fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3120					}
3121				}
3122
3123				# Address part shouldn't have comments
3124				my $stripped_address = $email_address;
3125				$stripped_address =~ s/\([^\(\)]*\)//g;
3126				if ($email_address ne $stripped_address) {
3127					if (WARN("BAD_SIGN_OFF",
3128						 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3129					    $fix) {
3130						$fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3131					}
3132				}
3133
3134				# Only one name comment should be allowed
3135				my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3136				if ($comment_count > 1) {
3137					WARN("BAD_SIGN_OFF",
3138					     "Use a single name comment in email: '$email'\n" . $herecurr);
3139				}
3140
3141
3142				# stable@vger.kernel.org or stable@kernel.org shouldn't
3143				# have an email name. In addition comments should strictly
3144				# begin with a #
3145				if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3146					if (($comment ne "" && $comment !~ /^#.+/) ||
3147					    ($email_name ne "")) {
3148						my $cur_name = $email_name;
3149						my $new_comment = $comment;
3150						$cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3151
3152						# Remove brackets enclosing comment text
3153						# and # from start of comments to get comment text
3154						$new_comment =~ s/^\((.*)\)$/$1/;
3155						$new_comment =~ s/^\[(.*)\]$/$1/;
3156						$new_comment =~ s/^[\s\#]+|\s+$//g;
3157
3158						$new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3159						$new_comment = " # $new_comment" if ($new_comment ne "");
3160						my $new_email = "$email_address$new_comment";
3161
3162						if (WARN("BAD_STABLE_ADDRESS_STYLE",
3163							 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3164						    $fix) {
3165							$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3166						}
3167					}
3168				} elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3169					my $new_comment = $comment;
3170
3171					# Extract comment text from within brackets or
3172					# c89 style /*...*/ comments
3173					$new_comment =~ s/^\[(.*)\]$/$1/;
3174					$new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3175
3176					$new_comment = trim($new_comment);
3177					$new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3178					$new_comment = "($new_comment)" if ($new_comment ne "");
3179					my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3180
3181					if (WARN("BAD_SIGN_OFF",
3182						 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3183					    $fix) {
3184						$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3185					}
3186				}
3187			}
3188
3189# Check for duplicate signatures
3190			my $sig_nospace = $line;
3191			$sig_nospace =~ s/\s//g;
3192			$sig_nospace = lc($sig_nospace);
3193			if (defined $signatures{$sig_nospace}) {
3194				WARN("BAD_SIGN_OFF",
3195				     "Duplicate signature\n" . $herecurr);
3196			} else {
3197				$signatures{$sig_nospace} = 1;
3198			}
3199
3200# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3201			if ($sign_off =~ /^co-developed-by:$/i) {
3202				if ($email eq $author) {
3203					WARN("BAD_SIGN_OFF",
3204					      "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
3205				}
3206				if (!defined $lines[$linenr]) {
3207					WARN("BAD_SIGN_OFF",
3208					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3209				} elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
3210					WARN("BAD_SIGN_OFF",
3211					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
3212				} elsif ($1 ne $email) {
3213					WARN("BAD_SIGN_OFF",
3214					     "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
3215				}
3216			}
3217
3218# check if Reported-by: is followed by a Closes: tag
3219			if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3220				if (!defined $lines[$linenr]) {
3221					WARN("BAD_REPORTED_BY_LINK",
3222					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
3223				} elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
3224					WARN("BAD_REPORTED_BY_LINK",
3225					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
3226				}
3227			}
3228		}
3229
3230# These indicate a bug fix
3231		if (!$in_header_lines && !$is_patch &&
3232			$line =~ /^This reverts commit/) {
3233			$is_revert = 1;
3234		}
3235
3236		if (!$in_header_lines && !$is_patch &&
3237		    $line =~ /((?:(?:BUG: K.|UB)SAN: |Call Trace:|stable\@|syzkaller))/) {
3238			$needs_fixes_tag = $1;
3239		}
3240
3241# Check Fixes: styles is correct
3242		if (!$in_header_lines &&
3243		    $line =~ /^\s*(fixes:?)\s*(?:commit\s*)?([0-9a-f]{5,40})(?:\s*($balanced_parens))?/i) {
3244			my $tag = $1;
3245			my $orig_commit = $2;
3246			my $title;
3247			my $title_has_quotes = 0;
3248			$fixes_tag = 1;
3249			if (defined $3) {
3250				# Always strip leading/trailing parens then double quotes if existing
3251				$title = substr($3, 1, -1);
3252				if ($title =~ /^".*"$/) {
3253					$title = substr($title, 1, -1);
3254					$title_has_quotes = 1;
3255				}
3256			} else {
3257				$title = "commit title"
3258			}
3259
3260
3261			my $tag_case = not ($tag eq "Fixes:");
3262			my $tag_space = not ($line =~ /^fixes:? [0-9a-f]{5,40} ($balanced_parens)/i);
3263
3264			my $id_length = not ($orig_commit =~ /^[0-9a-f]{12,40}$/i);
3265			my $id_case = not ($orig_commit !~ /[A-F]/);
3266
3267			my $id = "0123456789ab";
3268			my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3269							     $title);
3270
3271			if (defined($cid) && ($ctitle ne $title || $tag_case || $tag_space || $id_length || $id_case || !$title_has_quotes)) {
3272				my $fixed = "Fixes: $cid (\"$ctitle\")";
3273				if (WARN("BAD_FIXES_TAG",
3274				     "Please use correct Fixes: style 'Fixes: <12+ chars of sha1> (\"<title line>\")' - ie: '$fixed'\n" . $herecurr) &&
3275				    $fix) {
3276					$fixed[$fixlinenr] = $fixed;
3277				}
3278			}
3279		}
3280
3281# Check email subject for common tools that don't need to be mentioned
3282		if ($in_header_lines &&
3283		    $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3284			WARN("EMAIL_SUBJECT",
3285			     "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3286		}
3287
3288# Check for Gerrit Change-Ids not in any patch context
3289		if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3290			if (ERROR("GERRIT_CHANGE_ID",
3291			          "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3292			    $fix) {
3293				fix_delete_line($fixlinenr, $rawline);
3294			}
3295		}
3296
3297# Check if the commit log is in a possible stack dump
3298		if ($in_commit_log && !$commit_log_possible_stack_dump &&
3299		    ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3300		     $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3301					# timestamp
3302		     $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3303		     $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3304		     $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3305					# stack dump address styles
3306			$commit_log_possible_stack_dump = 1;
3307		}
3308
3309# Check for line lengths > 75 in commit log, warn once
3310		if ($in_commit_log && !$commit_log_long_line &&
3311		    length($line) > 75 &&
3312		    !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3313					# file delta changes
3314		      $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3315					# filename then :
3316		      $line =~ /^\s*(?:Fixes:|https?:|$link_tags_search|$signature_tags)/i ||
3317					# A Fixes:, link or signature tag line
3318		      $commit_log_possible_stack_dump)) {
3319			WARN("COMMIT_LOG_LONG_LINE",
3320			     "Prefer a maximum 75 chars per line (possible unwrapped commit description?)\n" . $herecurr);
3321			$commit_log_long_line = 1;
3322		}
3323
3324# Reset possible stack dump if a blank line is found
3325		if ($in_commit_log && $commit_log_possible_stack_dump &&
3326		    $line =~ /^\s*$/) {
3327			$commit_log_possible_stack_dump = 0;
3328		}
3329
3330# Check for odd tags before a URI/URL
3331		if ($in_commit_log &&
3332		    $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
3333			if ($1 =~ /^v(?:ersion)?\d+/i) {
3334				WARN("COMMIT_LOG_VERSIONING",
3335				     "Patch version information should be after the --- line\n" . $herecurr);
3336			} else {
3337				WARN("COMMIT_LOG_USE_LINK",
3338				     "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
3339			}
3340		}
3341
3342# Check for misuse of the link tags
3343		if ($in_commit_log &&
3344		    $line =~ /^\s*(\w+:)\s*(\S+)/) {
3345			my $tag = $1;
3346			my $value = $2;
3347			if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3348				WARN("COMMIT_LOG_WRONG_LINK",
3349				     "'$tag' should be followed by a public http(s) link\n" . $herecurr);
3350			}
3351		}
3352
3353# Check for lines starting with a #
3354		if ($in_commit_log && $line =~ /^#/) {
3355			if (WARN("COMMIT_COMMENT_SYMBOL",
3356				 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3357			    $fix) {
3358				$fixed[$fixlinenr] =~ s/^/ /;
3359			}
3360		}
3361
3362# Check for auto-generated unhandled placeholder text (mostly for cover letters)
3363		if (($in_commit_log || $in_header_lines) &&
3364		    $rawline =~ /(?:SUBJECT|BLURB) HERE/) {
3365			ERROR("PLACEHOLDER_USE",
3366			      "Placeholder text detected\n" . $herecurr);
3367		}
3368
3369# Check for git id commit length and improperly formed commit descriptions
3370# A correctly formed commit description is:
3371#    commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3372# with the commit subject '("' prefix and '")' suffix
3373# This is a fairly compilicated block as it tests for what appears to be
3374# bare SHA-1 hash with  minimum length of 5.  It also avoids several types of
3375# possible SHA-1 matches.
3376# A commit match can span multiple lines so this block attempts to find a
3377# complete typical commit on a maximum of 3 lines
3378		if ($perl_version_ok &&
3379		    $in_commit_log && !$commit_log_possible_stack_dump &&
3380		    $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3381		    $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3382		    (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3383		      ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3384		     ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3385		      $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3386		      $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3387			my $init_char = "c";
3388			my $orig_commit = "";
3389			my $short = 1;
3390			my $long = 0;
3391			my $case = 1;
3392			my $space = 1;
3393			my $id = '0123456789ab';
3394			my $orig_desc = "commit description";
3395			my $description = "";
3396			my $herectx = $herecurr;
3397			my $has_parens = 0;
3398			my $has_quotes = 0;
3399
3400			my $input = $line;
3401			if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3402				for (my $n = 0; $n < 2; $n++) {
3403					if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3404						$orig_desc = $1;
3405						$has_parens = 1;
3406						# Always strip leading/trailing parens then double quotes if existing
3407						$orig_desc = substr($orig_desc, 1, -1);
3408						if ($orig_desc =~ /^".*"$/) {
3409							$orig_desc = substr($orig_desc, 1, -1);
3410							$has_quotes = 1;
3411						}
3412						last;
3413					}
3414					last if ($#lines < $linenr + $n);
3415					$input .= " " . trim($rawlines[$linenr + $n]);
3416					$herectx .= "$rawlines[$linenr + $n]\n";
3417				}
3418				$herectx = $herecurr if (!$has_parens);
3419			}
3420
3421			if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3422				$init_char = $1;
3423				$orig_commit = lc($2);
3424				$short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3425				$long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3426				$space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3427				$case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3428			} elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3429				$orig_commit = lc($1);
3430			}
3431
3432			($id, $description) = git_commit_info($orig_commit,
3433							      $id, $orig_desc);
3434
3435			if (defined($id) &&
3436			    ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3437			    $last_git_commit_id_linenr != $linenr - 1) {
3438				ERROR("GIT_COMMIT_ID",
3439				      "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3440			}
3441			#don't report the next line if this line ends in commit and the sha1 hash is the next line
3442			$last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3443		}
3444
3445# Check for mailing list archives other than lore.kernel.org
3446		if ($rawline =~ m{http.*\b$obsolete_archives}) {
3447			WARN("PREFER_LORE_ARCHIVE",
3448			     "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3449		}
3450
3451# Check for added, moved or deleted files
3452		if (!$reported_maintainer_file && !$in_commit_log &&
3453		    ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3454		     $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3455		     ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3456		      (defined($1) || defined($2))))) {
3457			$is_patch = 1;
3458			$reported_maintainer_file = 1;
3459			WARN("FILE_PATH_CHANGES",
3460			     "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3461		}
3462
3463# Check for adding new DT bindings not in schema format
3464		if (!$in_commit_log &&
3465		    ($line =~ /^new file mode\s*\d+\s*$/) &&
3466		    ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3467			WARN("DT_SCHEMA_BINDING_PATCH",
3468			     "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3469		}
3470
3471# Check for wrappage within a valid hunk of the file
3472		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3473			ERROR("CORRUPTED_PATCH",
3474			      "patch seems to be corrupt (line wrapped?)\n" .
3475				$herecurr) if (!$emitted_corrupt++);
3476		}
3477
3478# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3479		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3480		    $rawline !~ m/^$UTF8*$/) {
3481			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3482
3483			my $blank = copy_spacing($rawline);
3484			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3485			my $hereptr = "$hereline$ptr\n";
3486
3487			CHK("INVALID_UTF8",
3488			    "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3489		}
3490
3491# Check if it's the start of a commit log
3492# (not a header line and we haven't seen the patch filename)
3493		if ($in_header_lines && $realfile =~ /^$/ &&
3494		    !($rawline =~ /^\s+(?:\S|$)/ ||
3495		      $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3496			$in_header_lines = 0;
3497			$in_commit_log = 1;
3498			$has_commit_log = 1;
3499		}
3500
3501# Check if there is UTF-8 in a commit log when a mail header has explicitly
3502# declined it, i.e defined some charset where it is missing.
3503		if ($in_header_lines &&
3504		    $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3505		    $1 !~ /utf-8/i) {
3506			$non_utf8_charset = 1;
3507		}
3508
3509		if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3510		    $rawline =~ /$NON_ASCII_UTF8/) {
3511			WARN("UTF8_BEFORE_PATCH",
3512			    "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3513		}
3514
3515# Check for absolute kernel paths in commit message
3516		if ($tree && $in_commit_log) {
3517			while ($line =~ m{(?:^|\s)(/\S*)}g) {
3518				my $file = $1;
3519
3520				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3521				    check_absolute_file($1, $herecurr)) {
3522					#
3523				} else {
3524					check_absolute_file($file, $herecurr);
3525				}
3526			}
3527		}
3528
3529# Check for various typo / spelling mistakes
3530		if (defined($misspellings) &&
3531		    ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3532			my $rawline_utf8 = decode("utf8", $rawline);
3533			while ($rawline_utf8 =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3534				my $typo = $1;
3535				my $blank = copy_spacing($rawline_utf8);
3536				my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3537				my $hereptr = "$hereline$ptr\n";
3538				my $typo_fix = $spelling_fix{lc($typo)};
3539				$typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3540				$typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3541				my $msg_level = \&WARN;
3542				$msg_level = \&CHK if ($file);
3543				if (&{$msg_level}("TYPO_SPELLING",
3544						  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3545				    $fix) {
3546					$fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3547				}
3548			}
3549		}
3550
3551# check for invalid commit id
3552		if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3553			my $id;
3554			my $description;
3555			($id, $description) = git_commit_info($2, undef, undef);
3556			if (!defined($id)) {
3557				WARN("UNKNOWN_COMMIT_ID",
3558				     "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3559			}
3560		}
3561
3562# check for repeated words separated by a single space
3563# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3564		if (($rawline =~ /^\+/ || $in_commit_log) &&
3565		    $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3566			pos($rawline) = 1 if (!$in_commit_log);
3567			while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3568
3569				my $first = $1;
3570				my $second = $2;
3571				my $start_pos = $-[1];
3572				my $end_pos = $+[2];
3573				if ($first =~ /(?:struct|union|enum)/) {
3574					pos($rawline) += length($first) + length($second) + 1;
3575					next;
3576				}
3577
3578				next if (lc($first) ne lc($second));
3579				next if ($first eq 'long');
3580
3581				# check for character before and after the word matches
3582				my $start_char = '';
3583				my $end_char = '';
3584				$start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3585				$end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3586
3587				next if ($start_char =~ /^\S$/);
3588				next if (index(" \t.,;?!", $end_char) == -1);
3589
3590				# avoid repeating hex occurrences like 'ff ff fe 09 ...'
3591				if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3592					next if (!exists($allow_repeated_words{lc($first)}));
3593				}
3594
3595				if (WARN("REPEATED_WORD",
3596					 "Possible repeated word: '$first'\n" . $herecurr) &&
3597				    $fix) {
3598					$fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3599				}
3600			}
3601
3602			# if it's a repeated word on consecutive lines in a comment block
3603			if ($prevline =~ /$;+\s*$/ &&
3604			    $prevrawline =~ /($word_pattern)\s*$/) {
3605				my $last_word = $1;
3606				if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3607					if (WARN("REPEATED_WORD",
3608						 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3609					    $fix) {
3610						$fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3611					}
3612				}
3613			}
3614		}
3615
3616# ignore non-hunk lines and lines being removed
3617		next if (!$hunk_line || $line =~ /^-/);
3618
3619#trailing whitespace
3620		if ($line =~ /^\+.*\015/) {
3621			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3622			if (ERROR("DOS_LINE_ENDINGS",
3623				  "DOS line endings\n" . $herevet) &&
3624			    $fix) {
3625				$fixed[$fixlinenr] =~ s/[\s\015]+$//;
3626			}
3627		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3628			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3629			if (ERROR("TRAILING_WHITESPACE",
3630				  "trailing whitespace\n" . $herevet) &&
3631			    $fix) {
3632				$fixed[$fixlinenr] =~ s/\s+$//;
3633			}
3634
3635			$rpt_cleaners = 1;
3636		}
3637
3638# Check for FSF mailing addresses.
3639		if ($rawline =~ /\bwrite to the Free/i ||
3640		    $rawline =~ /\b675\s+Mass\s+Ave/i ||
3641		    $rawline =~ /\b59\s+Temple\s+Pl/i ||
3642		    $rawline =~ /\b51\s+Franklin\s+St/i) {
3643			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3644			my $msg_level = \&ERROR;
3645			$msg_level = \&CHK if ($file);
3646			&{$msg_level}("FSF_MAILING_ADDRESS",
3647				      "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)
3648		}
3649
3650# check for Kconfig help text having a real description
3651# Only applies when adding the entry originally, after that we do not have
3652# sufficient context to determine whether it is indeed long enough.
3653		if ($realfile =~ /Kconfig/ &&
3654		    # 'choice' is usually the last thing on the line (though
3655		    # Kconfig supports named choices), so use a word boundary
3656		    # (\b) rather than a whitespace character (\s)
3657		    $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3658			my $ln = $linenr;
3659			my $needs_help = 0;
3660			my $has_help = 0;
3661			my $help_length = 0;
3662			while (defined $lines[$ln]) {
3663				my $f = $lines[$ln++];
3664
3665				next if ($f =~ /^-/);
3666				last if ($f !~ /^[\+ ]/);	# !patch context
3667
3668				if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3669					$needs_help = 1;
3670					next;
3671				}
3672				if ($f =~ /^\+\s*help\s*$/) {
3673					$has_help = 1;
3674					next;
3675				}
3676
3677				$f =~ s/^.//;	# strip patch context [+ ]
3678				$f =~ s/#.*//;	# strip # directives
3679				$f =~ s/^\s+//;	# strip leading blanks
3680				next if ($f =~ /^$/);	# skip blank lines
3681
3682				# At the end of this Kconfig block:
3683				# This only checks context lines in the patch
3684				# and so hopefully shouldn't trigger false
3685				# positives, even though some of these are
3686				# common words in help texts
3687				if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3688					       if|endif|menu|endmenu|source)\b/x) {
3689					last;
3690				}
3691				$help_length++ if ($has_help);
3692			}
3693			if ($needs_help &&
3694			    $help_length < $min_conf_desc_length) {
3695				my $stat_real = get_stat_real($linenr, $ln - 1);
3696				WARN("CONFIG_DESCRIPTION",
3697				     "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");
3698			}
3699		}
3700
3701# check MAINTAINERS entries
3702		if ($realfile =~ /^MAINTAINERS$/) {
3703# check MAINTAINERS entries for the right form
3704			if ($rawline =~ /^\+[A-Z]:/ &&
3705			    $rawline !~ /^\+[A-Z]:\t\S/) {
3706				if (WARN("MAINTAINERS_STYLE",
3707					 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3708				    $fix) {
3709					$fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3710				}
3711			}
3712# check MAINTAINERS entries for the right ordering too
3713			my $preferred_order = 'MRLSWQBCPTFXNK';
3714			if ($rawline =~ /^\+[A-Z]:/ &&
3715			    $prevrawline =~ /^[\+ ][A-Z]:/) {
3716				$rawline =~ /^\+([A-Z]):\s*(.*)/;
3717				my $cur = $1;
3718				my $curval = $2;
3719				$prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3720				my $prev = $1;
3721				my $prevval = $2;
3722				my $curindex = index($preferred_order, $cur);
3723				my $previndex = index($preferred_order, $prev);
3724				if ($curindex < 0) {
3725					WARN("MAINTAINERS_STYLE",
3726					     "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3727				} else {
3728					if ($previndex >= 0 && $curindex < $previndex) {
3729						WARN("MAINTAINERS_STYLE",
3730						     "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3731					} elsif ((($prev eq 'F' && $cur eq 'F') ||
3732						  ($prev eq 'X' && $cur eq 'X')) &&
3733						 ($prevval cmp $curval) > 0) {
3734						WARN("MAINTAINERS_STYLE",
3735						     "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3736					}
3737				}
3738			}
3739		}
3740
3741# check for DT compatible documentation
3742		if (defined $root &&
3743			(($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3744			 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3745
3746			my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3747
3748			my $dt_path = $root . "/Documentation/devicetree/bindings/";
3749			my $vp_file = $dt_path . "vendor-prefixes.yaml";
3750
3751			foreach my $compat (@compats) {
3752				my $compat2 = $compat;
3753				$compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3754				my $compat3 = $compat;
3755				$compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3756				`grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3757				if ( $? >> 8 ) {
3758					WARN("UNDOCUMENTED_DT_STRING",
3759					     "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3760				}
3761
3762				next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3763				my $vendor = $1;
3764				`grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3765				if ( $? >> 8 ) {
3766					WARN("UNDOCUMENTED_DT_STRING",
3767					     "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3768				}
3769			}
3770		}
3771
3772# Check for RGMII phy-mode with delay on PCB
3773		if ($realfile =~ /\.(dts|dtsi|dtso)$/ &&
3774		    $line =~ /^\+\s*(phy-mode|phy-connection-type)\s*=\s*"/ &&
3775		    !ctx_has_comment($first_line, $linenr)) {
3776			my $prop = $1;
3777			my $mode = get_quoted_string($line, $rawline);
3778			if ($mode =~ /^"rgmii(?:|-rxid|-txid)"$/) {
3779				WARN("UNCOMMENTED_RGMII_MODE",
3780				     "$prop $mode without comment -- delays on the PCB should be described, otherwise use \"rgmii-id\"\n" . $herecurr);
3781			}
3782		}
3783
3784# check for using SPDX license tag at beginning of files
3785		if ($realline == $checklicenseline) {
3786			if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3787				$checklicenseline = 2;
3788			} elsif ($rawline =~ /^\+/) {
3789				my $comment = "";
3790				if ($realfile =~ /\.(h|s|S)$/) {
3791					$comment = '/*';
3792				} elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3793					$comment = '//';
3794				} elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3795					$comment = '#';
3796				} elsif ($realfile =~ /\.rst$/) {
3797					$comment = '..';
3798				}
3799
3800# check SPDX comment style for .[chsS] files
3801				if ($realfile =~ /\.[chsS]$/ &&
3802				    $rawline =~ /SPDX-License-Identifier:/ &&
3803				    $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3804					WARN("SPDX_LICENSE_TAG",
3805					     "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3806				}
3807
3808				if ($comment !~ /^$/ &&
3809				    $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3810					WARN("SPDX_LICENSE_TAG",
3811					     "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3812				} elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3813					my $spdx_license = $1;
3814					if (!is_SPDX_License_valid($spdx_license)) {
3815						WARN("SPDX_LICENSE_TAG",
3816						     "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3817					}
3818					if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3819					    $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
3820						my $msg_level = \&WARN;
3821						$msg_level = \&CHK if ($file);
3822						if (&{$msg_level}("SPDX_LICENSE_TAG",
3823
3824								  "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3825						    $fix) {
3826							$fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3827						}
3828					}
3829					if ($realfile =~ m@^include/dt-bindings/@ &&
3830					    $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3831						WARN("SPDX_LICENSE_TAG",
3832						     "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3833					}
3834				}
3835			}
3836		}
3837
3838# check for embedded filenames
3839		if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
3840			WARN("EMBEDDED_FILENAME",
3841			     "It's generally not useful to have the filename in the file\n" . $herecurr);
3842		}
3843
3844# check we are in a valid source file if not then ignore this hunk
3845		next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3846
3847# check for using SPDX-License-Identifier on the wrong line number
3848		if ($realline != $checklicenseline &&
3849		    $rawline =~ /\bSPDX-License-Identifier:/ &&
3850		    substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3851			WARN("SPDX_LICENSE_TAG",
3852			     "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3853		}
3854
3855# line length limit (with some exclusions)
3856#
3857# There are a few types of lines that may extend beyond $max_line_length:
3858#	logging functions like pr_info that end in a string
3859#	lines with a single string
3860#	#defines that are a single string
3861#	lines with an RFC3986 like URL
3862#
3863# There are 3 different line length message types:
3864# LONG_LINE_COMMENT	a comment starts before but extends beyond $max_line_length
3865# LONG_LINE_STRING	a string starts before but extends beyond $max_line_length
3866# LONG_LINE		all other lines longer than $max_line_length
3867#
3868# if LONG_LINE is ignored, the other 2 types are also ignored
3869#
3870
3871		if ($line =~ /^\+/ && $length > $max_line_length) {
3872			my $msg_type = "LONG_LINE";
3873
3874			# Check the allowed long line types first
3875
3876			# logging functions that end in a string that starts
3877			# before $max_line_length
3878			if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3879			    length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3880				$msg_type = "";
3881
3882			# lines with only strings (w/ possible termination)
3883			# #defines with only strings
3884			} elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3885				 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3886				$msg_type = "";
3887
3888			# More special cases
3889			} elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3890				 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3891				$msg_type = "";
3892
3893			# URL ($rawline is used in case the URL is in a comment)
3894			} elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3895				$msg_type = "";
3896
3897			# Otherwise set the alternate message types
3898
3899			# a comment starts before $max_line_length
3900			} elsif ($line =~ /($;[\s$;]*)$/ &&
3901				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3902				$msg_type = "LONG_LINE_COMMENT"
3903
3904			# a quoted string starts before $max_line_length
3905			} elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3906				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3907				$msg_type = "LONG_LINE_STRING"
3908			}
3909
3910			if ($msg_type ne "" &&
3911			    show_type("LONG_LINE") && show_type($msg_type)) {
3912				my $msg_level = \&WARN;
3913				$msg_level = \&CHK if ($file);
3914				&{$msg_level}($msg_type,
3915					      "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3916			}
3917		}
3918
3919# check for adding lines without a newline.
3920		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3921			if (WARN("MISSING_EOF_NEWLINE",
3922			         "adding a line without newline at end of file\n" . $herecurr) &&
3923			    $fix) {
3924				fix_delete_line($fixlinenr+1, "No newline at end of file");
3925			}
3926		}
3927
3928# check for .L prefix local symbols in .S files
3929		if ($realfile =~ /\.S$/ &&
3930		    $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3931			WARN("AVOID_L_PREFIX",
3932			     "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);
3933		}
3934
3935# check we are in a valid source file C or perl if not then ignore this hunk
3936		next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3937
3938# at the beginning of a line any tabs must come first and anything
3939# more than $tabsize must use tabs.
3940		if ($rawline =~ /^\+\s* \t\s*\S/ ||
3941		    $rawline =~ /^\+\s*        \s*/) {
3942			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3943			$rpt_cleaners = 1;
3944			if (ERROR("CODE_INDENT",
3945				  "code indent should use tabs where possible\n" . $herevet) &&
3946			    $fix) {
3947				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3948			}
3949		}
3950
3951# check for space before tabs.
3952		if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3953			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3954			if (WARN("SPACE_BEFORE_TAB",
3955				"please, no space before tabs\n" . $herevet) &&
3956			    $fix) {
3957				while ($fixed[$fixlinenr] =~
3958					   s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3959				while ($fixed[$fixlinenr] =~
3960					   s/(^\+.*) +\t/$1\t/) {}
3961			}
3962		}
3963
3964# check for assignments on the start of a line
3965		if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3966			my $operator = $1;
3967			if (CHK("ASSIGNMENT_CONTINUATIONS",
3968				"Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3969			    $fix && $prevrawline =~ /^\+/) {
3970				# add assignment operator to the previous line, remove from current line
3971				$fixed[$fixlinenr - 1] .= " $operator";
3972				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3973			}
3974		}
3975
3976# check for && or || at the start of a line
3977		if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3978			my $operator = $1;
3979			if (CHK("LOGICAL_CONTINUATIONS",
3980				"Logical continuations should be on the previous line\n" . $hereprev) &&
3981			    $fix && $prevrawline =~ /^\+/) {
3982				# insert logical operator at last non-comment, non-whitepsace char on previous line
3983				$prevline =~ /[\s$;]*$/;
3984				my $line_end = substr($prevrawline, $-[0]);
3985				$fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3986				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3987			}
3988		}
3989
3990# check indentation starts on a tab stop
3991		if ($perl_version_ok &&
3992		    $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3993			my $indent = length($1);
3994			if ($indent % $tabsize) {
3995				if (WARN("TABSTOP",
3996					 "Statements should start on a tabstop\n" . $herecurr) &&
3997				    $fix) {
3998					$fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3999				}
4000			}
4001		}
4002
4003# check multi-line statement indentation matches previous line
4004		if ($perl_version_ok &&
4005		    $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
4006			$prevline =~ /^\+(\t*)(.*)$/;
4007			my $oldindent = $1;
4008			my $rest = $2;
4009
4010			my $pos = pos_last_openparen($rest);
4011			if ($pos >= 0) {
4012				$line =~ /^(\+| )([ \t]*)/;
4013				my $newindent = $2;
4014
4015				my $goodtabindent = $oldindent .
4016					"\t" x ($pos / $tabsize) .
4017					" "  x ($pos % $tabsize);
4018				my $goodspaceindent = $oldindent . " "  x $pos;
4019
4020				if ($newindent ne $goodtabindent &&
4021				    $newindent ne $goodspaceindent) {
4022
4023					if (CHK("PARENTHESIS_ALIGNMENT",
4024						"Alignment should match open parenthesis\n" . $hereprev) &&
4025					    $fix && $line =~ /^\+/) {
4026						$fixed[$fixlinenr] =~
4027						    s/^\+[ \t]*/\+$goodtabindent/;
4028					}
4029				}
4030			}
4031		}
4032
4033# check for space after cast like "(int) foo" or "(struct foo) bar"
4034# avoid checking a few false positives:
4035#   "sizeof(<type>)" or "__alignof__(<type>)"
4036#   function pointer declarations like "(*foo)(int) = bar;"
4037#   structure definitions like "(struct foo) { 0 };"
4038#   multiline macros that define functions
4039#   known attributes or the __attribute__ keyword
4040		if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
4041		    (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
4042			if (CHK("SPACING",
4043				"No space is necessary after a cast\n" . $herecurr) &&
4044			    $fix) {
4045				$fixed[$fixlinenr] =~
4046				    s/(\(\s*$Type\s*\))[ \t]+/$1/;
4047			}
4048		}
4049
4050# Block comments use * on subsequent lines
4051		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4052		    $prevrawline =~ /^\+.*?\/\*/ &&		#starting /*
4053		    $prevrawline !~ /\*\/[ \t]*$/ &&		#no trailing */
4054		    $rawline =~ /^\+/ &&			#line is new
4055		    $rawline !~ /^\+[ \t]*\*/) {		#no leading *
4056			WARN("BLOCK_COMMENT_STYLE",
4057			     "Block comments use * on subsequent lines\n" . $hereprev);
4058		}
4059
4060# Block comments use */ on trailing lines
4061		if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&	#trailing */
4062		    $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&	#inline /*...*/
4063		    $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&	#trailing **/
4064		    $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {	#non blank */
4065			WARN("BLOCK_COMMENT_STYLE",
4066			     "Block comments use a trailing */ on a separate line\n" . $herecurr);
4067		}
4068
4069# Block comment * alignment
4070		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4071		    $line =~ /^\+[ \t]*$;/ &&			#leading comment
4072		    $rawline =~ /^\+[ \t]*\*/ &&		#leading *
4073		    (($prevrawline =~ /^\+.*?\/\*/ &&		#leading /*
4074		      $prevrawline !~ /\*\/[ \t]*$/) ||		#no trailing */
4075		     $prevrawline =~ /^\+[ \t]*\*/)) {		#leading *
4076			my $oldindent;
4077			$prevrawline =~ m@^\+([ \t]*/?)\*@;
4078			if (defined($1)) {
4079				$oldindent = expand_tabs($1);
4080			} else {
4081				$prevrawline =~ m@^\+(.*/?)\*@;
4082				$oldindent = expand_tabs($1);
4083			}
4084			$rawline =~ m@^\+([ \t]*)\*@;
4085			my $newindent = $1;
4086			$newindent = expand_tabs($newindent);
4087			if (length($oldindent) ne length($newindent)) {
4088				WARN("BLOCK_COMMENT_STYLE",
4089				     "Block comments should align the * on each line\n" . $hereprev);
4090			}
4091		}
4092
4093# check for missing blank lines after struct/union declarations
4094# with exceptions for various attributes and macros
4095		if ($prevline =~ /^[\+ ]};?\s*$/ &&
4096		    $line =~ /^\+/ &&
4097		    !($line =~ /^\+\s*$/ ||
4098		      $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param|ALLOW_ERROR_INJECTION)/ ||
4099		      $line =~ /^\+\s*MODULE_/i ||
4100		      $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4101		      $line =~ /^\+[a-z_]*init/ ||
4102		      $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4103		      $line =~ /^\+\s*DECLARE/ ||
4104		      $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4105		      $line =~ /^\+\s*__setup/)) {
4106			if (CHK("LINE_SPACING",
4107				"Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4108			    $fix) {
4109				fix_insert_line($fixlinenr, "\+");
4110			}
4111		}
4112
4113# check for multiple consecutive blank lines
4114		if ($prevline =~ /^[\+ ]\s*$/ &&
4115		    $line =~ /^\+\s*$/ &&
4116		    $last_blank_line != ($linenr - 1)) {
4117			if (CHK("LINE_SPACING",
4118				"Please don't use multiple blank lines\n" . $hereprev) &&
4119			    $fix) {
4120				fix_delete_line($fixlinenr, $rawline);
4121			}
4122
4123			$last_blank_line = $linenr;
4124		}
4125
4126# check for missing blank lines after declarations
4127# (declarations must have the same indentation and not be at the start of line)
4128		if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4129			# use temporaries
4130			my $sl = $sline;
4131			my $pl = $prevline;
4132			# remove $Attribute/$Sparse uses to simplify comparisons
4133			$sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4134			$pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4135			if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4136			# function pointer declarations
4137			     $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4138			# foo bar; where foo is some local typedef or #define
4139			     $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4140			# known declaration macros
4141			     $pl =~ /^\+\s+$declaration_macros/) &&
4142			# for "else if" which can look like "$Ident $Ident"
4143			    !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4144			# other possible extensions of declaration lines
4145			      $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4146			# not starting a section or a macro "\" extended line
4147			      $pl =~ /(?:\{\s*|\\)$/) &&
4148			# looks like a declaration
4149			    !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4150			# function pointer declarations
4151			      $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4152			# foo bar; where foo is some local typedef or #define
4153			      $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4154			# known declaration macros
4155			      $sl =~ /^\+\s+$declaration_macros/ ||
4156			# start of struct or union or enum
4157			      $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4158			# start or end of block or continuation of declaration
4159			      $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4160			# bitfield continuation
4161			      $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4162			# other possible extensions of declaration lines
4163			      $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4164				if (WARN("LINE_SPACING",
4165					 "Missing a blank line after declarations\n" . $hereprev) &&
4166				    $fix) {
4167					fix_insert_line($fixlinenr, "\+");
4168				}
4169			}
4170		}
4171
4172# check for spaces at the beginning of a line.
4173# Exceptions:
4174#  1) within comments
4175#  2) indented preprocessor commands
4176#  3) hanging labels
4177		if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
4178			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4179			if (WARN("LEADING_SPACE",
4180				 "please, no spaces at the start of a line\n" . $herevet) &&
4181			    $fix) {
4182				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4183			}
4184		}
4185
4186# check we are in a valid C source file if not then ignore this hunk
4187		next if ($realfile !~ /\.(h|c)$/);
4188
4189# check for unusual line ending [ or (
4190		if ($line =~ /^\+.*([\[\(])\s*$/) {
4191			CHK("OPEN_ENDED_LINE",
4192			    "Lines should not end with a '$1'\n" . $herecurr);
4193		}
4194
4195# check if this appears to be the start function declaration, save the name
4196		if ($sline =~ /^\+\{\s*$/ &&
4197		    $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4198			$context_function = $1;
4199		}
4200
4201# check if this appears to be the end of function declaration
4202		if ($sline =~ /^\+\}\s*$/) {
4203			undef $context_function;
4204		}
4205
4206# check indentation of any line with a bare else
4207# (but not if it is a multiple line "if (foo) return bar; else return baz;")
4208# if the previous line is a break or return and is indented 1 tab more...
4209		if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4210			my $tabs = length($1) + 1;
4211			if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4212			    ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4213			     defined $lines[$linenr] &&
4214			     $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4215				WARN("UNNECESSARY_ELSE",
4216				     "else is not generally useful after a break or return\n" . $hereprev);
4217			}
4218		}
4219
4220# check indentation of a line with a break;
4221# if the previous line is a goto, return or break
4222# and is indented the same # of tabs
4223		if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4224			my $tabs = $1;
4225			if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4226				if (WARN("UNNECESSARY_BREAK",
4227					 "break is not useful after a $1\n" . $hereprev) &&
4228				    $fix) {
4229					fix_delete_line($fixlinenr, $rawline);
4230				}
4231			}
4232		}
4233
4234# check for RCS/CVS revision markers
4235		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4236			WARN("CVS_KEYWORD",
4237			     "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4238		}
4239
4240# check for old HOTPLUG __dev<foo> section markings
4241		if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4242			WARN("HOTPLUG_SECTION",
4243			     "Using $1 is unnecessary\n" . $herecurr);
4244		}
4245
4246# Check for potential 'bare' types
4247		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4248		    $realline_next);
4249#print "LINE<$line>\n";
4250		if ($linenr > $suppress_statement &&
4251		    $realcnt && $sline =~ /.\s*\S/) {
4252			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4253				ctx_statement_block($linenr, $realcnt, 0);
4254			$stat =~ s/\n./\n /g;
4255			$cond =~ s/\n./\n /g;
4256
4257#print "linenr<$linenr> <$stat>\n";
4258			# If this statement has no statement boundaries within
4259			# it there is no point in retrying a statement scan
4260			# until we hit end of it.
4261			my $frag = $stat; $frag =~ s/;+\s*$//;
4262			if ($frag !~ /(?:{|;)/) {
4263#print "skip<$line_nr_next>\n";
4264				$suppress_statement = $line_nr_next;
4265			}
4266
4267			# Find the real next line.
4268			$realline_next = $line_nr_next;
4269			if (defined $realline_next &&
4270			    (!defined $lines[$realline_next - 1] ||
4271			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4272				$realline_next++;
4273			}
4274
4275			my $s = $stat;
4276			$s =~ s/{.*$//s;
4277
4278			# Ignore goto labels.
4279			if ($s =~ /$Ident:\*$/s) {
4280
4281			# Ignore functions being called
4282			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4283
4284			} elsif ($s =~ /^.\s*else\b/s) {
4285
4286			# declarations always start with types
4287			} 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) {
4288				my $type = $1;
4289				$type =~ s/\s+/ /g;
4290				possible($type, "A:" . $s);
4291
4292			# definitions in global scope can only start with types
4293			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4294				possible($1, "B:" . $s);
4295			}
4296
4297			# any (foo ... *) is a pointer cast, and foo is a type
4298			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4299				possible($1, "C:" . $s);
4300			}
4301
4302			# Check for any sort of function declaration.
4303			# int foo(something bar, other baz);
4304			# void (*store_gdt)(x86_descr_ptr *);
4305			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4306				my ($name_len) = length($1);
4307
4308				my $ctx = $s;
4309				substr($ctx, 0, $name_len + 1, '');
4310				$ctx =~ s/\)[^\)]*$//;
4311
4312				for my $arg (split(/\s*,\s*/, $ctx)) {
4313					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4314
4315						possible($1, "D:" . $s);
4316					}
4317				}
4318			}
4319
4320		}
4321
4322#
4323# Checks which may be anchored in the context.
4324#
4325
4326# Check for switch () and associated case and default
4327# statements should be at the same indent.
4328		if ($line=~/\bswitch\s*\(.*\)/) {
4329			my $err = '';
4330			my $sep = '';
4331			my @ctx = ctx_block_outer($linenr, $realcnt);
4332			shift(@ctx);
4333			for my $ctx (@ctx) {
4334				my ($clen, $cindent) = line_stats($ctx);
4335				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4336							$indent != $cindent) {
4337					$err .= "$sep$ctx\n";
4338					$sep = '';
4339				} else {
4340					$sep = "[...]\n";
4341				}
4342			}
4343			if ($err ne '') {
4344				ERROR("SWITCH_CASE_INDENT_LEVEL",
4345				      "switch and case should be at the same indent\n$hereline$err");
4346			}
4347		}
4348
4349# if/while/etc brace do not go on next line, unless defining a do while loop,
4350# or if that brace on the next line is for something else
4351		if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4352			my $pre_ctx = "$1$2";
4353
4354			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4355
4356			if ($line =~ /^\+\t{6,}/) {
4357				WARN("DEEP_INDENTATION",
4358				     "Too many leading tabs - consider code refactoring\n" . $herecurr);
4359			}
4360
4361			my $ctx_cnt = $realcnt - $#ctx - 1;
4362			my $ctx = join("\n", @ctx);
4363
4364			my $ctx_ln = $linenr;
4365			my $ctx_skip = $realcnt;
4366
4367			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4368					defined $lines[$ctx_ln - 1] &&
4369					$lines[$ctx_ln - 1] =~ /^-/)) {
4370				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4371				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4372				$ctx_ln++;
4373			}
4374
4375			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4376			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4377
4378			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4379				ERROR("OPEN_BRACE",
4380				      "that open brace { should be on the previous line\n" .
4381					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4382			}
4383			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4384			    $ctx =~ /\)\s*\;\s*$/ &&
4385			    defined $lines[$ctx_ln - 1])
4386			{
4387				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4388				if ($nindent > $indent) {
4389					WARN("TRAILING_SEMICOLON",
4390					     "trailing semicolon indicates no statements, indent implies otherwise\n" .
4391						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4392				}
4393			}
4394		}
4395
4396# Check relative indent for conditionals and blocks.
4397		if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4398			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4399				ctx_statement_block($linenr, $realcnt, 0)
4400					if (!defined $stat);
4401			my ($s, $c) = ($stat, $cond);
4402
4403			substr($s, 0, length($c), '');
4404
4405			# remove inline comments
4406			$s =~ s/$;/ /g;
4407			$c =~ s/$;/ /g;
4408
4409			# Find out how long the conditional actually is.
4410			my @newlines = ($c =~ /\n/gs);
4411			my $cond_lines = 1 + $#newlines;
4412
4413			# Make sure we remove the line prefixes as we have
4414			# none on the first line, and are going to readd them
4415			# where necessary.
4416			$s =~ s/\n./\n/gs;
4417			while ($s =~ /\n\s+\\\n/) {
4418				$cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4419			}
4420
4421			# We want to check the first line inside the block
4422			# starting at the end of the conditional, so remove:
4423			#  1) any blank line termination
4424			#  2) any opening brace { on end of the line
4425			#  3) any do (...) {
4426			my $continuation = 0;
4427			my $check = 0;
4428			$s =~ s/^.*\bdo\b//;
4429			$s =~ s/^\s*{//;
4430			if ($s =~ s/^\s*\\//) {
4431				$continuation = 1;
4432			}
4433			if ($s =~ s/^\s*?\n//) {
4434				$check = 1;
4435				$cond_lines++;
4436			}
4437
4438			# Also ignore a loop construct at the end of a
4439			# preprocessor statement.
4440			if (($prevline =~ /^.\s*#\s*define\s/ ||
4441			    $prevline =~ /\\\s*$/) && $continuation == 0) {
4442				$check = 0;
4443			}
4444
4445			my $cond_ptr = -1;
4446			$continuation = 0;
4447			while ($cond_ptr != $cond_lines) {
4448				$cond_ptr = $cond_lines;
4449
4450				# If we see an #else/#elif then the code
4451				# is not linear.
4452				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4453					$check = 0;
4454				}
4455
4456				# Ignore:
4457				#  1) blank lines, they should be at 0,
4458				#  2) preprocessor lines, and
4459				#  3) labels.
4460				if ($continuation ||
4461				    $s =~ /^\s*?\n/ ||
4462				    $s =~ /^\s*#\s*?/ ||
4463				    $s =~ /^\s*$Ident\s*:/) {
4464					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4465					if ($s =~ s/^.*?\n//) {
4466						$cond_lines++;
4467					}
4468				}
4469			}
4470
4471			my (undef, $sindent) = line_stats("+" . $s);
4472			my $stat_real = raw_line($linenr, $cond_lines);
4473
4474			# Check if either of these lines are modified, else
4475			# this is not this patch's fault.
4476			if (!defined($stat_real) ||
4477			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4478				$check = 0;
4479			}
4480			if (defined($stat_real) && $cond_lines > 1) {
4481				$stat_real = "[...]\n$stat_real";
4482			}
4483
4484			#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";
4485
4486			if ($check && $s ne '' &&
4487			    (($sindent % $tabsize) != 0 ||
4488			     ($sindent < $indent) ||
4489			     ($sindent == $indent &&
4490			      ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4491			     ($sindent > $indent + $tabsize))) {
4492				WARN("SUSPECT_CODE_INDENT",
4493				     "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4494			}
4495		}
4496
4497		# Track the 'values' across context and added lines.
4498		my $opline = $line; $opline =~ s/^./ /;
4499		my ($curr_values, $curr_vars) =
4500				annotate_values($opline . "\n", $prev_values);
4501		$curr_values = $prev_values . $curr_values;
4502		if ($dbg_values) {
4503			my $outline = $opline; $outline =~ s/\t/ /g;
4504			print "$linenr > .$outline\n";
4505			print "$linenr > $curr_values\n";
4506			print "$linenr >  $curr_vars\n";
4507		}
4508		$prev_values = substr($curr_values, -1);
4509
4510#ignore lines not being added
4511		next if ($line =~ /^[^\+]/);
4512
4513# check for self assignments used to avoid compiler warnings
4514# e.g.:	int foo = foo, *bar = NULL;
4515#	struct foo bar = *(&(bar));
4516		if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4517			my $var = $1;
4518			if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4519				WARN("SELF_ASSIGNMENT",
4520				     "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4521			}
4522		}
4523
4524# check for dereferences that span multiple lines
4525		if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4526		    $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4527			$prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4528			my $ref = $1;
4529			$line =~ /^.\s*($Lval)/;
4530			$ref .= $1;
4531			$ref =~ s/\s//g;
4532			WARN("MULTILINE_DEREFERENCE",
4533			     "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4534		}
4535
4536# check for declarations of signed or unsigned without int
4537		while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4538			my $type = $1;
4539			my $var = $2;
4540			$var = "" if (!defined $var);
4541			if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4542				my $sign = $1;
4543				my $pointer = $2;
4544
4545				$pointer = "" if (!defined $pointer);
4546
4547				if (WARN("UNSPECIFIED_INT",
4548					 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4549				    $fix) {
4550					my $decl = trim($sign) . " int ";
4551					my $comp_pointer = $pointer;
4552					$comp_pointer =~ s/\s//g;
4553					$decl .= $comp_pointer;
4554					$decl = rtrim($decl) if ($var eq "");
4555					$fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4556				}
4557			}
4558		}
4559
4560# TEST: allow direct testing of the type matcher.
4561		if ($dbg_type) {
4562			if ($line =~ /^.\s*$Declare\s*$/) {
4563				ERROR("TEST_TYPE",
4564				      "TEST: is type\n" . $herecurr);
4565			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4566				ERROR("TEST_NOT_TYPE",
4567				      "TEST: is not type ($1 is)\n". $herecurr);
4568			}
4569			next;
4570		}
4571# TEST: allow direct testing of the attribute matcher.
4572		if ($dbg_attr) {
4573			if ($line =~ /^.\s*$Modifier\s*$/) {
4574				ERROR("TEST_ATTR",
4575				      "TEST: is attr\n" . $herecurr);
4576			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4577				ERROR("TEST_NOT_ATTR",
4578				      "TEST: is not attr ($1 is)\n". $herecurr);
4579			}
4580			next;
4581		}
4582
4583# check for initialisation to aggregates open brace on the next line
4584		if ($line =~ /^.\s*{/ &&
4585		    $prevline =~ /(?:^|[^=])=\s*$/) {
4586			if (ERROR("OPEN_BRACE",
4587				  "that open brace { should be on the previous line\n" . $hereprev) &&
4588			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4589				fix_delete_line($fixlinenr - 1, $prevrawline);
4590				fix_delete_line($fixlinenr, $rawline);
4591				my $fixedline = $prevrawline;
4592				$fixedline =~ s/\s*=\s*$/ = {/;
4593				fix_insert_line($fixlinenr, $fixedline);
4594				$fixedline = $line;
4595				$fixedline =~ s/^(.\s*)\{\s*/$1/;
4596				fix_insert_line($fixlinenr, $fixedline);
4597			}
4598		}
4599
4600#
4601# Checks which are anchored on the added line.
4602#
4603
4604# check for malformed paths in #include statements (uses RAW line)
4605		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4606			my $path = $1;
4607			if ($path =~ m{//}) {
4608				ERROR("MALFORMED_INCLUDE",
4609				      "malformed #include filename\n" . $herecurr);
4610			}
4611			if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4612				ERROR("UAPI_INCLUDE",
4613				      "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4614			}
4615		}
4616
4617# no C99 // comments
4618		if ($line =~ m{//}) {
4619			if (ERROR("C99_COMMENTS",
4620				  "do not use C99 // comments\n" . $herecurr) &&
4621			    $fix) {
4622				my $line = $fixed[$fixlinenr];
4623				if ($line =~ /\/\/(.*)$/) {
4624					my $comment = trim($1);
4625					$fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4626				}
4627			}
4628		}
4629		# Remove C99 comments.
4630		$line =~ s@//.*@@;
4631		$opline =~ s@//.*@@;
4632
4633# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4634# the whole statement.
4635#print "APW <$lines[$realline_next - 1]>\n";
4636		if (defined $realline_next &&
4637		    exists $lines[$realline_next - 1] &&
4638		    !defined $suppress_export{$realline_next} &&
4639		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4640			# Handle definitions which produce identifiers with
4641			# a prefix:
4642			#   XXX(foo);
4643			#   EXPORT_SYMBOL(something_foo);
4644			my $name = $1;
4645			$name =~ s/^\s*($Ident).*/$1/;
4646			if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4647			    $name =~ /^${Ident}_$2/) {
4648#print "FOO C name<$name>\n";
4649				$suppress_export{$realline_next} = 1;
4650
4651			} elsif ($stat !~ /(?:
4652				\n.}\s*$|
4653				^.DEFINE_$Ident\(\Q$name\E\)|
4654				^.DECLARE_$Ident\(\Q$name\E\)|
4655				^.LIST_HEAD\(\Q$name\E\)|
4656				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4657				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4658			    )/x) {
4659#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4660				$suppress_export{$realline_next} = 2;
4661			} else {
4662				$suppress_export{$realline_next} = 1;
4663			}
4664		}
4665		if (!defined $suppress_export{$linenr} &&
4666		    $prevline =~ /^.\s*$/ &&
4667		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4668#print "FOO B <$lines[$linenr - 1]>\n";
4669			$suppress_export{$linenr} = 2;
4670		}
4671		if (defined $suppress_export{$linenr} &&
4672		    $suppress_export{$linenr} == 2) {
4673			WARN("EXPORT_SYMBOL",
4674			     "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4675		}
4676
4677# check for global initialisers.
4678		if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4679		    !exclude_global_initialisers($realfile)) {
4680			if (ERROR("GLOBAL_INITIALISERS",
4681				  "do not initialise globals to $1\n" . $herecurr) &&
4682			    $fix) {
4683				$fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4684			}
4685		}
4686# check for static initialisers.
4687		if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4688			if (ERROR("INITIALISED_STATIC",
4689				  "do not initialise statics to $1\n" .
4690				      $herecurr) &&
4691			    $fix) {
4692				$fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4693			}
4694		}
4695
4696# check for misordered declarations of char/short/int/long with signed/unsigned
4697		while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4698			my $tmp = trim($1);
4699			WARN("MISORDERED_TYPE",
4700			     "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4701		}
4702
4703# check for unnecessary <signed> int declarations of short/long/long long
4704		while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4705			my $type = trim($1);
4706			next if ($type !~ /\bint\b/);
4707			next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4708			my $new_type = $type;
4709			$new_type =~ s/\b\s*int\s*\b/ /;
4710			$new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4711			$new_type =~ s/^const\s+//;
4712			$new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4713			$new_type = "const $new_type" if ($type =~ /^const\b/);
4714			$new_type =~ s/\s+/ /g;
4715			$new_type = trim($new_type);
4716			if (WARN("UNNECESSARY_INT",
4717				 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4718			    $fix) {
4719				$fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4720			}
4721		}
4722
4723# check for static const char * arrays.
4724		if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4725			WARN("STATIC_CONST_CHAR_ARRAY",
4726			     "static const char * array should probably be static const char * const\n" .
4727				$herecurr);
4728		}
4729
4730# check for initialized const char arrays that should be static const
4731		if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4732			if (WARN("STATIC_CONST_CHAR_ARRAY",
4733				 "const array should probably be static const\n" . $herecurr) &&
4734			    $fix) {
4735				$fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4736			}
4737		}
4738
4739# check for static char foo[] = "bar" declarations.
4740		if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4741			WARN("STATIC_CONST_CHAR_ARRAY",
4742			     "static char array declaration should probably be static const char\n" .
4743				$herecurr);
4744		}
4745
4746# check for const <foo> const where <foo> is not a pointer or array type
4747		if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4748			my $found = $1;
4749			if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4750				WARN("CONST_CONST",
4751				     "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4752			} elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4753				WARN("CONST_CONST",
4754				     "'const $found const' should probably be 'const $found'\n" . $herecurr);
4755			}
4756		}
4757
4758# check for const static or static <non ptr type> const declarations
4759# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4760		if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4761		    $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4762			if (WARN("STATIC_CONST",
4763				 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4764			    $fix) {
4765				$fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4766				$fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4767			}
4768		}
4769
4770# check for non-global char *foo[] = {"bar", ...} declarations.
4771		if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4772			WARN("STATIC_CONST_CHAR_ARRAY",
4773			     "char * array declaration might be better as static const\n" .
4774				$herecurr);
4775		}
4776
4777# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4778		if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4779			my $array = $1;
4780			if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4781				my $array_div = $1;
4782				if (WARN("ARRAY_SIZE",
4783					 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4784				    $fix) {
4785					$fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4786				}
4787			}
4788		}
4789
4790# check for function declarations without arguments like "int foo()"
4791		if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4792			if (ERROR("FUNCTION_WITHOUT_ARGS",
4793				  "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4794			    $fix) {
4795				$fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4796			}
4797		}
4798
4799# check for new typedefs, only function parameters and sparse annotations
4800# make sense.
4801		if ($line =~ /\btypedef\s/ &&
4802		    $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4803		    $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4804		    $line !~ /\b$typeTypedefs\b/ &&
4805		    $line !~ /\b__bitwise\b/) {
4806			WARN("NEW_TYPEDEFS",
4807			     "do not add new typedefs\n" . $herecurr);
4808		}
4809
4810# * goes on variable not on type
4811		# (char*[ const])
4812		while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4813			#print "AA<$1>\n";
4814			my ($ident, $from, $to) = ($1, $2, $2);
4815
4816			# Should start with a space.
4817			$to =~ s/^(\S)/ $1/;
4818			# Should not end with a space.
4819			$to =~ s/\s+$//;
4820			# '*'s should not have spaces between.
4821			while ($to =~ s/\*\s+\*/\*\*/) {
4822			}
4823
4824##			print "1: from<$from> to<$to> ident<$ident>\n";
4825			if ($from ne $to) {
4826				if (ERROR("POINTER_LOCATION",
4827					  "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4828				    $fix) {
4829					my $sub_from = $ident;
4830					my $sub_to = $ident;
4831					$sub_to =~ s/\Q$from\E/$to/;
4832					$fixed[$fixlinenr] =~
4833					    s@\Q$sub_from\E@$sub_to@;
4834				}
4835			}
4836		}
4837		while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4838			#print "BB<$1>\n";
4839			my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4840
4841			# Should start with a space.
4842			$to =~ s/^(\S)/ $1/;
4843			# Should not end with a space.
4844			$to =~ s/\s+$//;
4845			# '*'s should not have spaces between.
4846			while ($to =~ s/\*\s+\*/\*\*/) {
4847			}
4848			# Modifiers should have spaces.
4849			$to =~ s/(\b$Modifier$)/$1 /;
4850
4851##			print "2: from<$from> to<$to> ident<$ident>\n";
4852			if ($from ne $to && $ident !~ /^$Modifier$/) {
4853				if (ERROR("POINTER_LOCATION",
4854					  "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4855				    $fix) {
4856
4857					my $sub_from = $match;
4858					my $sub_to = $match;
4859					$sub_to =~ s/\Q$from\E/$to/;
4860					$fixed[$fixlinenr] =~
4861					    s@\Q$sub_from\E@$sub_to@;
4862				}
4863			}
4864		}
4865
4866# do not use BUG() or variants
4867		if ($line =~ /\b(?!AA_|BUILD_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4868			my $msg_level = \&WARN;
4869			$msg_level = \&CHK if ($file);
4870			&{$msg_level}("AVOID_BUG",
4871				      "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);
4872		}
4873
4874# avoid LINUX_VERSION_CODE
4875		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4876			WARN("LINUX_VERSION_CODE",
4877			     "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4878		}
4879
4880# check for uses of printk_ratelimit
4881		if ($line =~ /\bprintk_ratelimit\s*\(/) {
4882			WARN("PRINTK_RATELIMITED",
4883			     "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4884		}
4885
4886# printk should use KERN_* levels
4887		if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4888			WARN("PRINTK_WITHOUT_KERN_LEVEL",
4889			     "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4890		}
4891
4892# prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4893		if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4894			my $printk = $1;
4895			my $modifier = $2;
4896			my $orig = $3;
4897			$modifier = "" if (!defined($modifier));
4898			my $level = lc($orig);
4899			$level = "warn" if ($level eq "warning");
4900			my $level2 = $level;
4901			$level2 = "dbg" if ($level eq "debug");
4902			$level .= $modifier;
4903			$level2 .= $modifier;
4904			WARN("PREFER_PR_LEVEL",
4905			     "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to $printk(KERN_$orig ...\n" . $herecurr);
4906		}
4907
4908# prefer dev_<level> to dev_printk(KERN_<LEVEL>
4909		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4910			my $orig = $1;
4911			my $level = lc($orig);
4912			$level = "warn" if ($level eq "warning");
4913			$level = "dbg" if ($level eq "debug");
4914			WARN("PREFER_DEV_LEVEL",
4915			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4916		}
4917
4918# trace_printk should not be used in production code.
4919		if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4920			WARN("TRACE_PRINTK",
4921			     "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4922		}
4923
4924# ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4925# number of false positives, but assembly files are not checked, so at
4926# least the arch entry code will not trigger this warning.
4927		if ($line =~ /\bENOSYS\b/) {
4928			WARN("ENOSYS",
4929			     "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4930		}
4931
4932# ENOTSUPP is not a standard error code and should be avoided in new patches.
4933# Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4934# Similarly to ENOSYS warning a small number of false positives is expected.
4935		if (!$file && $line =~ /\bENOTSUPP\b/) {
4936			if (WARN("ENOTSUPP",
4937				 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4938			    $fix) {
4939				$fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4940			}
4941		}
4942
4943# function brace can't be on same line, except for #defines of do while,
4944# or if closed on same line
4945		if ($perl_version_ok &&
4946		    $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4947		    $sline !~ /\#\s*define\b.*do\s*\{/ &&
4948		    $sline !~ /}/) {
4949			if (ERROR("OPEN_BRACE",
4950				  "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4951			    $fix) {
4952				fix_delete_line($fixlinenr, $rawline);
4953				my $fixed_line = $rawline;
4954				$fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4955				my $line1 = $1;
4956				my $line2 = $2;
4957				fix_insert_line($fixlinenr, ltrim($line1));
4958				fix_insert_line($fixlinenr, "\+{");
4959				if ($line2 !~ /^\s*$/) {
4960					fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4961				}
4962			}
4963		}
4964
4965# open braces for enum, union and struct go on the same line.
4966		if ($line =~ /^.\s*{/ &&
4967		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4968			if (ERROR("OPEN_BRACE",
4969				  "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4970			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4971				fix_delete_line($fixlinenr - 1, $prevrawline);
4972				fix_delete_line($fixlinenr, $rawline);
4973				my $fixedline = rtrim($prevrawline) . " {";
4974				fix_insert_line($fixlinenr, $fixedline);
4975				$fixedline = $rawline;
4976				$fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4977				if ($fixedline !~ /^\+\s*$/) {
4978					fix_insert_line($fixlinenr, $fixedline);
4979				}
4980			}
4981		}
4982
4983# missing space after union, struct or enum definition
4984		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4985			if (WARN("SPACING",
4986				 "missing space after $1 definition\n" . $herecurr) &&
4987			    $fix) {
4988				$fixed[$fixlinenr] =~
4989				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4990			}
4991		}
4992
4993# Function pointer declarations
4994# check spacing between type, funcptr, and args
4995# canonical declaration is "type (*funcptr)(args...)"
4996		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4997			my $declare = $1;
4998			my $pre_pointer_space = $2;
4999			my $post_pointer_space = $3;
5000			my $funcname = $4;
5001			my $post_funcname_space = $5;
5002			my $pre_args_space = $6;
5003
5004# the $Declare variable will capture all spaces after the type
5005# so check it for a missing trailing missing space but pointer return types
5006# don't need a space so don't warn for those.
5007			my $post_declare_space = "";
5008			if ($declare =~ /(\s+)$/) {
5009				$post_declare_space = $1;
5010				$declare = rtrim($declare);
5011			}
5012			if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
5013				WARN("SPACING",
5014				     "missing space after return type\n" . $herecurr);
5015				$post_declare_space = " ";
5016			}
5017
5018# unnecessary space "type  (*funcptr)(args...)"
5019# This test is not currently implemented because these declarations are
5020# equivalent to
5021#	int  foo(int bar, ...)
5022# and this is form shouldn't/doesn't generate a checkpatch warning.
5023#
5024#			elsif ($declare =~ /\s{2,}$/) {
5025#				WARN("SPACING",
5026#				     "Multiple spaces after return type\n" . $herecurr);
5027#			}
5028
5029# unnecessary space "type ( *funcptr)(args...)"
5030			if (defined $pre_pointer_space &&
5031			    $pre_pointer_space =~ /^\s/) {
5032				WARN("SPACING",
5033				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
5034			}
5035
5036# unnecessary space "type (* funcptr)(args...)"
5037			if (defined $post_pointer_space &&
5038			    $post_pointer_space =~ /^\s/) {
5039				WARN("SPACING",
5040				     "Unnecessary space before function pointer name\n" . $herecurr);
5041			}
5042
5043# unnecessary space "type (*funcptr )(args...)"
5044			if (defined $post_funcname_space &&
5045			    $post_funcname_space =~ /^\s/) {
5046				WARN("SPACING",
5047				     "Unnecessary space after function pointer name\n" . $herecurr);
5048			}
5049
5050# unnecessary space "type (*funcptr) (args...)"
5051			if (defined $pre_args_space &&
5052			    $pre_args_space =~ /^\s/) {
5053				WARN("SPACING",
5054				     "Unnecessary space before function pointer arguments\n" . $herecurr);
5055			}
5056
5057			if (show_type("SPACING") && $fix) {
5058				$fixed[$fixlinenr] =~
5059				    s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5060			}
5061		}
5062
5063# check for spacing round square brackets; allowed:
5064#  1. with a type on the left -- int [] a;
5065#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5066#  3. inside a curly brace -- = { [0...10] = 5 }
5067		while ($line =~ /(.*?\s)\[/g) {
5068			my ($where, $prefix) = ($-[1], $1);
5069			if ($prefix !~ /$Type\s+$/ &&
5070			    ($where != 0 || $prefix !~ /^.\s+$/) &&
5071			    $prefix !~ /[{,:]\s+$/) {
5072				if (ERROR("BRACKET_SPACE",
5073					  "space prohibited before open square bracket '['\n" . $herecurr) &&
5074				    $fix) {
5075				    $fixed[$fixlinenr] =~
5076					s/^(\+.*?)\s+\[/$1\[/;
5077				}
5078			}
5079		}
5080
5081# check for spaces between functions and their parentheses.
5082		while ($line =~ /($Ident)\s+\(/g) {
5083			my $name = $1;
5084			my $ctx_before = substr($line, 0, $-[1]);
5085			my $ctx = "$ctx_before$name";
5086
5087			# Ignore those directives where spaces _are_ permitted.
5088			if ($name =~ /^(?:
5089				if|for|while|switch|return|case|
5090				volatile|__volatile__|
5091				__attribute__|format|__extension__|
5092				asm|__asm__|scoped_guard)$/x)
5093			{
5094			# cpp #define statements have non-optional spaces, ie
5095			# if there is a space between the name and the open
5096			# parenthesis it is simply not a parameter group.
5097			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5098
5099			# cpp #elif statement condition may start with a (
5100			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5101
5102			# If this whole things ends with a type its most
5103			# likely a typedef for a function.
5104			} elsif ($ctx =~ /$Type$/) {
5105
5106			} else {
5107				if (WARN("SPACING",
5108					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5109					     $fix) {
5110					$fixed[$fixlinenr] =~
5111					    s/\b$name\s+\(/$name\(/;
5112				}
5113			}
5114		}
5115
5116# Check operator spacing.
5117		if (!($line=~/\#\s*include/)) {
5118			my $fixed_line = "";
5119			my $line_fixed = 0;
5120
5121			my $ops = qr{
5122				<<=|>>=|<=|>=|==|!=|
5123				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5124				=>|->|<<|>>|<|>|=|!|~|
5125				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5126				\?:|\?|:
5127			}x;
5128			my @elements = split(/($ops|;)/, $opline);
5129
5130##			print("element count: <" . $#elements . ">\n");
5131##			foreach my $el (@elements) {
5132##				print("el: <$el>\n");
5133##			}
5134
5135			my @fix_elements = ();
5136			my $off = 0;
5137
5138			foreach my $el (@elements) {
5139				push(@fix_elements, substr($rawline, $off, length($el)));
5140				$off += length($el);
5141			}
5142
5143			$off = 0;
5144
5145			my $blank = copy_spacing($opline);
5146			my $last_after = -1;
5147
5148			for (my $n = 0; $n < $#elements; $n += 2) {
5149
5150				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5151
5152##				print("n: <$n> good: <$good>\n");
5153
5154				$off += length($elements[$n]);
5155
5156				# Pick up the preceding and succeeding characters.
5157				my $ca = substr($opline, 0, $off);
5158				my $cc = '';
5159				if (length($opline) >= ($off + length($elements[$n + 1]))) {
5160					$cc = substr($opline, $off + length($elements[$n + 1]));
5161				}
5162				my $cb = "$ca$;$cc";
5163
5164				my $a = '';
5165				$a = 'V' if ($elements[$n] ne '');
5166				$a = 'W' if ($elements[$n] =~ /\s$/);
5167				$a = 'C' if ($elements[$n] =~ /$;$/);
5168				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5169				$a = 'O' if ($elements[$n] eq '');
5170				$a = 'E' if ($ca =~ /^\s*$/);
5171
5172				my $op = $elements[$n + 1];
5173
5174				my $c = '';
5175				if (defined $elements[$n + 2]) {
5176					$c = 'V' if ($elements[$n + 2] ne '');
5177					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
5178					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
5179					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5180					$c = 'O' if ($elements[$n + 2] eq '');
5181					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5182				} else {
5183					$c = 'E';
5184				}
5185
5186				my $ctx = "${a}x${c}";
5187
5188				my $at = "(ctx:$ctx)";
5189
5190				my $ptr = substr($blank, 0, $off) . "^";
5191				my $hereptr = "$hereline$ptr\n";
5192
5193				# Pull out the value of this operator.
5194				my $op_type = substr($curr_values, $off + 1, 1);
5195
5196				# Get the full operator variant.
5197				my $opv = $op . substr($curr_vars, $off, 1);
5198
5199				# Ignore operators passed as parameters.
5200				if ($op_type ne 'V' &&
5201				    $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5202
5203#				# Ignore comments
5204#				} elsif ($op =~ /^$;+$/) {
5205
5206				# ; should have either the end of line or a space or \ after it
5207				} elsif ($op eq ';') {
5208					if ($ctx !~ /.x[WEBC]/ &&
5209					    $cc !~ /^\\/ && $cc !~ /^;/) {
5210						if (ERROR("SPACING",
5211							  "space required after that '$op' $at\n" . $hereptr)) {
5212							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5213							$line_fixed = 1;
5214						}
5215					}
5216
5217				# // is a comment
5218				} elsif ($op eq '//') {
5219
5220				#   :   when part of a bitfield
5221				} elsif ($opv eq ':B') {
5222					# skip the bitfield test for now
5223
5224				# No spaces for:
5225				#   ->
5226				} elsif ($op eq '->') {
5227					if ($ctx =~ /Wx.|.xW/) {
5228						if (ERROR("SPACING",
5229							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5230							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5231							if (defined $fix_elements[$n + 2]) {
5232								$fix_elements[$n + 2] =~ s/^\s+//;
5233							}
5234							$line_fixed = 1;
5235						}
5236					}
5237
5238				# , must not have a space before and must have a space on the right.
5239				} elsif ($op eq ',') {
5240					my $rtrim_before = 0;
5241					my $space_after = 0;
5242					if ($ctx =~ /Wx./) {
5243						if (ERROR("SPACING",
5244							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5245							$line_fixed = 1;
5246							$rtrim_before = 1;
5247						}
5248					}
5249					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5250						if (ERROR("SPACING",
5251							  "space required after that '$op' $at\n" . $hereptr)) {
5252							$line_fixed = 1;
5253							$last_after = $n;
5254							$space_after = 1;
5255						}
5256					}
5257					if ($rtrim_before || $space_after) {
5258						if ($rtrim_before) {
5259							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5260						} else {
5261							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5262						}
5263						if ($space_after) {
5264							$good .= " ";
5265						}
5266					}
5267
5268				# '*' as part of a type definition -- reported already.
5269				} elsif ($opv eq '*_') {
5270					#warn "'*' is part of type\n";
5271
5272				# unary operators should have a space before and
5273				# none after.  May be left adjacent to another
5274				# unary operator, or a cast
5275				} elsif ($op eq '!' || $op eq '~' ||
5276					 $opv eq '*U' || $opv eq '-U' ||
5277					 $opv eq '&U' || $opv eq '&&U') {
5278					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5279						if (ERROR("SPACING",
5280							  "space required before that '$op' $at\n" . $hereptr)) {
5281							if ($n != $last_after + 2) {
5282								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5283								$line_fixed = 1;
5284							}
5285						}
5286					}
5287					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5288						# A unary '*' may be const
5289
5290					} elsif ($ctx =~ /.xW/) {
5291						if (ERROR("SPACING",
5292							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5293							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5294							if (defined $fix_elements[$n + 2]) {
5295								$fix_elements[$n + 2] =~ s/^\s+//;
5296							}
5297							$line_fixed = 1;
5298						}
5299					}
5300
5301				# unary ++ and unary -- are allowed no space on one side.
5302				} elsif ($op eq '++' or $op eq '--') {
5303					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5304						if (ERROR("SPACING",
5305							  "space required one side of that '$op' $at\n" . $hereptr)) {
5306							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5307							$line_fixed = 1;
5308						}
5309					}
5310					if ($ctx =~ /Wx[BE]/ ||
5311					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5312						if (ERROR("SPACING",
5313							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5314							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5315							$line_fixed = 1;
5316						}
5317					}
5318					if ($ctx =~ /ExW/) {
5319						if (ERROR("SPACING",
5320							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5321							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5322							if (defined $fix_elements[$n + 2]) {
5323								$fix_elements[$n + 2] =~ s/^\s+//;
5324							}
5325							$line_fixed = 1;
5326						}
5327					}
5328
5329				# << and >> may either have or not have spaces both sides
5330				} elsif ($op eq '<<' or $op eq '>>' or
5331					 $op eq '&' or $op eq '^' or $op eq '|' or
5332					 $op eq '+' or $op eq '-' or
5333					 $op eq '*' or $op eq '/' or
5334					 $op eq '%')
5335				{
5336					if ($check) {
5337						if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5338							if (CHK("SPACING",
5339								"spaces preferred around that '$op' $at\n" . $hereptr)) {
5340								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5341								$fix_elements[$n + 2] =~ s/^\s+//;
5342								$line_fixed = 1;
5343							}
5344						} elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5345							if (CHK("SPACING",
5346								"space preferred before that '$op' $at\n" . $hereptr)) {
5347								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5348								$line_fixed = 1;
5349							}
5350						}
5351					} elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5352						if (ERROR("SPACING",
5353							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
5354							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5355							if (defined $fix_elements[$n + 2]) {
5356								$fix_elements[$n + 2] =~ s/^\s+//;
5357							}
5358							$line_fixed = 1;
5359						}
5360					}
5361
5362				# A colon needs no spaces before when it is
5363				# terminating a case value or a label.
5364				} elsif ($opv eq ':C' || $opv eq ':L') {
5365					if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5366						if (ERROR("SPACING",
5367							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5368							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5369							$line_fixed = 1;
5370						}
5371					}
5372
5373				# All the others need spaces both sides.
5374				} elsif ($ctx !~ /[EWC]x[CWE]/) {
5375					my $ok = 0;
5376
5377					# Ignore email addresses <foo@bar>
5378					if (($op eq '<' &&
5379					     $cc =~ /^\S+\@\S+>/) ||
5380					    ($op eq '>' &&
5381					     $ca =~ /<\S+\@\S+$/))
5382					{
5383						$ok = 1;
5384					}
5385
5386					# for asm volatile statements
5387					# ignore a colon with another
5388					# colon immediately before or after
5389					if (($op eq ':') &&
5390					    ($ca =~ /:$/ || $cc =~ /^:/)) {
5391						$ok = 1;
5392					}
5393
5394					# messages are ERROR, but ?: are CHK
5395					if ($ok == 0) {
5396						my $msg_level = \&ERROR;
5397						$msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5398
5399						if (&{$msg_level}("SPACING",
5400								  "spaces required around that '$op' $at\n" . $hereptr)) {
5401							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5402							if (defined $fix_elements[$n + 2]) {
5403								$fix_elements[$n + 2] =~ s/^\s+//;
5404							}
5405							$line_fixed = 1;
5406						}
5407					}
5408				}
5409				$off += length($elements[$n + 1]);
5410
5411##				print("n: <$n> GOOD: <$good>\n");
5412
5413				$fixed_line = $fixed_line . $good;
5414			}
5415
5416			if (($#elements % 2) == 0) {
5417				$fixed_line = $fixed_line . $fix_elements[$#elements];
5418			}
5419
5420			if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5421				$fixed[$fixlinenr] = $fixed_line;
5422			}
5423
5424
5425		}
5426
5427# check for whitespace before a non-naked semicolon
5428		if ($line =~ /^\+.*\S\s+;\s*$/) {
5429			if (WARN("SPACING",
5430				 "space prohibited before semicolon\n" . $herecurr) &&
5431			    $fix) {
5432				1 while $fixed[$fixlinenr] =~
5433				    s/^(\+.*\S)\s+;/$1;/;
5434			}
5435		}
5436
5437# check for multiple assignments
5438		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5439			CHK("MULTIPLE_ASSIGNMENTS",
5440			    "multiple assignments should be avoided\n" . $herecurr);
5441		}
5442
5443## # check for multiple declarations, allowing for a function declaration
5444## # continuation.
5445## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5446## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5447##
5448## 			# Remove any bracketed sections to ensure we do not
5449## 			# falsely report the parameters of functions.
5450## 			my $ln = $line;
5451## 			while ($ln =~ s/\([^\(\)]*\)//g) {
5452## 			}
5453## 			if ($ln =~ /,/) {
5454## 				WARN("MULTIPLE_DECLARATION",
5455##				     "declaring multiple variables together should be avoided\n" . $herecurr);
5456## 			}
5457## 		}
5458
5459#need space before brace following if, while, etc
5460		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5461		    $line =~ /\b(?:else|do)\{/) {
5462			if (ERROR("SPACING",
5463				  "space required before the open brace '{'\n" . $herecurr) &&
5464			    $fix) {
5465				$fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5466			}
5467		}
5468
5469## # check for blank lines before declarations
5470##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5471##		    $prevrawline =~ /^.\s*$/) {
5472##			WARN("SPACING",
5473##			     "No blank lines before declarations\n" . $hereprev);
5474##		}
5475##
5476
5477# closing brace should have a space following it when it has anything
5478# on the line
5479		if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5480			if (ERROR("SPACING",
5481				  "space required after that close brace '}'\n" . $herecurr) &&
5482			    $fix) {
5483				$fixed[$fixlinenr] =~
5484				    s/}((?!(?:,|;|\)))\S)/} $1/;
5485			}
5486		}
5487
5488# check spacing on square brackets
5489		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5490			if (ERROR("SPACING",
5491				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
5492			    $fix) {
5493				$fixed[$fixlinenr] =~
5494				    s/\[\s+/\[/;
5495			}
5496		}
5497		if ($line =~ /\s\]/) {
5498			if (ERROR("SPACING",
5499				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5500			    $fix) {
5501				$fixed[$fixlinenr] =~
5502				    s/\s+\]/\]/;
5503			}
5504		}
5505
5506# check spacing on parentheses
5507		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5508		    $line !~ /for\s*\(\s+;/) {
5509			if (ERROR("SPACING",
5510				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5511			    $fix) {
5512				$fixed[$fixlinenr] =~
5513				    s/\(\s+/\(/;
5514			}
5515		}
5516		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5517		    $line !~ /for\s*\(.*;\s+\)/ &&
5518		    $line !~ /:\s+\)/) {
5519			if (ERROR("SPACING",
5520				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5521			    $fix) {
5522				$fixed[$fixlinenr] =~
5523				    s/\s+\)/\)/;
5524			}
5525		}
5526
5527# check unnecessary parentheses around addressof/dereference single $Lvals
5528# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5529
5530		while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5531			my $var = $1;
5532			if (CHK("UNNECESSARY_PARENTHESES",
5533				"Unnecessary parentheses around $var\n" . $herecurr) &&
5534			    $fix) {
5535				$fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5536			}
5537		}
5538
5539# check for unnecessary parentheses around function pointer uses
5540# ie: (foo->bar)(); should be foo->bar();
5541# but not "if (foo->bar) (" to avoid some false positives
5542		if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5543			my $var = $2;
5544			if (CHK("UNNECESSARY_PARENTHESES",
5545				"Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5546			    $fix) {
5547				my $var2 = deparenthesize($var);
5548				$var2 =~ s/\s//g;
5549				$fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5550			}
5551		}
5552
5553# check for unnecessary parentheses around comparisons
5554# except in drivers/staging
5555		if (($realfile !~ m@^(?:drivers/staging/)@) &&
5556		    $perl_version_ok && defined($stat) &&
5557		    $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5558			my $if_stat = $1;
5559			my $test = substr($2, 1, -1);
5560			my $herectx;
5561			while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5562				my $match = $1;
5563				# avoid parentheses around potential macro args
5564				next if ($match =~ /^\s*\w+\s*$/);
5565				if (!defined($herectx)) {
5566					$herectx = $here . "\n";
5567					my $cnt = statement_rawlines($if_stat);
5568					for (my $n = 0; $n < $cnt; $n++) {
5569						my $rl = raw_line($linenr, $n);
5570						$herectx .=  $rl . "\n";
5571						last if $rl =~ /^[ \+].*\{/;
5572					}
5573				}
5574				CHK("UNNECESSARY_PARENTHESES",
5575				    "Unnecessary parentheses around '$match'\n" . $herectx);
5576			}
5577		}
5578
5579# check that goto labels aren't indented (allow a single space indentation)
5580# and ignore bitfield definitions like foo:1
5581# Strictly, labels can have whitespace after the identifier and before the :
5582# but this is not allowed here as many ?: uses would appear to be labels
5583		if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5584		    $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5585		    $sline !~ /^.\s+default:/) {
5586			if (WARN("INDENTED_LABEL",
5587				 "labels should not be indented\n" . $herecurr) &&
5588			    $fix) {
5589				$fixed[$fixlinenr] =~
5590				    s/^(.)\s+/$1/;
5591			}
5592		}
5593
5594# check if a statement with a comma should be two statements like:
5595#	foo = bar(),	/* comma should be semicolon */
5596#	bar = baz();
5597		if (defined($stat) &&
5598		    $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5599			my $cnt = statement_rawlines($stat);
5600			my $herectx = get_stat_here($linenr, $cnt, $here);
5601			WARN("SUSPECT_COMMA_SEMICOLON",
5602			     "Possible comma where semicolon could be used\n" . $herectx);
5603		}
5604
5605# return is not a function
5606		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5607			my $spacing = $1;
5608			if ($perl_version_ok &&
5609			    $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5610				my $value = $1;
5611				$value = deparenthesize($value);
5612				if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5613					ERROR("RETURN_PARENTHESES",
5614					      "return is not a function, parentheses are not required\n" . $herecurr);
5615				}
5616			} elsif ($spacing !~ /\s+/) {
5617				ERROR("SPACING",
5618				      "space required before the open parenthesis '('\n" . $herecurr);
5619			}
5620		}
5621
5622# unnecessary return in a void function
5623# at end-of-function, with the previous line a single leading tab, then return;
5624# and the line before that not a goto label target like "out:"
5625		if ($sline =~ /^[ \+]}\s*$/ &&
5626		    $prevline =~ /^\+\treturn\s*;\s*$/ &&
5627		    $linenr >= 3 &&
5628		    $lines[$linenr - 3] =~ /^[ +]/ &&
5629		    $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5630			WARN("RETURN_VOID",
5631			     "void function return statements are not generally useful\n" . $hereprev);
5632		}
5633
5634# if statements using unnecessary parentheses - ie: if ((foo == bar))
5635		if ($perl_version_ok &&
5636		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
5637			my $openparens = $1;
5638			my $count = $openparens =~ tr@\(@\(@;
5639			my $msg = "";
5640			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5641				my $comp = $4;	#Not $1 because of $LvalOrFunc
5642				$msg = " - maybe == should be = ?" if ($comp eq "==");
5643				WARN("UNNECESSARY_PARENTHESES",
5644				     "Unnecessary parentheses$msg\n" . $herecurr);
5645			}
5646		}
5647
5648# comparisons with a constant or upper case identifier on the left
5649#	avoid cases like "foo + BAR < baz"
5650#	only fix matches surrounded by parentheses to avoid incorrect
5651#	conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5652		if ($perl_version_ok &&
5653		    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5654			my $lead = $1;
5655			my $const = $2;
5656			my $comp = $3;
5657			my $to = $4;
5658			my $newcomp = $comp;
5659			if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5660			    $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5661			    WARN("CONSTANT_COMPARISON",
5662				 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5663			    $fix) {
5664				if ($comp eq "<") {
5665					$newcomp = ">";
5666				} elsif ($comp eq "<=") {
5667					$newcomp = ">=";
5668				} elsif ($comp eq ">") {
5669					$newcomp = "<";
5670				} elsif ($comp eq ">=") {
5671					$newcomp = "<=";
5672				}
5673				$fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5674			}
5675		}
5676
5677# Return of what appears to be an errno should normally be negative
5678		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5679			my $name = $1;
5680			if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5681				WARN("USE_NEGATIVE_ERRNO",
5682				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5683			}
5684		}
5685
5686# Need a space before open parenthesis after if, while etc
5687		if ($line =~ /\b(if|while|for|switch)\(/) {
5688			if (ERROR("SPACING",
5689				  "space required before the open parenthesis '('\n" . $herecurr) &&
5690			    $fix) {
5691				$fixed[$fixlinenr] =~
5692				    s/\b(if|while|for|switch)\(/$1 \(/;
5693			}
5694		}
5695
5696# Check for illegal assignment in if conditional -- and check for trailing
5697# statements after the conditional.
5698		if ($line =~ /do\s*(?!{)/) {
5699			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5700				ctx_statement_block($linenr, $realcnt, 0)
5701					if (!defined $stat);
5702			my ($stat_next) = ctx_statement_block($line_nr_next,
5703						$remain_next, $off_next);
5704			$stat_next =~ s/\n./\n /g;
5705			##print "stat<$stat> stat_next<$stat_next>\n";
5706
5707			if ($stat_next =~ /^\s*while\b/) {
5708				# If the statement carries leading newlines,
5709				# then count those as offsets.
5710				my ($whitespace) =
5711					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5712				my $offset =
5713					statement_rawlines($whitespace) - 1;
5714
5715				$suppress_whiletrailers{$line_nr_next +
5716								$offset} = 1;
5717			}
5718		}
5719		if (!defined $suppress_whiletrailers{$linenr} &&
5720		    defined($stat) && defined($cond) &&
5721		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5722			my ($s, $c) = ($stat, $cond);
5723			my $fixed_assign_in_if = 0;
5724
5725			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5726				if (ERROR("ASSIGN_IN_IF",
5727					  "do not use assignment in if condition\n" . $herecurr) &&
5728				    $fix && $perl_version_ok) {
5729					if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5730						my $space = $1;
5731						my $not = $2;
5732						my $statement = $3;
5733						my $assigned = $4;
5734						my $test = $8;
5735						my $against = $9;
5736						my $brace = $15;
5737						fix_delete_line($fixlinenr, $rawline);
5738						fix_insert_line($fixlinenr, "$space$statement;");
5739						my $newline = "${space}if (";
5740						$newline .= '!' if defined($not);
5741						$newline .= '(' if (defined $not && defined($test) && defined($against));
5742						$newline .= "$assigned";
5743						$newline .= " $test $against" if (defined($test) && defined($against));
5744						$newline .= ')' if (defined $not && defined($test) && defined($against));
5745						$newline .= ')';
5746						$newline .= " {" if (defined($brace));
5747						fix_insert_line($fixlinenr + 1, $newline);
5748						$fixed_assign_in_if = 1;
5749					}
5750				}
5751			}
5752
5753			# Find out what is on the end of the line after the
5754			# conditional.
5755			substr($s, 0, length($c), '');
5756			$s =~ s/\n.*//g;
5757			$s =~ s/$;//g;	# Remove any comments
5758			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5759			    $c !~ /}\s*while\s*/)
5760			{
5761				# Find out how long the conditional actually is.
5762				my @newlines = ($c =~ /\n/gs);
5763				my $cond_lines = 1 + $#newlines;
5764				my $stat_real = '';
5765
5766				$stat_real = raw_line($linenr, $cond_lines)
5767							. "\n" if ($cond_lines);
5768				if (defined($stat_real) && $cond_lines > 1) {
5769					$stat_real = "[...]\n$stat_real";
5770				}
5771
5772				if (ERROR("TRAILING_STATEMENTS",
5773					  "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5774				    !$fixed_assign_in_if &&
5775				    $cond_lines == 0 &&
5776				    $fix && $perl_version_ok &&
5777				    $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5778					my $indent = $1;
5779					my $test = $2;
5780					my $rest = rtrim($4);
5781					if ($rest =~ /;$/) {
5782						$fixed[$fixlinenr] = "\+$indent$test";
5783						fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5784					}
5785				}
5786			}
5787		}
5788
5789# Check for bitwise tests written as boolean
5790		if ($line =~ /
5791			(?:
5792				(?:\[|\(|\&\&|\|\|)
5793				\s*0[xX][0-9]+\s*
5794				(?:\&\&|\|\|)
5795			|
5796				(?:\&\&|\|\|)
5797				\s*0[xX][0-9]+\s*
5798				(?:\&\&|\|\||\)|\])
5799			)/x)
5800		{
5801			WARN("HEXADECIMAL_BOOLEAN_TEST",
5802			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5803		}
5804
5805# if and else should not have general statements after it
5806		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5807			my $s = $1;
5808			$s =~ s/$;//g;	# Remove any comments
5809			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5810				ERROR("TRAILING_STATEMENTS",
5811				      "trailing statements should be on next line\n" . $herecurr);
5812			}
5813		}
5814# if should not continue a brace
5815		if ($line =~ /}\s*if\b/) {
5816			ERROR("TRAILING_STATEMENTS",
5817			      "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5818				$herecurr);
5819		}
5820# case and default should not have general statements after them
5821		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5822		    $line !~ /\G(?:
5823			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5824			\s*return\s+
5825		    )/xg)
5826		{
5827			ERROR("TRAILING_STATEMENTS",
5828			      "trailing statements should be on next line\n" . $herecurr);
5829		}
5830
5831		# Check for }<nl>else {, these must be at the same
5832		# indent level to be relevant to each other.
5833		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5834		    $previndent == $indent) {
5835			if (ERROR("ELSE_AFTER_BRACE",
5836				  "else should follow close brace '}'\n" . $hereprev) &&
5837			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5838				fix_delete_line($fixlinenr - 1, $prevrawline);
5839				fix_delete_line($fixlinenr, $rawline);
5840				my $fixedline = $prevrawline;
5841				$fixedline =~ s/}\s*$//;
5842				if ($fixedline !~ /^\+\s*$/) {
5843					fix_insert_line($fixlinenr, $fixedline);
5844				}
5845				$fixedline = $rawline;
5846				$fixedline =~ s/^(.\s*)else/$1} else/;
5847				fix_insert_line($fixlinenr, $fixedline);
5848			}
5849		}
5850
5851		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5852		    $previndent == $indent) {
5853			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5854
5855			# Find out what is on the end of the line after the
5856			# conditional.
5857			substr($s, 0, length($c), '');
5858			$s =~ s/\n.*//g;
5859
5860			if ($s =~ /^\s*;/) {
5861				if (ERROR("WHILE_AFTER_BRACE",
5862					  "while should follow close brace '}'\n" . $hereprev) &&
5863				    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5864					fix_delete_line($fixlinenr - 1, $prevrawline);
5865					fix_delete_line($fixlinenr, $rawline);
5866					my $fixedline = $prevrawline;
5867					my $trailing = $rawline;
5868					$trailing =~ s/^\+//;
5869					$trailing = trim($trailing);
5870					$fixedline =~ s/}\s*$/} $trailing/;
5871					fix_insert_line($fixlinenr, $fixedline);
5872				}
5873			}
5874		}
5875
5876#Specific variable tests
5877		while ($line =~ m{($Constant|$Lval)}g) {
5878			my $var = $1;
5879
5880#CamelCase
5881			if ($var !~ /^$Constant$/ &&
5882			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5883#Ignore C keywords
5884			    $var !~ /^_Generic$/ &&
5885#Ignore some autogenerated defines and enum values
5886			    $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5887#Ignore Page<foo> variants
5888			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5889#Ignore ETHTOOL_LINK_MODE_<foo> variants
5890			    $var !~ /^ETHTOOL_LINK_MODE_/ &&
5891#Ignore SI style variants like nS, mV and dB
5892#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5893			    $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5894#Ignore some three character SI units explicitly, like MiB and KHz
5895			    $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5896				while ($var =~ m{\b($Ident)}g) {
5897					my $word = $1;
5898					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5899					if ($check) {
5900						seed_camelcase_includes();
5901						if (!$file && !$camelcase_file_seeded) {
5902							seed_camelcase_file($realfile);
5903							$camelcase_file_seeded = 1;
5904						}
5905					}
5906					if (!defined $camelcase{$word}) {
5907						$camelcase{$word} = 1;
5908						CHK("CAMELCASE",
5909						    "Avoid CamelCase: <$word>\n" . $herecurr);
5910					}
5911				}
5912			}
5913		}
5914
5915#no spaces allowed after \ in define
5916		if ($line =~ /\#\s*define.*\\\s+$/) {
5917			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5918				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5919			    $fix) {
5920				$fixed[$fixlinenr] =~ s/\s+$//;
5921			}
5922		}
5923
5924# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5925# itself <asm/foo.h> (uses RAW line)
5926		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5927			my $file = "$1.h";
5928			my $checkfile = "include/linux/$file";
5929			if (-f "$root/$checkfile" &&
5930			    $realfile ne $checkfile &&
5931			    $1 !~ /$allowed_asm_includes/)
5932			{
5933				my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5934				if ($asminclude > 0) {
5935					if ($realfile =~ m{^arch/}) {
5936						CHK("ARCH_INCLUDE_LINUX",
5937						    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5938					} else {
5939						WARN("INCLUDE_LINUX",
5940						     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5941					}
5942				}
5943			}
5944		}
5945
5946# Usually multi-statement macros should be enclosed in a do {} while
5947# (0) loop.  Grab the first statement and ensure its the whole macro
5948# if its not enclosed in a known good container
5949		if ($realfile !~ m@/vmlinux.lds.h$@ &&
5950		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5951			my $ln = $linenr;
5952			my $cnt = $realcnt;
5953			my ($off, $dstat, $dcond, $rest);
5954			my $ctx = '';
5955			my $has_flow_statement = 0;
5956			my $has_arg_concat = 0;
5957			($dstat, $dcond, $ln, $cnt, $off) =
5958				ctx_statement_block($linenr, $realcnt, 0);
5959			$ctx = $dstat;
5960			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5961			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5962
5963			$has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5964			$has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5965
5966			$dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5967			my $define_args = $1;
5968			my $define_stmt = $dstat;
5969			my @def_args = ();
5970
5971			if (defined $define_args && $define_args ne "") {
5972				$define_args = substr($define_args, 1, length($define_args) - 2);
5973				$define_args =~ s/\s*//g;
5974				$define_args =~ s/\\\+?//g;
5975				@def_args = split(",", $define_args);
5976			}
5977
5978			$dstat =~ s/$;//g;
5979			$dstat =~ s/\\\n.//g;
5980			$dstat =~ s/^\s*//s;
5981			$dstat =~ s/\s*$//s;
5982
5983			# Flatten any parentheses and braces
5984			while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5985			       $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5986			       $dstat =~ s/.\[[^\[\]]*\]/1u/)
5987			{
5988			}
5989
5990			# Flatten any obvious string concatenation.
5991			while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5992			       $dstat =~ s/$Ident\s*($String)/$1/)
5993			{
5994			}
5995
5996			# Make asm volatile uses seem like a generic function
5997			$dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5998
5999			my $exceptions = qr{
6000				$Declare|
6001				# named exceptions
6002				module_param_named|
6003				MODULE_PARM_DESC|
6004				DECLARE_PER_CPU|
6005				DEFINE_PER_CPU|
6006				static_assert|
6007				# declaration primitives
6008				__typeof__\(|
6009				union|
6010				struct|
6011				\.$Ident\s*=\s*|
6012				^\"|\"$|
6013				^\[
6014			}x;
6015			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
6016
6017			$ctx =~ s/\n*$//;
6018			my $stmt_cnt = statement_rawlines($ctx);
6019			my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
6020
6021			if ($dstat ne '' &&
6022			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
6023			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
6024			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
6025			    $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&			# character constants
6026			    $dstat !~ /$exceptions/ &&
6027			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
6028			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
6029			    $dstat !~ /^case\b/ &&					# case ...
6030			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
6031			    $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ &&		# while (...) {...}
6032			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
6033			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
6034			    $dstat !~ /^do\s*{/ &&					# do {...
6035			    $dstat !~ /^\(\{/ &&						# ({...
6036			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
6037			{
6038				if ($dstat =~ /^\s*if\b/) {
6039					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6040					      "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
6041				} elsif ($dstat =~ /;/) {
6042					WARN("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6043					      "Non-declarative macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6044				} else {
6045					ERROR("COMPLEX_MACRO",
6046					      "Macros with complex values should be enclosed in parentheses\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6047				}
6048
6049			}
6050
6051			# Make $define_stmt single line, comment-free, etc
6052			my @stmt_array = split('\n', $define_stmt);
6053			my $first = 1;
6054			$define_stmt = "";
6055			foreach my $l (@stmt_array) {
6056				$l =~ s/\\$//;
6057				if ($first) {
6058					$define_stmt = $l;
6059					$first = 0;
6060				} elsif ($l =~ /^[\+ ]/) {
6061					$define_stmt .= substr($l, 1);
6062				}
6063			}
6064			$define_stmt =~ s/$;//g;
6065			$define_stmt =~ s/\s+/ /g;
6066			$define_stmt = trim($define_stmt);
6067
6068# check if any macro arguments are reused (ignore '...' and 'type')
6069			foreach my $arg (@def_args) {
6070			        next if ($arg =~ /\.\.\./);
6071			        next if ($arg =~ /^type$/i);
6072				my $tmp_stmt = $define_stmt;
6073				$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;
6074				$tmp_stmt =~ s/\#+\s*$arg\b//g;
6075				$tmp_stmt =~ s/\b$arg\s*\#\#//g;
6076				my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6077				if ($use_cnt > 1) {
6078					CHK("MACRO_ARG_REUSE",
6079					    "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6080				    }
6081# check if any macro arguments may have other precedence issues
6082				if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6083				    ((defined($1) && $1 ne ',') ||
6084				     (defined($2) && $2 ne ','))) {
6085					CHK("MACRO_ARG_PRECEDENCE",
6086					    "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6087				}
6088
6089# check if this is an unused argument
6090				if ($define_stmt !~ /\b$arg\b/ && $define_stmt) {
6091					WARN("MACRO_ARG_UNUSED",
6092					     "Argument '$arg' is not used in function-like macro\n" . "$herectx");
6093				}
6094			}
6095
6096# check for macros with flow control, but without ## concatenation
6097# ## concatenation is commonly a macro that defines a function so ignore those
6098			if ($has_flow_statement && !$has_arg_concat) {
6099				my $cnt = statement_rawlines($ctx);
6100				my $herectx = get_stat_here($linenr, $cnt, $here);
6101
6102				WARN("MACRO_WITH_FLOW_CONTROL",
6103				     "Macros with flow control statements should be avoided\n" . "$herectx");
6104			}
6105
6106# check for line continuations outside of #defines, preprocessor #, and asm
6107
6108		} elsif ($realfile =~ m@/vmlinux.lds.h$@) {
6109		    $line =~ s/(\w+)/$maybe_linker_symbol{$1}++/ge;
6110		    #print "REAL: $realfile\nln: $line\nkeys:", sort keys %maybe_linker_symbol;
6111		} else {
6112			if ($prevline !~ /^..*\\$/ &&
6113			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
6114			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
6115			    $line =~ /^\+.*\\$/) {
6116				WARN("LINE_CONTINUATIONS",
6117				     "Avoid unnecessary line continuations\n" . $herecurr);
6118			}
6119		}
6120
6121# do {} while (0) macro tests:
6122# single-statement macros do not need to be enclosed in do while (0) loop,
6123# macro should not end with a semicolon
6124		if ($perl_version_ok &&
6125		    $realfile !~ m@/vmlinux.lds.h$@ &&
6126		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6127			my $ln = $linenr;
6128			my $cnt = $realcnt;
6129			my ($off, $dstat, $dcond, $rest);
6130			my $ctx = '';
6131			($dstat, $dcond, $ln, $cnt, $off) =
6132				ctx_statement_block($linenr, $realcnt, 0);
6133			$ctx = $dstat;
6134
6135			$dstat =~ s/\\\n.//g;
6136			$dstat =~ s/$;/ /g;
6137
6138			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6139				my $stmts = $2;
6140				my $semis = $3;
6141
6142				$ctx =~ s/\n*$//;
6143				my $cnt = statement_rawlines($ctx);
6144				my $herectx = get_stat_here($linenr, $cnt, $here);
6145
6146				if (($stmts =~ tr/;/;/) == 1 &&
6147				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
6148					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6149					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6150				}
6151				if (defined $semis && $semis ne "") {
6152					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6153					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6154				}
6155			} elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6156				$ctx =~ s/\n*$//;
6157				my $cnt = statement_rawlines($ctx);
6158				my $herectx = get_stat_here($linenr, $cnt, $here);
6159
6160				WARN("TRAILING_SEMICOLON",
6161				     "macros should not use a trailing semicolon\n" . "$herectx");
6162			}
6163		}
6164
6165# check for redundant bracing round if etc
6166		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6167			my ($level, $endln, @chunks) =
6168				ctx_statement_full($linenr, $realcnt, 1);
6169			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6170			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6171			if ($#chunks > 0 && $level == 0) {
6172				my @allowed = ();
6173				my $allow = 0;
6174				my $seen = 0;
6175				my $herectx = $here . "\n";
6176				my $ln = $linenr - 1;
6177				for my $chunk (@chunks) {
6178					my ($cond, $block) = @{$chunk};
6179
6180					# If the condition carries leading newlines, then count those as offsets.
6181					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6182					my $offset = statement_rawlines($whitespace) - 1;
6183
6184					$allowed[$allow] = 0;
6185					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6186
6187					# We have looked at and allowed this specific line.
6188					$suppress_ifbraces{$ln + $offset} = 1;
6189
6190					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6191					$ln += statement_rawlines($block) - 1;
6192
6193					substr($block, 0, length($cond), '');
6194
6195					$seen++ if ($block =~ /^\s*{/);
6196
6197					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6198					if (statement_lines($cond) > 1) {
6199						#print "APW: ALLOWED: cond<$cond>\n";
6200						$allowed[$allow] = 1;
6201					}
6202					if ($block =~/\b(?:if|for|while)\b/) {
6203						#print "APW: ALLOWED: block<$block>\n";
6204						$allowed[$allow] = 1;
6205					}
6206					if (statement_block_size($block) > 1) {
6207						#print "APW: ALLOWED: lines block<$block>\n";
6208						$allowed[$allow] = 1;
6209					}
6210					$allow++;
6211				}
6212				if ($seen) {
6213					my $sum_allowed = 0;
6214					foreach (@allowed) {
6215						$sum_allowed += $_;
6216					}
6217					if ($sum_allowed == 0) {
6218						WARN("BRACES",
6219						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
6220					} elsif ($sum_allowed != $allow &&
6221						 $seen != $allow) {
6222						CHK("BRACES",
6223						    "braces {} should be used on all arms of this statement\n" . $herectx);
6224					}
6225				}
6226			}
6227		}
6228		if (!defined $suppress_ifbraces{$linenr - 1} &&
6229					$line =~ /\b(if|while|for|else)\b/) {
6230			my $allowed = 0;
6231
6232			# Check the pre-context.
6233			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6234				#print "APW: ALLOWED: pre<$1>\n";
6235				$allowed = 1;
6236			}
6237
6238			my ($level, $endln, @chunks) =
6239				ctx_statement_full($linenr, $realcnt, $-[0]);
6240
6241			# Check the condition.
6242			my ($cond, $block) = @{$chunks[0]};
6243			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6244			if (defined $cond) {
6245				substr($block, 0, length($cond), '');
6246			}
6247			if (statement_lines($cond) > 1) {
6248				#print "APW: ALLOWED: cond<$cond>\n";
6249				$allowed = 1;
6250			}
6251			if ($block =~/\b(?:if|for|while)\b/) {
6252				#print "APW: ALLOWED: block<$block>\n";
6253				$allowed = 1;
6254			}
6255			if (statement_block_size($block) > 1) {
6256				#print "APW: ALLOWED: lines block<$block>\n";
6257				$allowed = 1;
6258			}
6259			# Check the post-context.
6260			if (defined $chunks[1]) {
6261				my ($cond, $block) = @{$chunks[1]};
6262				if (defined $cond) {
6263					substr($block, 0, length($cond), '');
6264				}
6265				if ($block =~ /^\s*\{/) {
6266					#print "APW: ALLOWED: chunk-1 block<$block>\n";
6267					$allowed = 1;
6268				}
6269			}
6270			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6271				my $cnt = statement_rawlines($block);
6272				my $herectx = get_stat_here($linenr, $cnt, $here);
6273
6274				WARN("BRACES",
6275				     "braces {} are not necessary for single statement blocks\n" . $herectx);
6276			}
6277		}
6278
6279# check for single line unbalanced braces
6280		if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6281		    $sline =~ /^.\s*else\s*\{\s*$/) {
6282			CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6283		}
6284
6285# check for unnecessary blank lines around braces
6286		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6287			if (CHK("BRACES",
6288				"Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6289			    $fix && $prevrawline =~ /^\+/) {
6290				fix_delete_line($fixlinenr - 1, $prevrawline);
6291			}
6292		}
6293		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6294			if (CHK("BRACES",
6295				"Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6296			    $fix) {
6297				fix_delete_line($fixlinenr, $rawline);
6298			}
6299		}
6300
6301# no volatiles please
6302		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6303		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6304			WARN("VOLATILE",
6305			     "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6306		}
6307
6308# Check for user-visible strings broken across lines, which breaks the ability
6309# to grep for the string.  Make exceptions when the previous string ends in a
6310# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6311# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6312		if ($line =~ /^\+\s*$String/ &&
6313		    $prevline =~ /"\s*$/ &&
6314		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6315			if (WARN("SPLIT_STRING",
6316				 "quoted string split across lines\n" . $hereprev) &&
6317				     $fix &&
6318				     $prevrawline =~ /^\+.*"\s*$/ &&
6319				     $last_coalesced_string_linenr != $linenr - 1) {
6320				my $extracted_string = get_quoted_string($line, $rawline);
6321				my $comma_close = "";
6322				if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6323					$comma_close = $1;
6324				}
6325
6326				fix_delete_line($fixlinenr - 1, $prevrawline);
6327				fix_delete_line($fixlinenr, $rawline);
6328				my $fixedline = $prevrawline;
6329				$fixedline =~ s/"\s*$//;
6330				$fixedline .= substr($extracted_string, 1) . trim($comma_close);
6331				fix_insert_line($fixlinenr - 1, $fixedline);
6332				$fixedline = $rawline;
6333				$fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6334				if ($fixedline !~ /\+\s*$/) {
6335					fix_insert_line($fixlinenr, $fixedline);
6336				}
6337				$last_coalesced_string_linenr = $linenr;
6338			}
6339		}
6340
6341# check for missing a space in a string concatenation
6342		if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6343			WARN('MISSING_SPACE',
6344			     "break quoted strings at a space character\n" . $hereprev);
6345		}
6346
6347# check for an embedded function name in a string when the function is known
6348# This does not work very well for -f --file checking as it depends on patch
6349# context providing the function name or a single line form for in-file
6350# function declarations
6351		if ($line =~ /^\+.*$String/ &&
6352		    defined($context_function) &&
6353		    get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6354		    length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6355			WARN("EMBEDDED_FUNCTION_NAME",
6356			     "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6357		}
6358
6359# check for unnecessary function tracing like uses
6360# This does not use $logFunctions because there are many instances like
6361# 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6362		if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6363			if (WARN("TRACING_LOGGING",
6364				 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6365			    $fix) {
6366                                fix_delete_line($fixlinenr, $rawline);
6367			}
6368		}
6369
6370# check for spaces before a quoted newline
6371		if ($rawline =~ /^.*\".*\s\\n/) {
6372			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6373				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6374			    $fix) {
6375				$fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6376			}
6377
6378		}
6379
6380# concatenated string without spaces between elements
6381		if ($line =~ /$String[A-Z_]/ ||
6382		    ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6383			if (CHK("CONCATENATED_STRING",
6384				"Concatenated strings should use spaces between elements\n" . $herecurr) &&
6385			    $fix) {
6386				while ($line =~ /($String)/g) {
6387					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6388					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6389					$fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6390				}
6391			}
6392		}
6393
6394# uncoalesced string fragments
6395		if ($line =~ /$String\s*[Lu]?"/) {
6396			if (WARN("STRING_FRAGMENTS",
6397				 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6398			    $fix) {
6399				while ($line =~ /($String)(?=\s*")/g) {
6400					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6401					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6402				}
6403			}
6404		}
6405
6406# check for non-standard and hex prefixed decimal printf formats
6407		my $show_L = 1;	#don't show the same defect twice
6408		my $show_Z = 1;
6409		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6410			my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6411			$string =~ s/%%/__/g;
6412			# check for %L
6413			if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6414				WARN("PRINTF_L",
6415				     "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6416				$show_L = 0;
6417			}
6418			# check for %Z
6419			if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6420				WARN("PRINTF_Z",
6421				     "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6422				$show_Z = 0;
6423			}
6424			# check for 0x<decimal>
6425			if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6426				ERROR("PRINTF_0XDECIMAL",
6427				      "Prefixing 0x with decimal output is defective\n" . $herecurr);
6428			}
6429		}
6430
6431# check for line continuations in quoted strings with odd counts of "
6432		if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6433			WARN("LINE_CONTINUATIONS",
6434			     "Avoid line continuations in quoted strings\n" . $herecurr);
6435		}
6436
6437# warn about #if 0
6438		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6439			WARN("IF_0",
6440			     "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6441		}
6442
6443# warn about #if 1
6444		if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6445			WARN("IF_1",
6446			     "Consider removing the #if 1 and its #endif\n" . $herecurr);
6447		}
6448
6449# check for needless "if (<foo>) fn(<foo>)" uses
6450		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6451			my $tested = quotemeta($1);
6452			my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6453			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6454				my $func = $1;
6455				if (WARN('NEEDLESS_IF',
6456					 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6457				    $fix) {
6458					my $do_fix = 1;
6459					my $leading_tabs = "";
6460					my $new_leading_tabs = "";
6461					if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6462						$leading_tabs = $1;
6463					} else {
6464						$do_fix = 0;
6465					}
6466					if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6467						$new_leading_tabs = $1;
6468						if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6469							$do_fix = 0;
6470						}
6471					} else {
6472						$do_fix = 0;
6473					}
6474					if ($do_fix) {
6475						fix_delete_line($fixlinenr - 1, $prevrawline);
6476						$fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6477					}
6478				}
6479			}
6480		}
6481
6482# check for unnecessary "Out of Memory" messages
6483		if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6484		    $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6485		    (defined $1 || defined $3) &&
6486		    $linenr > 3) {
6487			my $testval = $2;
6488			my $testline = $lines[$linenr - 3];
6489
6490			my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6491#			print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6492
6493			if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6494			    $s !~ /\b__GFP_NOWARN\b/ ) {
6495				WARN("OOM_MESSAGE",
6496				     "Possible unnecessary 'out of memory' message\n" . $hereprev);
6497			}
6498		}
6499
6500# check for logging functions with KERN_<LEVEL>
6501		if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6502		    $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6503			my $level = $1;
6504			if (WARN("UNNECESSARY_KERN_LEVEL",
6505				 "Possible unnecessary $level\n" . $herecurr) &&
6506			    $fix) {
6507				$fixed[$fixlinenr] =~ s/\s*$level\s*//;
6508			}
6509		}
6510
6511# check for logging continuations
6512		if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6513			WARN("LOGGING_CONTINUATION",
6514			     "Avoid logging continuation uses where feasible\n" . $herecurr);
6515		}
6516
6517# check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6518		if (defined $stat &&
6519		    $line =~ /\b$logFunctions\s*\(/ &&
6520		    index($stat, '"') >= 0) {
6521			my $lc = $stat =~ tr@\n@@;
6522			$lc = $lc + $linenr;
6523			my $stat_real = get_stat_real($linenr, $lc);
6524			pos($stat_real) = index($stat_real, '"');
6525			while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6526				my $pspec = $1;
6527				my $h = $2;
6528				my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6529				if (WARN("UNNECESSARY_MODIFIER",
6530					 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6531				    $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6532					my $nspec = $pspec;
6533					$nspec =~ s/h//g;
6534					$fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6535				}
6536			}
6537		}
6538
6539# check for mask then right shift without a parentheses
6540		if ($perl_version_ok &&
6541		    $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6542		    $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6543			WARN("MASK_THEN_SHIFT",
6544			     "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6545		}
6546
6547# check for pointer comparisons to NULL
6548		if ($perl_version_ok) {
6549			while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6550				my $val = $1;
6551				my $equal = "!";
6552				$equal = "" if ($4 eq "!=");
6553				if (CHK("COMPARISON_TO_NULL",
6554					"Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6555					    $fix) {
6556					$fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6557				}
6558			}
6559		}
6560
6561# check for bad placement of section $InitAttribute (e.g.: __initdata)
6562		if ($line =~ /(\b$InitAttribute\b)/) {
6563			my $attr = $1;
6564			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6565				my $ptr = $1;
6566				my $var = $2;
6567				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6568				      ERROR("MISPLACED_INIT",
6569					    "$attr should be placed after $var\n" . $herecurr)) ||
6570				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6571				      WARN("MISPLACED_INIT",
6572					   "$attr should be placed after $var\n" . $herecurr))) &&
6573				    $fix) {
6574					$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;
6575				}
6576			}
6577		}
6578
6579# check for $InitAttributeData (ie: __initdata) with const
6580		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6581			my $attr = $1;
6582			$attr =~ /($InitAttributePrefix)(.*)/;
6583			my $attr_prefix = $1;
6584			my $attr_type = $2;
6585			if (ERROR("INIT_ATTRIBUTE",
6586				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6587			    $fix) {
6588				$fixed[$fixlinenr] =~
6589				    s/$InitAttributeData/${attr_prefix}initconst/;
6590			}
6591		}
6592
6593# check for $InitAttributeConst (ie: __initconst) without const
6594		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6595			my $attr = $1;
6596			if (ERROR("INIT_ATTRIBUTE",
6597				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
6598			    $fix) {
6599				my $lead = $fixed[$fixlinenr] =~
6600				    /(^\+\s*(?:static\s+))/;
6601				$lead = rtrim($1);
6602				$lead = "$lead " if ($lead !~ /^\+$/);
6603				$lead = "${lead}const ";
6604				$fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6605			}
6606		}
6607
6608# check for __read_mostly with const non-pointer (should just be const)
6609		if ($line =~ /\b__read_mostly\b/ &&
6610		    $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6611			if (ERROR("CONST_READ_MOSTLY",
6612				  "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6613			    $fix) {
6614				$fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6615			}
6616		}
6617
6618# don't use __constant_<foo> functions outside of include/uapi/
6619		if ($realfile !~ m@^include/uapi/@ &&
6620		    $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6621			my $constant_func = $1;
6622			my $func = $constant_func;
6623			$func =~ s/^__constant_//;
6624			if (WARN("CONSTANT_CONVERSION",
6625				 "$constant_func should be $func\n" . $herecurr) &&
6626			    $fix) {
6627				$fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6628			}
6629		}
6630
6631# prefer usleep_range over udelay
6632		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6633			my $delay = $1;
6634			# ignore udelay's < 10, however
6635			if (! ($delay < 10) ) {
6636				CHK("USLEEP_RANGE",
6637				    "usleep_range is preferred over udelay; see function description of usleep_range() and udelay().\n" . $herecurr);
6638			}
6639			if ($delay > 2000) {
6640				WARN("LONG_UDELAY",
6641				     "long udelay - prefer mdelay; see function description of mdelay().\n" . $herecurr);
6642			}
6643		}
6644
6645# warn about unexpectedly long msleep's
6646		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6647			if ($1 < 20) {
6648				WARN("MSLEEP",
6649				     "msleep < 20ms can sleep for up to 20ms; see function description of msleep().\n" . $herecurr);
6650			}
6651		}
6652
6653# check for comparisons of jiffies
6654		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6655			WARN("JIFFIES_COMPARISON",
6656			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6657		}
6658
6659# check for comparisons of get_jiffies_64()
6660		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6661			WARN("JIFFIES_COMPARISON",
6662			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6663		}
6664
6665# warn about #ifdefs in C files
6666#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6667#			print "#ifdef in C files should be avoided\n";
6668#			print "$herecurr";
6669#			$clean = 0;
6670#		}
6671
6672# warn about spacing in #ifdefs
6673		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6674			if (ERROR("SPACING",
6675				  "exactly one space required after that #$1\n" . $herecurr) &&
6676			    $fix) {
6677				$fixed[$fixlinenr] =~
6678				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6679			}
6680
6681		}
6682
6683# check for spinlock_t definitions without a comment.
6684		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6685		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6686			my $which = $1;
6687			if (!ctx_has_comment($first_line, $linenr)) {
6688				CHK("UNCOMMENTED_DEFINITION",
6689				    "$1 definition without comment\n" . $herecurr);
6690			}
6691		}
6692# check for memory barriers without a comment.
6693
6694		my $barriers = qr{
6695			mb|
6696			rmb|
6697			wmb
6698		}x;
6699		my $barrier_stems = qr{
6700			mb__before_atomic|
6701			mb__after_atomic|
6702			store_release|
6703			load_acquire|
6704			store_mb|
6705			(?:$barriers)
6706		}x;
6707		my $all_barriers = qr{
6708			(?:$barriers)|
6709			smp_(?:$barrier_stems)|
6710			virt_(?:$barrier_stems)
6711		}x;
6712
6713		if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6714			if (!ctx_has_comment($first_line, $linenr)) {
6715				WARN("MEMORY_BARRIER",
6716				     "memory barrier without comment\n" . $herecurr);
6717			}
6718		}
6719
6720		my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6721
6722		if ($realfile !~ m@^include/asm-generic/@ &&
6723		    $realfile !~ m@/barrier\.h$@ &&
6724		    $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6725		    $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6726			WARN("MEMORY_BARRIER",
6727			     "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6728		}
6729
6730# check for waitqueue_active without a comment.
6731		if ($line =~ /\bwaitqueue_active\s*\(/) {
6732			if (!ctx_has_comment($first_line, $linenr)) {
6733				WARN("WAITQUEUE_ACTIVE",
6734				     "waitqueue_active without comment\n" . $herecurr);
6735			}
6736		}
6737
6738# check for data_race without a comment.
6739		if ($line =~ /\bdata_race\s*\(/) {
6740			if (!ctx_has_comment($first_line, $linenr)) {
6741				WARN("DATA_RACE",
6742				     "data_race without comment\n" . $herecurr);
6743			}
6744		}
6745
6746# check of hardware specific defines
6747		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6748			CHK("ARCH_DEFINES",
6749			    "architecture specific defines should be avoided\n" .  $herecurr);
6750		}
6751
6752# check that the storage class is not after a type
6753		if ($line =~ /\b($Type)\s+($Storage)\b/) {
6754			WARN("STORAGE_CLASS",
6755			     "storage class '$2' should be located before type '$1'\n" . $herecurr);
6756		}
6757# Check that the storage class is at the beginning of a declaration
6758		if ($line =~ /\b$Storage\b/ &&
6759		    $line !~ /^.\s*$Storage/ &&
6760		    $line =~ /^.\s*(.+?)\$Storage\s/ &&
6761		    $1 !~ /[\,\)]\s*$/) {
6762			WARN("STORAGE_CLASS",
6763			     "storage class should be at the beginning of the declaration\n" . $herecurr);
6764		}
6765
6766# check the location of the inline attribute, that it is between
6767# storage class and type.
6768		if ($line =~ /\b$Type\s+$Inline\b/ ||
6769		    $line =~ /\b$Inline\s+$Storage\b/) {
6770			ERROR("INLINE_LOCATION",
6771			      "inline keyword should sit between storage class and type\n" . $herecurr);
6772		}
6773
6774# Check for __inline__ and __inline, prefer inline
6775		if ($realfile !~ m@\binclude/uapi/@ &&
6776		    $line =~ /\b(__inline__|__inline)\b/) {
6777			if (WARN("INLINE",
6778				 "plain inline is preferred over $1\n" . $herecurr) &&
6779			    $fix) {
6780				$fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6781
6782			}
6783		}
6784
6785# Check for compiler attributes
6786		if ($realfile !~ m@\binclude/uapi/@ &&
6787		    $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6788			my $attr = $1;
6789			$attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6790
6791			my %attr_list = (
6792				"alias"				=> "__alias",
6793				"aligned"			=> "__aligned",
6794				"always_inline"			=> "__always_inline",
6795				"assume_aligned"		=> "__assume_aligned",
6796				"cold"				=> "__cold",
6797				"const"				=> "__attribute_const__",
6798				"copy"				=> "__copy",
6799				"designated_init"		=> "__designated_init",
6800				"externally_visible"		=> "__visible",
6801				"format"			=> "printf|scanf",
6802				"gnu_inline"			=> "__gnu_inline",
6803				"malloc"			=> "__malloc",
6804				"mode"				=> "__mode",
6805				"no_caller_saved_registers"	=> "__no_caller_saved_registers",
6806				"noclone"			=> "__noclone",
6807				"noinline"			=> "noinline",
6808				"nonstring"			=> "__nonstring",
6809				"noreturn"			=> "__noreturn",
6810				"packed"			=> "__packed",
6811				"pure"				=> "__pure",
6812				"section"			=> "__section",
6813				"used"				=> "__used",
6814				"weak"				=> "__weak"
6815			);
6816
6817			while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6818				my $orig_attr = $1;
6819				my $params = '';
6820				$params = $2 if defined($2);
6821				my $curr_attr = $orig_attr;
6822				$curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6823				if (exists($attr_list{$curr_attr})) {
6824					my $new = $attr_list{$curr_attr};
6825					if ($curr_attr eq "format" && $params) {
6826						$params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6827						$new = "__$1\($2";
6828					} else {
6829						$new = "$new$params";
6830					}
6831					if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6832						 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6833					    $fix) {
6834						my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6835						$fixed[$fixlinenr] =~ s/$remove//;
6836						$fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6837						$fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6838						$fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6839					}
6840				}
6841			}
6842
6843			# Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6844			if ($attr =~ /^_*unused/) {
6845				WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6846				     "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6847			}
6848		}
6849
6850# Check for __attribute__ weak, or __weak declarations (may have link issues)
6851		if ($perl_version_ok &&
6852		    $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6853		    ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6854		     $line =~ /\b__weak\b/)) {
6855			ERROR("WEAK_DECLARATION",
6856			      "Using weak declarations can have unintended link defects\n" . $herecurr);
6857		}
6858
6859# check for c99 types like uint8_t used outside of uapi/ and tools/
6860		if ($realfile !~ m@\binclude/uapi/@ &&
6861		    $realfile !~ m@\btools/@ &&
6862		    $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6863			my $type = $1;
6864			if ($type =~ /\b($typeC99Typedefs)\b/) {
6865				$type = $1;
6866				my $kernel_type = 'u';
6867				$kernel_type = 's' if ($type =~ /^_*[si]/);
6868				$type =~ /(\d+)/;
6869				$kernel_type .= $1;
6870				if (CHK("PREFER_KERNEL_TYPES",
6871					"Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6872				    $fix) {
6873					$fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6874				}
6875			}
6876		}
6877
6878# check for cast of C90 native int or longer types constants
6879		if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6880			my $cast = $1;
6881			my $const = $2;
6882			my $suffix = "";
6883			my $newconst = $const;
6884			$newconst =~ s/${Int_type}$//;
6885			$suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6886			if ($cast =~ /\blong\s+long\b/) {
6887			    $suffix .= 'LL';
6888			} elsif ($cast =~ /\blong\b/) {
6889			    $suffix .= 'L';
6890			}
6891			if (WARN("TYPECAST_INT_CONSTANT",
6892				 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6893			    $fix) {
6894				$fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6895			}
6896		}
6897
6898# check for sizeof(&)
6899		if ($line =~ /\bsizeof\s*\(\s*\&/) {
6900			WARN("SIZEOF_ADDRESS",
6901			     "sizeof(& should be avoided\n" . $herecurr);
6902		}
6903
6904# check for sizeof without parenthesis
6905		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6906			if (WARN("SIZEOF_PARENTHESIS",
6907				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6908			    $fix) {
6909				$fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6910			}
6911		}
6912
6913# check for struct spinlock declarations
6914		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6915			WARN("USE_SPINLOCK_T",
6916			     "struct spinlock should be spinlock_t\n" . $herecurr);
6917		}
6918
6919# check for seq_printf uses that could be seq_puts
6920		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6921			my $fmt = get_quoted_string($line, $rawline);
6922			$fmt =~ s/%%//g;
6923			if ($fmt !~ /%/) {
6924				if (WARN("PREFER_SEQ_PUTS",
6925					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6926				    $fix) {
6927					$fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6928				}
6929			}
6930		}
6931
6932# check for vsprintf extension %p<foo> misuses
6933		if ($perl_version_ok &&
6934		    defined $stat &&
6935		    $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6936		    $1 !~ /^_*volatile_*$/) {
6937			my $stat_real;
6938
6939			my $lc = $stat =~ tr@\n@@;
6940			$lc = $lc + $linenr;
6941		        for (my $count = $linenr; $count <= $lc; $count++) {
6942				my $specifier;
6943				my $extension;
6944				my $qualifier;
6945				my $bad_specifier = "";
6946				my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6947				$fmt =~ s/%%//g;
6948
6949				while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6950					$specifier = $1;
6951					$extension = $2;
6952					$qualifier = $3;
6953					if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6954					    ($extension eq "f" &&
6955					     defined $qualifier && $qualifier !~ /^w/) ||
6956					    ($extension eq "4" &&
6957					     defined $qualifier && $qualifier !~ /^c(?:[hlbc]|hR)$/)) {
6958						$bad_specifier = $specifier;
6959						last;
6960					}
6961					if ($extension eq "x" && !defined($stat_real)) {
6962						if (!defined($stat_real)) {
6963							$stat_real = get_stat_real($linenr, $lc);
6964						}
6965						WARN("VSPRINTF_SPECIFIER_PX",
6966						     "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");
6967					}
6968				}
6969				if ($bad_specifier ne "") {
6970					my $stat_real = get_stat_real($linenr, $lc);
6971					my $msg_level = \&WARN;
6972					my $ext_type = "Invalid";
6973					my $use = "";
6974					if ($bad_specifier =~ /p[Ff]/) {
6975						$use = " - use %pS instead";
6976						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6977					} elsif ($bad_specifier =~ /pA/) {
6978						$use =  " - '%pA' is only intended to be used from Rust code";
6979						$msg_level = \&ERROR;
6980					}
6981
6982					&{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6983						      "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6984				}
6985			}
6986		}
6987
6988# Check for misused memsets
6989		if ($perl_version_ok &&
6990		    defined $stat &&
6991		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6992
6993			my $ms_addr = $2;
6994			my $ms_val = $7;
6995			my $ms_size = $12;
6996
6997			if ($ms_size =~ /^(0x|)0$/i) {
6998				ERROR("MEMSET",
6999				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
7000			} elsif ($ms_size =~ /^(0x|)1$/i) {
7001				WARN("MEMSET",
7002				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
7003			}
7004		}
7005
7006# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
7007#		if ($perl_version_ok &&
7008#		    defined $stat &&
7009#		    $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7010#			if (WARN("PREFER_ETHER_ADDR_COPY",
7011#				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
7012#			    $fix) {
7013#				$fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
7014#			}
7015#		}
7016
7017# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
7018#		if ($perl_version_ok &&
7019#		    defined $stat &&
7020#		    $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7021#			WARN("PREFER_ETHER_ADDR_EQUAL",
7022#			     "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
7023#		}
7024
7025# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
7026# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
7027#		if ($perl_version_ok &&
7028#		    defined $stat &&
7029#		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7030#
7031#			my $ms_val = $7;
7032#
7033#			if ($ms_val =~ /^(?:0x|)0+$/i) {
7034#				if (WARN("PREFER_ETH_ZERO_ADDR",
7035#					 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
7036#				    $fix) {
7037#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
7038#				}
7039#			} elsif ($ms_val =~ /^(?:0xff|255)$/i) {
7040#				if (WARN("PREFER_ETH_BROADCAST_ADDR",
7041#					 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
7042#				    $fix) {
7043#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
7044#				}
7045#			}
7046#		}
7047# strcpy uses that should likely be strscpy
7048		if ($line =~ /\bstrcpy\s*\(/ && !is_userspace($realfile)) {
7049			WARN("STRCPY",
7050			     "Prefer strscpy over strcpy - see: https://github.com/KSPP/linux/issues/88\n" . $herecurr);
7051		}
7052
7053# strlcpy uses that should likely be strscpy
7054		if ($line =~ /\bstrlcpy\s*\(/ && !is_userspace($realfile)) {
7055			WARN("STRLCPY",
7056			     "Prefer strscpy over strlcpy - see: https://github.com/KSPP/linux/issues/89\n" . $herecurr);
7057		}
7058
7059# strncpy uses that should likely be strscpy or strscpy_pad
7060		if ($line =~ /\bstrncpy\s*\(/ && !is_userspace($realfile)) {
7061			WARN("STRNCPY",
7062			     "Prefer strscpy, strscpy_pad, or __nonstring over strncpy - see: https://github.com/KSPP/linux/issues/90\n" . $herecurr);
7063		}
7064
7065# ethtool_sprintf uses that should likely be ethtool_puts
7066		if ($line =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7067			if (WARN("PREFER_ETHTOOL_PUTS",
7068				 "Prefer ethtool_puts over ethtool_sprintf with only two arguments\n" . $herecurr) &&
7069			    $fix) {
7070				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7071			}
7072		}
7073
7074		# use $rawline because $line loses %s via sanitization and thus we can't match against it.
7075		if ($rawline =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*\"\%s\"\s*,\s*$FuncArg\s*\)/) {
7076			if (WARN("PREFER_ETHTOOL_PUTS",
7077				 "Prefer ethtool_puts over ethtool_sprintf with standalone \"%s\" specifier\n" . $herecurr) &&
7078			    $fix) {
7079				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*"\%s"\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7080			}
7081		}
7082
7083
7084# typecasts on min/max could be min_t/max_t
7085		if ($perl_version_ok &&
7086		    defined $stat &&
7087		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7088			if (defined $2 || defined $7) {
7089				my $call = $1;
7090				my $cast1 = deparenthesize($2);
7091				my $arg1 = $3;
7092				my $cast2 = deparenthesize($7);
7093				my $arg2 = $8;
7094				my $cast;
7095
7096				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7097					$cast = "$cast1 or $cast2";
7098				} elsif ($cast1 ne "") {
7099					$cast = $cast1;
7100				} else {
7101					$cast = $cast2;
7102				}
7103				WARN("MINMAX",
7104				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7105			}
7106		}
7107
7108# check usleep_range arguments
7109		if ($perl_version_ok &&
7110		    defined $stat &&
7111		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7112			my $min = $1;
7113			my $max = $7;
7114			if ($min eq $max) {
7115				WARN("USLEEP_RANGE",
7116				     "usleep_range should not use min == max args;  see function description of usleep_range().\n" . "$here\n$stat\n");
7117			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7118				 $min > $max) {
7119				WARN("USLEEP_RANGE",
7120				     "usleep_range args reversed, use min then max;  see function description of usleep_range().\n" . "$here\n$stat\n");
7121			}
7122		}
7123
7124# check for naked sscanf
7125		if ($perl_version_ok &&
7126		    defined $stat &&
7127		    $line =~ /\bsscanf\b/ &&
7128		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7129		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7130		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7131			my $lc = $stat =~ tr@\n@@;
7132			$lc = $lc + $linenr;
7133			my $stat_real = get_stat_real($linenr, $lc);
7134			WARN("NAKED_SSCANF",
7135			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7136		}
7137
7138# check for simple sscanf that should be kstrto<foo>
7139		if ($perl_version_ok &&
7140		    defined $stat &&
7141		    $line =~ /\bsscanf\b/) {
7142			my $lc = $stat =~ tr@\n@@;
7143			$lc = $lc + $linenr;
7144			my $stat_real = get_stat_real($linenr, $lc);
7145			if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7146				my $format = $6;
7147				my $count = $format =~ tr@%@%@;
7148				if ($count == 1 &&
7149				    $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7150					WARN("SSCANF_TO_KSTRTO",
7151					     "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7152				}
7153			}
7154		}
7155
7156# check for new externs in .h files.
7157		if ($realfile =~ /\.h$/ &&
7158		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7159			if (CHK("AVOID_EXTERNS",
7160				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
7161			    $fix) {
7162				$fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7163			}
7164		}
7165
7166# check for new externs in .c files.
7167		if ($realfile =~ /\.c$/ && defined $stat &&
7168		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7169		{
7170			my $function_name = $1;
7171			my $paren_space = $2;
7172
7173			my $s = $stat;
7174			if (defined $cond) {
7175				substr($s, 0, length($cond), '');
7176			}
7177			if ($s =~ /^\s*;/)
7178			{
7179				WARN("AVOID_EXTERNS",
7180				     "externs should be avoided in .c files\n" .  $herecurr);
7181			}
7182
7183			if ($paren_space =~ /\n/) {
7184				WARN("FUNCTION_ARGUMENTS",
7185				     "arguments for function declarations should follow identifier\n" . $herecurr);
7186			}
7187
7188		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7189		    $stat =~ /^\+extern struct\s+(\w+)\s+(\w+)\[\];/)
7190		{
7191			my ($st_type, $st_name) = ($1, $2);
7192
7193			for my $s (keys %maybe_linker_symbol) {
7194			    #print "Linker symbol? $st_name : $s\n";
7195			    goto LIKELY_LINKER_SYMBOL
7196				if $st_name =~ /$s/;
7197			}
7198			WARN("AVOID_EXTERNS",
7199			     "found a file-scoped extern type:$st_type name:$st_name in .c file\n"
7200			     . "is this a linker symbol ?\n" . $herecurr);
7201		  LIKELY_LINKER_SYMBOL:
7202
7203		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7204		    $stat =~ /^.\s*extern\s+/)
7205		{
7206			WARN("AVOID_EXTERNS",
7207			     "externs should be avoided in .c files\n" .  $herecurr);
7208		}
7209
7210# check for function declarations that have arguments without identifier names
7211		if (defined $stat &&
7212		    $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7213		    $1 ne "void") {
7214			my $args = trim($1);
7215			while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7216				my $arg = trim($1);
7217				if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7218					WARN("FUNCTION_ARGUMENTS",
7219					     "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7220				}
7221			}
7222		}
7223
7224# check for function definitions
7225		if ($perl_version_ok &&
7226		    defined $stat &&
7227		    $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7228			$context_function = $1;
7229
7230# check for multiline function definition with misplaced open brace
7231			my $ok = 0;
7232			my $cnt = statement_rawlines($stat);
7233			my $herectx = $here . "\n";
7234			for (my $n = 0; $n < $cnt; $n++) {
7235				my $rl = raw_line($linenr, $n);
7236				$herectx .=  $rl . "\n";
7237				$ok = 1 if ($rl =~ /^[ \+]\{/);
7238				$ok = 1 if ($rl =~ /\{/ && $n == 0);
7239				last if $rl =~ /^[ \+].*\{/;
7240			}
7241			if (!$ok) {
7242				ERROR("OPEN_BRACE",
7243				      "open brace '{' following function definitions go on the next line\n" . $herectx);
7244			}
7245		}
7246
7247# checks for new __setup's
7248		if ($rawline =~ /\b__setup\("([^"]*)"/) {
7249			my $name = $1;
7250
7251			if (!grep(/$name/, @setup_docs)) {
7252				CHK("UNDOCUMENTED_SETUP",
7253				    "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7254			}
7255		}
7256
7257# check for pointless casting of alloc functions
7258		if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7259			WARN("UNNECESSARY_CASTS",
7260			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7261		}
7262
7263# alloc style
7264# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7265		if ($perl_version_ok &&
7266		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7267			CHK("ALLOC_SIZEOF_STRUCT",
7268			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7269		}
7270
7271# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_array/kvmalloc_array/kvcalloc/kcalloc
7272		if ($perl_version_ok &&
7273		    defined $stat &&
7274		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7275			my $oldfunc = $3;
7276			my $a1 = $4;
7277			my $a2 = $10;
7278			my $newfunc = "kmalloc_array";
7279			$newfunc = "kvmalloc_array" if ($oldfunc eq "kvmalloc");
7280			$newfunc = "kvcalloc" if ($oldfunc eq "kvzalloc");
7281			$newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
7282			my $r1 = $a1;
7283			my $r2 = $a2;
7284			if ($a1 =~ /^sizeof\s*\S/) {
7285				$r1 = $a2;
7286				$r2 = $a1;
7287			}
7288			if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7289			    !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7290				my $cnt = statement_rawlines($stat);
7291				my $herectx = get_stat_here($linenr, $cnt, $here);
7292
7293				if (WARN("ALLOC_WITH_MULTIPLY",
7294					 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7295				    $cnt == 1 &&
7296				    $fix) {
7297					$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;
7298				}
7299			}
7300		}
7301
7302# check for krealloc arg reuse
7303		if ($perl_version_ok &&
7304		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7305		    $1 eq $3) {
7306			WARN("KREALLOC_ARG_REUSE",
7307			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7308		}
7309
7310# check for alloc argument mismatch
7311		if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
7312			WARN("ALLOC_ARRAY_ARGS",
7313			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7314		}
7315
7316# check for multiple semicolons
7317		if ($line =~ /;\s*;\s*$/) {
7318			if (WARN("ONE_SEMICOLON",
7319				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7320			    $fix) {
7321				$fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7322			}
7323		}
7324
7325# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7326		if ($realfile !~ m@^include/uapi/@ &&
7327		    $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7328			my $ull = "";
7329			$ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7330			if (CHK("BIT_MACRO",
7331				"Prefer using the BIT$ull macro\n" . $herecurr) &&
7332			    $fix) {
7333				$fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7334			}
7335		}
7336
7337# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7338		if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7339			WARN("IS_ENABLED_CONFIG",
7340			     "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7341		}
7342
7343# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7344		if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7345			my $config = $1;
7346			if (WARN("PREFER_IS_ENABLED",
7347				 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7348			    $fix) {
7349				$fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7350			}
7351		}
7352
7353# check for /* fallthrough */ like comment, prefer fallthrough;
7354		my @fallthroughs = (
7355			'fallthrough',
7356			'@fallthrough@',
7357			'lint -fallthrough[ \t]*',
7358			'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7359			'(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7360			'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7361			'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7362		    );
7363		if ($raw_comment ne '') {
7364			foreach my $ft (@fallthroughs) {
7365				if ($raw_comment =~ /$ft/) {
7366					my $msg_level = \&WARN;
7367					$msg_level = \&CHK if ($file);
7368					&{$msg_level}("PREFER_FALLTHROUGH",
7369						      "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7370					last;
7371				}
7372			}
7373		}
7374
7375# check for switch/default statements without a break;
7376		if ($perl_version_ok &&
7377		    defined $stat &&
7378		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7379			my $cnt = statement_rawlines($stat);
7380			my $herectx = get_stat_here($linenr, $cnt, $here);
7381
7382			WARN("DEFAULT_NO_BREAK",
7383			     "switch default: should use break\n" . $herectx);
7384		}
7385
7386# check for gcc specific __FUNCTION__
7387		if ($line =~ /\b__FUNCTION__\b/) {
7388			if (WARN("USE_FUNC",
7389				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
7390			    $fix) {
7391				$fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7392			}
7393		}
7394
7395# check for uses of __DATE__, __TIME__, __TIMESTAMP__
7396		while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7397			ERROR("DATE_TIME",
7398			      "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7399		}
7400
7401# check for use of yield()
7402		if ($line =~ /\byield\s*\(\s*\)/) {
7403			WARN("YIELD",
7404			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
7405		}
7406
7407# check for comparisons against true and false
7408		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7409			my $lead = $1;
7410			my $arg = $2;
7411			my $test = $3;
7412			my $otype = $4;
7413			my $trail = $5;
7414			my $op = "!";
7415
7416			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7417
7418			my $type = lc($otype);
7419			if ($type =~ /^(?:true|false)$/) {
7420				if (("$test" eq "==" && "$type" eq "true") ||
7421				    ("$test" eq "!=" && "$type" eq "false")) {
7422					$op = "";
7423				}
7424
7425				CHK("BOOL_COMPARISON",
7426				    "Using comparison to $otype is error prone\n" . $herecurr);
7427
7428## maybe suggesting a correct construct would better
7429##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7430
7431			}
7432		}
7433
7434# check for semaphores initialized locked
7435		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7436			WARN("CONSIDER_COMPLETION",
7437			     "consider using a completion\n" . $herecurr);
7438		}
7439
7440# recommend kstrto* over simple_strto* and strict_strto*
7441		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7442			WARN("CONSIDER_KSTRTO",
7443			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
7444		}
7445
7446# check for __initcall(), use device_initcall() explicitly or more appropriate function please
7447		if ($line =~ /^.\s*__initcall\s*\(/) {
7448			WARN("USE_DEVICE_INITCALL",
7449			     "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7450		}
7451
7452# check for spin_is_locked(), suggest lockdep instead
7453		if ($line =~ /\bspin_is_locked\(/) {
7454			WARN("USE_LOCKDEP",
7455			     "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7456		}
7457
7458# check for deprecated apis
7459		if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7460			my $deprecated_api = $1;
7461			my $new_api = $deprecated_apis{$deprecated_api};
7462			WARN("DEPRECATED_API",
7463			     "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7464		}
7465
7466# check for various structs that are normally const (ops, kgdb, device_tree)
7467# and avoid what seem like struct definitions 'struct foo {'
7468		if (defined($const_structs) &&
7469		    $line !~ /\bconst\b/ &&
7470		    $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7471			WARN("CONST_STRUCT",
7472			     "struct $1 should normally be const\n" . $herecurr);
7473		}
7474
7475# use of NR_CPUS is usually wrong
7476# ignore definitions of NR_CPUS and usage to define arrays as likely right
7477# ignore designated initializers using NR_CPUS
7478		if ($line =~ /\bNR_CPUS\b/ &&
7479		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7480		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7481		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7482		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7483		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7484		    $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7485		{
7486			WARN("NR_CPUS",
7487			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7488		}
7489
7490# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7491		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7492			ERROR("DEFINE_ARCH_HAS",
7493			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7494		}
7495
7496# likely/unlikely comparisons similar to "(likely(foo) > 0)"
7497		if ($perl_version_ok &&
7498		    $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7499			WARN("LIKELY_MISUSE",
7500			     "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7501		}
7502
7503# return sysfs_emit(foo, fmt, ...) fmt without newline
7504		if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7505		    substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7506			my $offset = $+[6] - 1;
7507			if (WARN("SYSFS_EMIT",
7508				 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7509			    $fix) {
7510				substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7511			}
7512		}
7513
7514# check for array definition/declarations that should use flexible arrays instead
7515		if ($sline =~ /^[\+ ]\s*\}(?:\s*__packed)?\s*;\s*$/ &&
7516		    $prevline =~ /^\+\s*(?:\}(?:\s*__packed\s*)?|$Type)\s*$Ident\s*\[\s*(0|1)\s*\]\s*;\s*$/) {
7517			if (ERROR("FLEXIBLE_ARRAY",
7518				  "Use C99 flexible arrays - see https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays\n" . $hereprev) &&
7519			    $1 == '0' && $fix) {
7520				$fixed[$fixlinenr - 1] =~ s/\[\s*0\s*\]/[]/;
7521			}
7522		}
7523
7524# nested likely/unlikely calls
7525		if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7526			WARN("LIKELY_MISUSE",
7527			     "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7528		}
7529
7530# whine mightly about in_atomic
7531		if ($line =~ /\bin_atomic\s*\(/) {
7532			if ($realfile =~ m@^drivers/@) {
7533				ERROR("IN_ATOMIC",
7534				      "do not use in_atomic in drivers\n" . $herecurr);
7535			} elsif ($realfile !~ m@^kernel/@) {
7536				WARN("IN_ATOMIC",
7537				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7538			}
7539		}
7540
7541# Complain about RCU Tasks Trace used outside of BPF (and of course, RCU).
7542		our $rcu_trace_funcs = qr{(?x:
7543			rcu_read_lock_trace |
7544			rcu_read_lock_trace_held |
7545			rcu_read_unlock_trace |
7546			call_rcu_tasks_trace |
7547			synchronize_rcu_tasks_trace |
7548			rcu_barrier_tasks_trace |
7549			rcu_request_urgent_qs_task
7550		)};
7551		our $rcu_trace_paths = qr{(?x:
7552			kernel/bpf/ |
7553			include/linux/bpf |
7554			net/bpf/ |
7555			kernel/rcu/ |
7556			include/linux/rcu
7557		)};
7558		if ($line =~ /\b($rcu_trace_funcs)\s*\(/) {
7559			if ($realfile !~ m{^$rcu_trace_paths}) {
7560				WARN("RCU_TASKS_TRACE",
7561				     "use of RCU tasks trace is incorrect outside BPF or core RCU code\n" . $herecurr);
7562			}
7563		}
7564
7565# check for lockdep_set_novalidate_class
7566		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7567		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
7568			if ($realfile !~ m@^kernel/lockdep@ &&
7569			    $realfile !~ m@^include/linux/lockdep@ &&
7570			    $realfile !~ m@^drivers/base/core@) {
7571				ERROR("LOCKDEP",
7572				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7573			}
7574		}
7575
7576		if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7577		    $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7578			WARN("EXPORTED_WORLD_WRITABLE",
7579			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7580		}
7581
7582# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7583# and whether or not function naming is typical and if
7584# DEVICE_ATTR permissions uses are unusual too
7585		if ($perl_version_ok &&
7586		    defined $stat &&
7587		    $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*\)/) {
7588			my $var = $1;
7589			my $perms = $2;
7590			my $show = $3;
7591			my $store = $4;
7592			my $octal_perms = perms_to_octal($perms);
7593			if ($show =~ /^${var}_show$/ &&
7594			    $store =~ /^${var}_store$/ &&
7595			    $octal_perms eq "0644") {
7596				if (WARN("DEVICE_ATTR_RW",
7597					 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7598				    $fix) {
7599					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7600				}
7601			} elsif ($show =~ /^${var}_show$/ &&
7602				 $store =~ /^NULL$/ &&
7603				 $octal_perms eq "0444") {
7604				if (WARN("DEVICE_ATTR_RO",
7605					 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7606				    $fix) {
7607					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7608				}
7609			} elsif ($show =~ /^NULL$/ &&
7610				 $store =~ /^${var}_store$/ &&
7611				 $octal_perms eq "0200") {
7612				if (WARN("DEVICE_ATTR_WO",
7613					 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7614				    $fix) {
7615					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7616				}
7617			} elsif ($octal_perms eq "0644" ||
7618				 $octal_perms eq "0444" ||
7619				 $octal_perms eq "0200") {
7620				my $newshow = "$show";
7621				$newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7622				my $newstore = $store;
7623				$newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7624				my $rename = "";
7625				if ($show ne $newshow) {
7626					$rename .= " '$show' to '$newshow'";
7627				}
7628				if ($store ne $newstore) {
7629					$rename .= " '$store' to '$newstore'";
7630				}
7631				WARN("DEVICE_ATTR_FUNCTIONS",
7632				     "Consider renaming function(s)$rename\n" . $herecurr);
7633			} else {
7634				WARN("DEVICE_ATTR_PERMS",
7635				     "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7636			}
7637		}
7638
7639# Mode permission misuses where it seems decimal should be octal
7640# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7641# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7642#   specific definition of not visible in sysfs.
7643# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7644#   use the default permissions
7645		if ($perl_version_ok &&
7646		    defined $stat &&
7647		    $line =~ /$mode_perms_search/) {
7648			foreach my $entry (@mode_permission_funcs) {
7649				my $func = $entry->[0];
7650				my $arg_pos = $entry->[1];
7651
7652				my $lc = $stat =~ tr@\n@@;
7653				$lc = $lc + $linenr;
7654				my $stat_real = get_stat_real($linenr, $lc);
7655
7656				my $skip_args = "";
7657				if ($arg_pos > 1) {
7658					$arg_pos--;
7659					$skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7660				}
7661				my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7662				if ($stat =~ /$test/) {
7663					my $val = $1;
7664					$val = $6 if ($skip_args ne "");
7665					if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7666					    (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7667					     ($val =~ /^$Octal$/ && length($val) ne 4))) {
7668						ERROR("NON_OCTAL_PERMISSIONS",
7669						      "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7670					}
7671					if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7672						ERROR("EXPORTED_WORLD_WRITABLE",
7673						      "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7674					}
7675				}
7676			}
7677		}
7678
7679# check for uses of S_<PERMS> that could be octal for readability
7680		while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7681			my $oval = $1;
7682			my $octal = perms_to_octal($oval);
7683			if (WARN("SYMBOLIC_PERMS",
7684				 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7685			    $fix) {
7686				$fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7687			}
7688		}
7689
7690# validate content of MODULE_LICENSE against list from include/linux/module.h
7691		if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7692			my $extracted_string = get_quoted_string($line, $rawline);
7693			my $valid_licenses = qr{
7694						GPL|
7695						GPL\ v2|
7696						GPL\ and\ additional\ rights|
7697						Dual\ BSD/GPL|
7698						Dual\ MIT/GPL|
7699						Dual\ MPL/GPL|
7700						Proprietary
7701					}x;
7702			if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7703				WARN("MODULE_LICENSE",
7704				     "unknown module license " . $extracted_string . "\n" . $herecurr);
7705			}
7706			if (!$file && $extracted_string eq '"GPL v2"') {
7707				if (WARN("MODULE_LICENSE",
7708				     "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7709				    $fix) {
7710					$fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7711				}
7712			}
7713		}
7714
7715# check for sysctl duplicate constants
7716		if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7717			WARN("DUPLICATED_SYSCTL_CONST",
7718				"duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7719		}
7720
7721# Check that *_device_id tables have sentinel entries.
7722		if (defined $stat && $line =~ /struct\s+$dev_id_types\s+\w+\s*\[\s*\]\s*=\s*\{/) {
7723			my $stripped = $stat;
7724
7725			# Strip diff line prefixes.
7726			$stripped =~ s/(^|\n)./$1/g;
7727			# Line continuations.
7728			$stripped =~ s/\\\n/\n/g;
7729			# Strip whitespace, empty strings, zeroes, and commas.
7730			$stripped =~ s/""//g;
7731			$stripped =~ s/0x0//g;
7732			$stripped =~ s/[\s$;,0]//g;
7733			# Strip field assignments.
7734			$stripped =~ s/\.$Ident=//g;
7735
7736			if (!(substr($stripped, -4) eq "{}};" ||
7737			      substr($stripped, -6) eq "{{}}};" ||
7738			      $stripped =~ /ISAPNP_DEVICE_SINGLE_END}};$/ ||
7739			      $stripped =~ /ISAPNP_CARD_END}};$/ ||
7740			      $stripped =~ /NULL};$/ ||
7741			      $stripped =~ /PCMCIA_DEVICE_NULL};$/)) {
7742				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
7743			}
7744		}
7745
7746# check for uninitialized pointers with __free attribute
7747		while ($line =~ /\*\s*($Ident)\s+__free\s*\(\s*$Ident\s*\)\s*[,;]/g) {
7748			ERROR("UNINITIALIZED_PTR_WITH_FREE",
7749			      "pointer '$1' with __free attribute should be initialized\n" . $herecurr);
7750		}
7751	}
7752
7753	# If we have no input at all, then there is nothing to report on
7754	# so just keep quiet.
7755	if ($#rawlines == -1) {
7756		exit(0);
7757	}
7758
7759	# In mailback mode only produce a report in the negative, for
7760	# things that appear to be patches.
7761	if ($mailback && ($clean == 1 || !$is_patch)) {
7762		exit(0);
7763	}
7764
7765	# This is not a patch, and we are in 'no-patch' mode so
7766	# just keep quiet.
7767	if (!$chk_patch && !$is_patch) {
7768		exit(0);
7769	}
7770
7771	if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7772		ERROR("NOT_UNIFIED_DIFF",
7773		      "Does not appear to be a unified-diff format patch\n");
7774	}
7775	if ($is_patch && $has_commit_log && $chk_fixes_tag) {
7776		if ($needs_fixes_tag ne "" && !$is_revert && !$fixes_tag) {
7777			WARN("MISSING_FIXES_TAG",
7778				 "The commit message has '$needs_fixes_tag', perhaps it also needs a 'Fixes:' tag?\n");
7779		}
7780	}
7781	if ($is_patch && $has_commit_log && $chk_signoff) {
7782		if ($signoff == 0) {
7783			ERROR("MISSING_SIGN_OFF",
7784			      "Missing Signed-off-by: line(s)\n");
7785		} elsif ($authorsignoff != 1) {
7786			# authorsignoff values:
7787			# 0 -> missing sign off
7788			# 1 -> sign off identical
7789			# 2 -> names and addresses match, comments mismatch
7790			# 3 -> addresses match, names different
7791			# 4 -> names match, addresses different
7792			# 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7793
7794			my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7795
7796			if ($authorsignoff == 0) {
7797				ERROR("NO_AUTHOR_SIGN_OFF",
7798				      "Missing Signed-off-by: line by nominal patch author '$author'\n");
7799			} elsif ($authorsignoff == 2) {
7800				CHK("FROM_SIGN_OFF_MISMATCH",
7801				    "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7802			} elsif ($authorsignoff == 3) {
7803				WARN("FROM_SIGN_OFF_MISMATCH",
7804				     "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7805			} elsif ($authorsignoff == 4) {
7806				WARN("FROM_SIGN_OFF_MISMATCH",
7807				     "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7808			} elsif ($authorsignoff == 5) {
7809				WARN("FROM_SIGN_OFF_MISMATCH",
7810				     "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7811			}
7812		}
7813	}
7814
7815	print report_dump();
7816	if ($summary && !($clean == 1 && $quiet == 1)) {
7817		print "$filename " if ($summary_file);
7818		print "total: $cnt_error errors, $cnt_warn warnings, " .
7819			(($check)? "$cnt_chk checks, " : "") .
7820			"$cnt_lines lines checked\n";
7821	}
7822
7823	if ($quiet == 0) {
7824		# If there were any defects found and not already fixing them
7825		if (!$clean and !$fix) {
7826			print << "EOM"
7827
7828NOTE: For some of the reported defects, checkpatch may be able to
7829      mechanically convert to the typical style using --fix or --fix-inplace.
7830EOM
7831		}
7832		# If there were whitespace errors which cleanpatch can fix
7833		# then suggest that.
7834		if ($rpt_cleaners) {
7835			$rpt_cleaners = 0;
7836			print << "EOM"
7837
7838NOTE: Whitespace errors detected.
7839      You may wish to use scripts/cleanpatch or scripts/cleanfile
7840EOM
7841		}
7842	}
7843
7844	if ($clean == 0 && $fix &&
7845	    ("@rawlines" ne "@fixed" ||
7846	     $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7847		my $newfile = $filename;
7848		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7849		my $linecount = 0;
7850		my $f;
7851
7852		@fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7853
7854		open($f, '>', $newfile)
7855		    or die "$P: Can't open $newfile for write\n";
7856		foreach my $fixed_line (@fixed) {
7857			$linecount++;
7858			if ($file) {
7859				if ($linecount > 3) {
7860					$fixed_line =~ s/^\+//;
7861					print $f $fixed_line . "\n";
7862				}
7863			} else {
7864				print $f $fixed_line . "\n";
7865			}
7866		}
7867		close($f);
7868
7869		if (!$quiet) {
7870			print << "EOM";
7871
7872Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7873
7874Do _NOT_ trust the results written to this file.
7875Do _NOT_ submit these changes without inspecting them for correctness.
7876
7877This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7878No warranties, expressed or implied...
7879EOM
7880		}
7881	}
7882
7883	if ($quiet == 0) {
7884		print "\n";
7885		if ($clean == 1) {
7886			print "$vname has no obvious style problems and is ready for submission.\n";
7887		} else {
7888			print "$vname has style problems, please review.\n";
7889		}
7890	}
7891	return $clean;
7892}
7893