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