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