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