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