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