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