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