File Index
Files and directories
Sign in
FILE

checkpatch.pl

File preview with syntax highlighting.

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