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