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