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