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