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