Project import generated by Copybara.
GitOrigin-RevId: d28750d2694715fda73560ae6bda40d25f9c059b
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..901467b
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# clang-format configuration file. Intended for clang-format >= 4.
+#
+# For more information, see:
+#
+# Documentation/process/clang-format.rst
+# https://clang.llvm.org/docs/ClangFormat.html
+# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
+#
+---
+AccessModifierOffset: -4
+AlignAfterOpenBracket: Align
+AlignConsecutiveAssignments: false
+AlignConsecutiveDeclarations: false
+#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
+AlignOperands: true
+AlignTrailingComments: false
+AllowAllParametersOfDeclarationOnNextLine: false
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: None
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: false
+AlwaysBreakTemplateDeclarations: false
+BinPackArguments: true
+BinPackParameters: true
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: true
+ AfterNamespace: true
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ #AfterExternBlock: false # Unknown to clang-format-5.0
+ BeforeCatch: false
+ BeforeElse: false
+ IndentBraces: false
+ #SplitEmptyFunction: true # Unknown to clang-format-4.0
+ #SplitEmptyRecord: true # Unknown to clang-format-4.0
+ #SplitEmptyNamespace: true # Unknown to clang-format-4.0
+BreakBeforeBinaryOperators: None
+BreakBeforeBraces: Custom
+#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
+BreakBeforeTernaryOperators: false
+BreakConstructorInitializersBeforeComma: false
+#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
+BreakAfterJavaFieldAnnotations: false
+BreakStringLiterals: false
+ColumnLimit: 80
+CommentPragmas: '^ IWYU pragma:'
+#CompactNamespaces: false # Unknown to clang-format-4.0
+ConstructorInitializerAllOnOneLineOrOnePerLine: false
+ConstructorInitializerIndentWidth: 8
+ContinuationIndentWidth: 8
+Cpp11BracedListStyle: false
+DerivePointerAlignment: false
+DisableFormat: false
+ExperimentalAutoDetectBinPacking: false
+#FixNamespaceComments: false # Unknown to clang-format-4.0
+
+# Taken from:
+# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \
+# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \
+# | sort | uniq
+ForEachMacros:
+ - 'list_for_each_entry'
+ - 'list_for_each_entry_safe'
+ - 'mnl_attr_for_each_nested'
+ - 'hlist_for_each'
+ - 'hlist_for_each_safe'
+ - 'hlist_for_each_entry'
+
+#IncludeBlocks: Preserve # Unknown to clang-format-5.0
+IncludeCategories:
+ - Regex: '.*'
+ Priority: 1
+IncludeIsMainRegex: '(Test)?$'
+IndentCaseLabels: false
+#IndentPPDirectives: None # Unknown to clang-format-5.0
+IndentWidth: 8
+IndentWrappedFunctionNames: false
+JavaScriptQuotes: Leave
+JavaScriptWrapImports: true
+KeepEmptyLinesAtTheStartOfBlocks: false
+MacroBlockBegin: ''
+MacroBlockEnd: ''
+MaxEmptyLinesToKeep: 1
+NamespaceIndentation: Inner
+#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
+ObjCBlockIndentWidth: 8
+ObjCSpaceAfterProperty: true
+ObjCSpaceBeforeProtocolList: true
+
+# Taken from git's rules
+#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
+PenaltyBreakBeforeFirstCallParameter: 30
+PenaltyBreakComment: 10
+PenaltyBreakFirstLessLess: 0
+PenaltyBreakString: 10
+PenaltyExcessCharacter: 100
+PenaltyReturnTypeOnItsOwnLine: 60
+
+PointerAlignment: Right
+ReflowComments: false
+SortIncludes: false
+#SortUsingDeclarations: false # Unknown to clang-format-4.0
+SpaceAfterCStyleCast: false
+SpaceAfterTemplateKeyword: true
+SpaceBeforeAssignmentOperators: true
+#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
+#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
+SpaceBeforeParens: ControlStatements
+#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
+SpaceInEmptyParentheses: false
+SpacesBeforeTrailingComments: 1
+SpacesInAngles: false
+SpacesInContainerLiterals: false
+SpacesInCStyleCastParentheses: false
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+Standard: Cpp03
+TabWidth: 8
+UseTab: Always
+...
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e5234a3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,41 @@
+# locally generated
+Config
+static-syms.h
+config.*
+*.o
+*.a
+*.so
+*~
+\#*#
+
+# cscope
+cscope.*
+ncscope.*
+tags
+TAGS
+
+# git files that we don't want to ignore even it they are dot-files
+!.gitignore
+!.mailmap
+
+# for patch generation
+*.diff
+*.patch
+*.orig
+*.rej
+
+# for quilt
+.pc
+patches
+series
+
+# for gdb
+.gdbinit
+.gdb_history
+*.gdb
+
+# tests
+testsuite/results
+testsuite/iproute2/iproute2-this
+testsuite/tools/generate_nlmsg
+testsuite/tests/ip/link/dev_wo_vf_rate.nl
diff --git a/.mailmap b/.mailmap
new file mode 100644
index 0000000..fd40c91
--- /dev/null
+++ b/.mailmap
@@ -0,0 +1,22 @@
+#
+# This list is used by git-shortlog to fix a few botched name translations
+# in the git archive, either because the author's full name was messed up
+# and/or not always written the same way, making contributions from the
+# same person appearing not to be so or badly displayed.
+#
+# Format
+# Full name <goodaddress> <badaddress>
+Steve Wise <larrystevenwise@gmail.com> <swise@opengridcomputing.com>
+Steve Wise <larrystevenwise@gmail.com> <swise@chelsio.com>
+
+Stephen Hemminger <stephen@networkplumber.org> <sthemmin@microsoft.com>
+Stephen Hemminger <stephen@networkplumber.org> <shemming@brocade.com>
+Stephen Hemminger <stephen@networkplumber.org> <stephen.hemminger@vyatta.com>
+Stephen Hemminger <stephen@networkplumber.org> <shemminger@vyatta.com>
+Stephen Hemminger <stephen@networkplumber.org> <shemminger>
+Stephen Hemminger <stephen@networkplumber.org> <shemminger@linux-foundation.org>
+Stephen Hemminger <stephen@networkplumber.org> <shemminger@osdl.org>
+Stephen Hemminger <stephen@networkplumber.org> <osdl.org!shemminger>
+Stephen Hemminger <stephen@networkplumber.org> <osdl.net!shemminger>
+
+David Ahern <dsahern@gmail.com> <dsa@cumulusnetworks.com>
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..5053e7d
--- /dev/null
+++ b/Android.mk
@@ -0,0 +1 @@
+include $(call all-subdir-makefiles)
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..3912109
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/CleanSpec.mk b/CleanSpec.mk
new file mode 100644
index 0000000..b84e1b6
--- /dev/null
+++ b/CleanSpec.mk
@@ -0,0 +1,49 @@
+# Copyright (C) 2007 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# If you don't need to do a full clean build but would like to touch
+# a file or delete some intermediate files, add a clean step to the end
+# of the list. These steps will only be run once, if they haven't been
+# run before.
+#
+# E.g.:
+# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
+# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
+#
+# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
+# files that are missing or have been moved.
+#
+# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
+# Use $(OUT_DIR) to refer to the "out" directory.
+#
+# If you need to re-do something that's already mentioned, just copy
+# the command and add it to the bottom of the list. E.g., if a change
+# that you made last week required touching a file and a change you
+# made today requires touching the same file, just copy the old
+# touch step and add it to the end of the list.
+#
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
+
+# For example:
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
+#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
+#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
+#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
+
+# ************************************************
+# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
+# ************************************************
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..0b79b1f
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,123 @@
+# SPDX-License-Identifier: GPL-2.0
+# Top level Makefile for iproute2
+
+ifeq ("$(origin V)", "command line")
+VERBOSE = $(V)
+endif
+ifndef VERBOSE
+VERBOSE = 0
+endif
+
+ifeq ($(VERBOSE),0)
+MAKEFLAGS += --no-print-directory
+endif
+
+PREFIX?=/usr
+LIBDIR?=$(PREFIX)/lib
+SBINDIR?=/sbin
+CONFDIR?=/etc/iproute2
+NETNS_RUN_DIR?=/var/run/netns
+NETNS_ETC_DIR?=/etc/netns
+DATADIR?=$(PREFIX)/share
+HDRDIR?=$(PREFIX)/include/iproute2
+DOCDIR?=$(DATADIR)/doc/iproute2
+MANDIR?=$(DATADIR)/man
+ARPDDIR?=/var/lib/arpd
+KERNEL_INCLUDE?=/usr/include
+BASH_COMPDIR?=$(DATADIR)/bash-completion/completions
+
+# Path to db_185.h include
+DBM_INCLUDE:=$(DESTDIR)/usr/include
+
+SHARED_LIBS = y
+
+DEFINES= -DRESOLVE_HOSTNAMES -DLIBDIR=\"$(LIBDIR)\"
+ifneq ($(SHARED_LIBS),y)
+DEFINES+= -DNO_SHARED_LIBS
+endif
+
+DEFINES+=-DCONFDIR=\"$(CONFDIR)\" \
+ -DNETNS_RUN_DIR=\"$(NETNS_RUN_DIR)\" \
+ -DNETNS_ETC_DIR=\"$(NETNS_ETC_DIR)\"
+
+#options for mpls
+ADDLIB+=mpls_ntop.o mpls_pton.o
+
+CC := gcc
+HOSTCC ?= $(CC)
+DEFINES += -D_GNU_SOURCE
+# Turn on transparent support for LFS
+DEFINES += -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
+CCOPTS = -O2 -pipe
+WFLAGS := -Wall -Wstrict-prototypes -Wmissing-prototypes
+WFLAGS += -Wmissing-declarations -Wold-style-definition -Wformat=2
+
+CFLAGS := $(WFLAGS) $(CCOPTS) -I../include -I../include/uapi $(DEFINES) $(CFLAGS)
+YACCFLAGS = -d -t -v
+
+SUBDIRS=lib ip tc bridge misc netem genl tipc devlink rdma man
+
+LIBNETLINK=../lib/libutil.a ../lib/libnetlink.a
+LDLIBS += $(LIBNETLINK)
+
+all: config.mk
+ @set -e; \
+ for i in $(SUBDIRS); \
+ do echo; echo $$i; $(MAKE) $(MFLAGS) -C $$i; done
+
+help:
+ @echo "Make Targets:"
+ @echo " all - build binaries"
+ @echo " clean - remove products of build"
+ @echo " distclean - remove configuration and build"
+ @echo " install - install binaries on local machine"
+ @echo " check - run tests"
+ @echo " cscope - build cscope database"
+ @echo " snapshot - generate version number header"
+ @echo ""
+ @echo "Make Arguments:"
+ @echo " V=[0|1] - set build verbosity level"
+
+config.mk:
+ sh configure $(KERNEL_INCLUDE)
+
+install: all
+ install -m 0755 -d $(DESTDIR)$(SBINDIR)
+ install -m 0755 -d $(DESTDIR)$(CONFDIR)
+ install -m 0755 -d $(DESTDIR)$(ARPDDIR)
+ install -m 0755 -d $(DESTDIR)$(HDRDIR)
+ @for i in $(SUBDIRS); do $(MAKE) -C $$i install; done
+ install -m 0644 $(shell find etc/iproute2 -maxdepth 1 -type f) $(DESTDIR)$(CONFDIR)
+ install -m 0755 -d $(DESTDIR)$(BASH_COMPDIR)
+ install -m 0644 bash-completion/tc $(DESTDIR)$(BASH_COMPDIR)
+ install -m 0644 include/bpf_elf.h $(DESTDIR)$(HDRDIR)
+
+snapshot:
+ echo "static const char SNAPSHOT[] = \""`date +%y%m%d`"\";" \
+ > include/SNAPSHOT.h
+
+clean:
+ @for i in $(SUBDIRS) testsuite; \
+ do $(MAKE) $(MFLAGS) -C $$i clean; done
+
+clobber:
+ touch config.mk
+ $(MAKE) $(MFLAGS) clean
+ rm -f config.mk cscope.*
+
+distclean: clobber
+
+check: all
+ $(MAKE) -C testsuite
+ $(MAKE) -C testsuite alltests
+ @if command -v man >/dev/null 2>&1; then \
+ echo "Checking manpages for syntax errors..."; \
+ $(MAKE) -C man check; \
+ else \
+ echo "man not installed, skipping checks for syntax errors."; \
+ fi
+
+cscope:
+ cscope -b -q -R -Iinclude -sip -slib -smisc -snetem -stc
+
+.EXPORT_ALL_VARIABLES:
diff --git a/NOTICE b/NOTICE
new file mode 120000
index 0000000..d24842f
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1 @@
+COPYING
\ No newline at end of file
diff --git a/README b/README
new file mode 100644
index 0000000..bc82187
--- /dev/null
+++ b/README
@@ -0,0 +1,47 @@
+This is a set of utilities for Linux networking.
+
+Information:
+ https://wiki.linuxfoundation.org/networking/iproute2
+
+Download:
+ http://www.kernel.org/pub/linux/utils/net/iproute2/
+
+Stable version repository:
+ git://git.kernel.org/pub/scm/network/iproute2/iproute2.git
+
+Development repository:
+ git://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git
+
+How to compile this.
+--------------------
+1. libdbm
+
+arpd needs to have the berkeleydb development libraries. For Debian
+users this is the package with a name like libdbX.X-dev.
+DBM_INCLUDE points to the directory with db_185.h which
+is the include file used by arpd to get to the old format Berkeley
+database routines. Often this is in the db-devel package.
+
+2. make
+
+The makefile will automatically build a config.mk file which
+contains definitions of libraries that may or may not be available
+on the system such as: ATM, ELF, MNL, and SELINUX.
+
+3. To make documentation, cd to doc/ directory , then
+ look at start of Makefile and set correct values for
+ PAGESIZE=a4 , ie: a4 , letter ... (string)
+ PAGESPERPAGE=2 , ie: 1 , 2 ... (numeric)
+ and make there. It assumes, that latex, dvips and psnup
+ are in your path.
+
+4. This package includes matching sanitized kernel headers because
+ the build environment may not have up to date versions. See Makefile
+ if you have special requirements and need to point at different
+ kernel include files.
+
+Stephen Hemminger
+stephen@networkplumber.org
+
+Alexey Kuznetsov
+kuznet@ms2.inr.ac.ru
diff --git a/README.devel b/README.devel
new file mode 100644
index 0000000..60c9546
--- /dev/null
+++ b/README.devel
@@ -0,0 +1,18 @@
+Iproute2 development is closely tied to Linux kernel networking
+development. Most new features require a kernel and a utility component.
+
+Please submit both to the Linux networking mailing list
+ <netdev@vger.kernel.org>
+
+The current source for the stable version is in the git repository:
+ git://git.kernel.org/pub/scm/network/iproute2/iproute2.git
+
+The development git repository is available at the following address:
+ git://git.kernel.org/pub/scm/network/iproute2/iproute2-next.git
+
+The stable repository contains the source corresponding to the
+current code in the Linux networking tree (net), which in turn is
+aligned on the mainline Linux kernel (ie follows Linus).
+The iproute2-next repository tracks the code intended for the next
+release; it corresponds with networking development tree (net-next)
+in the kernel.
diff --git a/bash-completion/tc b/bash-completion/tc
new file mode 100644
index 0000000..007e1c2
--- /dev/null
+++ b/bash-completion/tc
@@ -0,0 +1,800 @@
+# tc(8) completion -*- shell-script -*-
+# Copyright 2016 6WIND S.A.
+# Copyright 2016 Quentin Monnet <quentin.monnet@6wind.com>
+
+QDISC_KIND=' choke codel bfifo pfifo pfifo_head_drop fq fq_codel gred hhf \
+ mqprio multiq netem pfifo_fast pie red rr sfb sfq tbf atm cbq drr \
+ dsmark hfsc htb prio qfq '
+FILTER_KIND=' basic bpf cgroup flow flower fw route rsvp tcindex u32 matchall '
+ACTION_KIND=' gact mirred bpf sample '
+
+# Takes a list of words in argument; each one of them is added to COMPREPLY if
+# it is not already present on the command line. Returns no value.
+_tc_once_attr()
+{
+ local w subcword found
+ for w in $*; do
+ found=0
+ for (( subcword=3; subcword < ${#words[@]}-1; subcword++ )); do
+ if [[ $w == ${words[subcword]} ]]; then
+ found=1
+ break
+ fi
+ done
+ [[ $found -eq 0 ]] && \
+ COMPREPLY+=( $( compgen -W "$w" -- "$cur" ) )
+ done
+}
+
+# Takes a list of words in argument; each one of them is added to COMPREPLY if
+# it is not already present on the command line from the provided index. Returns
+# no value.
+_tc_once_attr_from()
+{
+ local w subcword found from=$1
+ shift
+ for w in $*; do
+ found=0
+ for (( subcword=$from; subcword < ${#words[@]}-1; subcword++ )); do
+ if [[ $w == ${words[subcword]} ]]; then
+ found=1
+ break
+ fi
+ done
+ [[ $found -eq 0 ]] && \
+ COMPREPLY+=( $( compgen -W "$w" -- "$cur" ) )
+ done
+}
+
+# Takes a list of words in argument; adds them all to COMPREPLY if none of them
+# is already present on the command line. Returns no value.
+_tc_one_of_list()
+{
+ local w subcword
+ for w in $*; do
+ for (( subcword=3; subcword < ${#words[@]}-1; subcword++ )); do
+ [[ $w == ${words[subcword]} ]] && return 1
+ done
+ done
+ COMPREPLY+=( $( compgen -W "$*" -- "$cur" ) )
+}
+
+# Takes a list of words in argument; adds them all to COMPREPLY if none of them
+# is already present on the command line from the provided index. Returns no
+# value.
+_tc_one_of_list_from()
+{
+ local w subcword from=$1
+ shift
+ for w in $*; do
+ for (( subcword=$from; subcword < ${#words[@]}-1; subcword++ )); do
+ [[ $w == ${words[subcword]} ]] && return 1
+ done
+ done
+ COMPREPLY+=( $( compgen -W "$*" -- "$cur" ) )
+}
+
+# Returns "$cur ${cur}arg1 ${cur}arg2 ..."
+_tc_expand_units()
+{
+ [[ $cur =~ ^[0-9]+ ]] || return 1
+ local value=${cur%%[^0-9]*}
+ [[ $cur == $value ]] && echo $cur
+ echo ${@/#/$value}
+}
+
+# Complete based on given word, usually $prev (or possibly the word before),
+# for when an argument or an option name has but a few possible arguments (so
+# tc does not take particular commands into account here).
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_direct_complete()
+{
+ case $1 in
+ # Command options
+ dev)
+ _available_interfaces
+ return 0
+ ;;
+ classid)
+ return 0
+ ;;
+ estimator)
+ local list=$( _tc_expand_units 'secs' 'msecs' 'usecs' )
+ COMPREPLY+=( $( compgen -W "$list" -- "$cur" ) )
+ return 0
+ ;;
+ handle)
+ return 0
+ ;;
+ parent|flowid)
+ local i iface ids cmd
+ for (( i=3; i < ${#words[@]}-2; i++ )); do
+ [[ ${words[i]} == dev ]] && iface=${words[i+1]}
+ break
+ done
+ for cmd in qdisc class; do
+ if [[ -n $iface ]]; then
+ ids+=$( tc $cmd show dev $iface 2>/dev/null | \
+ cut -d\ -f 3 )" "
+ else
+ ids+=$( tc $cmd show 2>/dev/null | cut -d\ -f 3 )
+ fi
+ done
+ [[ $ids != " " ]] && \
+ COMPREPLY+=( $( compgen -W "$ids" -- "$cur" ) )
+ return 0
+ ;;
+ protocol) # list comes from lib/ll_proto.c
+ COMPREPLY+=( $( compgen -W ' 802.1Q 802.1ad 802_2 802_3 LLDP aarp \
+ all aoe arp atalk atmfate atmmpoa ax25 bpq can control cust \
+ ddcmp dec diag dna_dl dna_rc dna_rt econet ieeepup ieeepupat \
+ ip ipv4 ipv6 ipx irda lat localtalk loop mobitex ppp_disc \
+ ppp_mp ppp_ses ppptalk pup pupat rarp sca snap tipc tr_802_2 \
+ wan_ppp x25' -- "$cur" ) )
+ return 0
+ ;;
+ prio)
+ return 0
+ ;;
+ stab)
+ COMPREPLY+=( $( compgen -W 'mtu tsize mpu overhead
+ linklayer' -- "$cur" ) )
+ ;;
+
+ # Qdiscs and classes options
+ alpha|bands|beta|buckets|corrupt|debug|decrement|default|\
+ default_index|depth|direct_qlen|divisor|duplicate|ewma|flow_limit|\
+ flows|hh_limit|increment|indices|linklayer|non_hh_weight|num_tc|\
+ penalty_burst|penalty_rate|prio|priomap|probability|queues|r2q|\
+ reorder|vq|vqs)
+ return 0
+ ;;
+ setup)
+ COMPREPLY+=( $( compgen -W 'vqs' -- "$cur" ) )
+ return 0
+ ;;
+ hw)
+ COMPREPLY+=( $( compgen -W '1 0' -- "$cur" ) )
+ return 0
+ ;;
+ distribution)
+ COMPREPLY+=( $( compgen -W 'uniform normal pareto
+ paretonormal' -- "$cur" ) )
+ return 0
+ ;;
+ loss)
+ COMPREPLY+=( $( compgen -W 'random state gmodel' -- "$cur" ) )
+ return 0
+ ;;
+
+ # Qdiscs and classes options options
+ gap|gmodel|state)
+ return 0
+ ;;
+
+ # Filters options
+ map)
+ COMPREPLY+=( $( compgen -W 'key' -- "$cur" ) )
+ return 0
+ ;;
+ hash)
+ COMPREPLY+=( $( compgen -W 'keys' -- "$cur" ) )
+ return 0
+ ;;
+ indev)
+ _available_interfaces
+ return 0
+ ;;
+ eth_type)
+ COMPREPLY+=( $( compgen -W 'ipv4 ipv6' -- "$cur" ) )
+ return 0
+ ;;
+ ip_proto)
+ COMPREPLY+=( $( compgen -W 'tcp udp' -- "$cur" ) )
+ return 0
+ ;;
+
+ # Filters options options
+ key|keys)
+ [[ ${words[@]} =~ graft ]] && return 1
+ COMPREPLY+=( $( compgen -W 'src dst proto proto-src proto-dst iif \
+ priority mark nfct nfct-src nfct-dst nfct-proto-src \
+ nfct-proto-dst rt-classid sk-uid sk-gid vlan-tag rxhash' -- \
+ "$cur" ) )
+ return 0
+ ;;
+
+ # BPF options - used for filters, actions, and exec
+ export|bytecode|bytecode-file|object-file)
+ _filedir
+ return 0
+ ;;
+ object-pinned|graft) # Pinned object is probably under /sys/fs/bpf/
+ [[ -n "$cur" ]] && _filedir && return 0
+ COMPREPLY=( $( compgen -G "/sys/fs/bpf/*" -- "$cur" ) ) || _filedir
+ compopt -o nospace
+ return 0
+ ;;
+ section)
+ if (type objdump > /dev/null 2>&1) ; then
+ local fword objfile section_list
+ for (( fword=3; fword < ${#words[@]}-3; fword++ )); do
+ if [[ ${words[fword]} == object-file ]]; then
+ objfile=${words[fword+1]}
+ break
+ fi
+ done
+ section_list=$( objdump -h $objfile 2>/dev/null | \
+ sed -n 's/^ *[0-9]\+ \([^ ]*\) *.*/\1/p' )
+ COMPREPLY+=( $( compgen -W "$section_list" -- "$cur" ) )
+ fi
+ return 0
+ ;;
+ import|run)
+ _filedir
+ return 0
+ ;;
+ type)
+ COMPREPLY+=( $( compgen -W 'cls act' -- "$cur" ) )
+ return 0
+ ;;
+
+ # Actions options
+ random)
+ _tc_one_of_list 'netrand determ'
+ return 0
+ ;;
+
+ # Units for option arguments
+ bandwidth|maxrate|peakrate|rate)
+ local list=$( _tc_expand_units 'bit' \
+ 'kbit' 'kibit' 'kbps' 'kibps' \
+ 'mbit' 'mibit' 'mbps' 'mibps' \
+ 'gbit' 'gibit' 'gbps' 'gibps' \
+ 'tbit' 'tibit' 'tbps' 'tibps' )
+ COMPREPLY+=( $( compgen -W "$list" -- "$cur" ) )
+ ;;
+ admit_bytes|avpkt|burst|cell|initial_quantum|limit|max|min|mtu|mpu|\
+ overhead|quantum|redflowlist)
+ local list=$( _tc_expand_units \
+ 'b' 'kbit' 'k' 'mbit' 'm' 'gbit' 'g' )
+ COMPREPLY+=( $( compgen -W "$list" -- "$cur" ) )
+ ;;
+ db|delay|evict_timeout|interval|latency|perturb|rehash|reset_timeout|\
+ target|tupdate)
+ local list=$( _tc_expand_units 'secs' 'msecs' 'usecs' )
+ COMPREPLY+=( $( compgen -W "$list" -- "$cur" ) )
+ ;;
+ esac
+ return 1
+}
+
+# Complete with options names for qdiscs. Each qdisc has its own set of options
+# and it seems we cannot really parse it from anywhere, so we add it manually
+# in this function.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_qdisc_options()
+{
+ case $1 in
+ choke)
+ _tc_once_attr 'limit bandwidth ecn min max burst'
+ return 0
+ ;;
+ codel)
+ _tc_once_attr 'limit target interval'
+ _tc_one_of_list 'ecn noecn'
+ return 0
+ ;;
+ bfifo|pfifo|pfifo_head_drop)
+ _tc_once_attr 'limit'
+ return 0
+ ;;
+ fq)
+ _tc_once_attr 'limit flow_limit quantum initial_quantum maxrate \
+ buckets'
+ _tc_one_of_list 'pacing nopacing'
+ return 0
+ ;;
+ fq_codel)
+ _tc_once_attr 'limit flows target interval quantum'
+ _tc_one_of_list 'ecn noecn'
+ return 0
+ ;;
+ gred)
+ _tc_once_attr 'setup vqs default grio vq prio limit min max avpkt \
+ burst probability bandwidth ecn harddrop'
+ return 0
+ ;;
+ hhf)
+ _tc_once_attr 'limit quantum hh_limit reset_timeout admit_bytes \
+ evict_timeout non_hh_weight'
+ return 0
+ ;;
+ mqprio)
+ _tc_once_attr 'num_tc map queues hw'
+ return 0
+ ;;
+ netem)
+ _tc_once_attr 'delay distribution corrupt duplicate loss ecn \
+ reorder rate'
+ return 0
+ ;;
+ pie)
+ _tc_once_attr 'limit target tupdate alpha beta'
+ _tc_one_of_list 'bytemode nobytemode'
+ _tc_one_of_list 'ecn noecn'
+ return 0
+ ;;
+ red)
+ _tc_once_attr 'limit min max avpkt burst adaptive probability \
+ bandwidth ecn harddrop'
+ return 0
+ ;;
+ rr|prio)
+ _tc_once_attr 'bands priomap multiqueue'
+ return 0
+ ;;
+ sfb)
+ _tc_once_attr 'rehash db limit max target increment decrement \
+ penalty_rate penalty_burst'
+ return 0
+ ;;
+ sfq)
+ _tc_once_attr 'limit perturb quantum divisor flows depth headdrop \
+ redflowlimit min max avpkt burst probability ecn harddrop'
+ return 0
+ ;;
+ tbf)
+ _tc_once_attr 'limit burst rate mtu peakrate latency overhead \
+ linklayer'
+ return 0
+ ;;
+ cbq)
+ _tc_once_attr 'bandwidth avpkt mpu cell ewma'
+ return 0
+ ;;
+ dsmark)
+ _tc_once_attr 'indices default_index set_tc_index'
+ return 0
+ ;;
+ hfsc)
+ _tc_once_attr 'default'
+ return 0
+ ;;
+ htb)
+ _tc_once_attr 'default r2q direct_qlen debug'
+ return 0
+ ;;
+ multiq|pfifo_fast|atm|drr|qfq)
+ return 0
+ ;;
+ esac
+ return 1
+}
+
+# Complete with options names for BPF filters or actions.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_bpf_options()
+{
+ [[ ${words[${#words[@]}-3]} == object-file ]] && \
+ _tc_once_attr 'section export'
+ [[ ${words[${#words[@]}-5]} == object-file ]] && \
+ [[ ${words[${#words[@]}-3]} =~ (section|export) ]] && \
+ _tc_once_attr 'section export'
+ _tc_one_of_list 'bytecode bytecode-file object-file object-pinned'
+ _tc_once_attr 'verbose index direct-action action classid'
+ return 0
+}
+
+# Complete with options names for filter actions.
+# This function is recursive, thus allowing multiple actions statement to be
+# parsed.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_filter_action_options()
+{
+ for ((acwd=$1; acwd < ${#words[@]}-1; acwd++));
+ do
+ if [[ action == ${words[acwd]} ]]; then
+ _tc_filter_action_options $((acwd+1)) && return 0
+ fi
+ done
+
+ local action acwd
+ for ((acwd=$1; acwd < ${#words[@]}-1; acwd++)); do
+ if [[ $ACTION_KIND =~ ' '${words[acwd]}' ' ]]; then
+ _tc_one_of_list_from $acwd action
+ _tc_action_options $acwd && return 0
+ fi
+ done
+ _tc_one_of_list_from $acwd $ACTION_KIND
+ return 0
+}
+
+# Complete with options names for filters.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_filter_options()
+{
+
+ for ((acwd=$1; acwd < ${#words[@]}-1; acwd++));
+ do
+ if [[ action == ${words[acwd]} ]]; then
+ _tc_filter_action_options $((acwd+1)) && return 0
+ fi
+ done
+
+ filter=${words[$1]}
+ case $filter in
+ basic)
+ _tc_once_attr 'match action classid'
+ return 0
+ ;;
+ bpf)
+ _tc_bpf_options
+ return 0
+ ;;
+ cgroup)
+ _tc_once_attr 'match action'
+ return 0
+ ;;
+ flow)
+ local i
+ for (( i=5; i < ${#words[@]}-1; i++ )); do
+ if [[ ${words[i]} =~ ^keys?$ ]]; then
+ _tc_direct_complete 'key'
+ COMPREPLY+=( $( compgen -W 'or and xor rshift addend' -- \
+ "$cur" ) )
+ break
+ fi
+ done
+ _tc_once_attr 'map hash divisor baseclass match action'
+ return 0
+ ;;
+ matchall)
+ _tc_once_attr 'action classid skip_sw skip_hw'
+ return 0
+ ;;
+ flower)
+ _tc_once_attr 'action classid indev dst_mac src_mac eth_type \
+ ip_proto dst_ip src_ip dst_port src_port'
+ return 0
+ ;;
+ fw)
+ _tc_once_attr 'action classid'
+ return 0
+ ;;
+ route)
+ _tc_one_of_list 'from fromif'
+ _tc_once_attr 'to classid action'
+ return 0
+ ;;
+ rsvp)
+ _tc_once_attr 'ipproto session sender classid action tunnelid \
+ tunnel flowlabel spi/ah spi/esp u8 u16 u32'
+ [[ ${words[${#words[@]}-3]} == tunnel ]] && \
+ COMPREPLY+=( $( compgen -W 'skip' -- "$cur" ) )
+ [[ ${words[${#words[@]}-3]} =~ u(8|16|32) ]] && \
+ COMPREPLY+=( $( compgen -W 'mask' -- "$cur" ) )
+ [[ ${words[${#words[@]}-3]} == mask ]] && \
+ COMPREPLY+=( $( compgen -W 'at' -- "$cur" ) )
+ return 0
+ ;;
+ tcindex)
+ _tc_once_attr 'hash mask shift classid action'
+ _tc_one_of_list 'pass_on fall_through'
+ return 0
+ ;;
+ u32)
+ _tc_once_attr 'match link classid action offset ht hashkey sample'
+ COMPREPLY+=( $( compgen -W 'ip ip6 udp tcp icmp u8 u16 u32 mark \
+ divisor' -- "$cur" ) )
+ return 0
+ ;;
+ esac
+ return 1
+}
+
+# Complete with options names for actions.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_action_options()
+{
+ local from=$1
+ local action=${words[from]}
+ case $action in
+ bpf)
+ _tc_bpf_options
+ return 0
+ ;;
+ mirred)
+ _tc_one_of_list_from $from 'ingress egress'
+ _tc_one_of_list_from $from 'mirror redirect'
+ _tc_once_attr_from $from 'index dev'
+ return 0
+ ;;
+ sample)
+ _tc_once_attr_from $from 'rate'
+ _tc_once_attr_from $from 'trunc'
+ _tc_once_attr_from $from 'group'
+ return 0
+ ;;
+ gact)
+ _tc_one_of_list_from $from 'reclassify drop continue pass'
+ _tc_once_attr_from $from 'random'
+ return 0
+ ;;
+ esac
+ return 1
+}
+
+# Complete with options names for exec.
+# Returns 0 is completion should stop after running this function, 1 otherwise.
+_tc_exec_options()
+{
+ case $1 in
+ import)
+ [[ ${words[${#words[@]}-3]} == import ]] && \
+ _tc_once_attr 'run'
+ return 0
+ ;;
+ graft)
+ COMPREPLY+=( $( compgen -W 'key type' -- "$cur" ) )
+ [[ ${words[${#words[@]}-3]} == object-file ]] && \
+ _tc_once_attr 'type'
+ _tc_bpf_options
+ return 0
+ ;;
+ esac
+ return 1
+}
+
+# Main completion function
+# Logic is as follows:
+# 1. Check if previous word is a global option; if so, propose arguments.
+# 2. Check if current word is a global option; if so, propose completion.
+# 3. Check for the presence of a main command (qdisc|class|filter|...). If
+# there is one, first call _tc_direct_complete to see if previous word is
+# waiting for a particular completion. If so, propose completion and exit.
+# 4. Extract main command and -- if available -- its subcommand
+# (add|delete|show|...).
+# 5. Propose completion based on main and sub- command in use. Additional
+# functions may be called for qdiscs, classes or filter options.
+_tc()
+{
+ local cur prev words cword
+ _init_completion || return
+
+ case $prev in
+ -V|-Version)
+ return 0
+ ;;
+ -b|-batch|-cf|-conf)
+ _filedir
+ return 0
+ ;;
+ -force)
+ COMPREPLY=( $( compgen -W '-batch' -- "$cur" ) )
+ return 0
+ ;;
+ -nm|name)
+ [[ -r /etc/iproute2/tc_cls ]] || \
+ COMPREPLY=( $( compgen -W '-conf' -- "$cur" ) )
+ return 0
+ ;;
+ -n|-net|-netns)
+ local nslist=$( ip netns list 2>/dev/null )
+ COMPREPLY+=( $( compgen -W "$nslist" -- "$cur" ) )
+ return 0
+ ;;
+ -tshort)
+ _tc_once_attr '-statistics'
+ COMPREPLY+=( $( compgen -W 'monitor' -- "$cur" ) )
+ return 0
+ ;;
+ -timestamp)
+ _tc_once_attr '-statistics -tshort'
+ COMPREPLY+=( $( compgen -W 'monitor' -- "$cur" ) )
+ return 0
+ ;;
+ esac
+
+ # Search for main commands
+ local subcword cmd subcmd
+ for (( subcword=1; subcword < ${#words[@]}-1; subcword++ )); do
+ [[ ${words[subcword]} == -b?(atch) ]] && return 0
+ [[ -n $cmd ]] && subcmd=${words[subcword]} && break
+ [[ ${words[subcword]} != -* && \
+ ${words[subcword-1]} != -@(n?(et?(ns))|c?(on)f) ]] && \
+ cmd=${words[subcword]}
+ done
+
+ if [[ -z $cmd ]]; then
+ case $cur in
+ -*)
+ local c='-Version -statistics -details -raw -pretty \
+ -iec -graphe -batch -name -netns -timestamp'
+ [[ $cword -eq 1 ]] && c+=' -force'
+ COMPREPLY=( $( compgen -W "$c" -- "$cur" ) )
+ return 0
+ ;;
+ *)
+ COMPREPLY=( $( compgen -W "help $( tc help 2>&1 | \
+ command sed \
+ -e '/OBJECT := /!d' \
+ -e 's/.*{//' \
+ -e 's/}.*//' \
+ -e \ 's/|//g' )" -- "$cur" ) )
+ return 0
+ ;;
+ esac
+ fi
+
+ [[ $subcmd == help ]] && return 0
+
+ # For this set of commands we may create COMPREPLY just by analysing the
+ # previous word, if it expects for a specific list of options or values.
+ if [[ $cmd =~ (qdisc|class|filter|action|exec) ]]; then
+ _tc_direct_complete $prev && return 0
+ if [[ ${words[${#words[@]}-3]} == estimator ]]; then
+ local list=$( _tc_expand_units 'secs' 'msecs' 'usecs' )
+ COMPREPLY+=( $( compgen -W "$list" -- "$cur" ) ) && return 0
+ fi
+ fi
+
+ # Completion depends on main command and subcommand in use.
+ case $cmd in
+ qdisc)
+ case $subcmd in
+ add|change|replace|link|del|delete)
+ if [[ $(($cword-$subcword)) -eq 1 ]]; then
+ COMPREPLY=( $( compgen -W 'dev' -- "$cur" ) )
+ return 0
+ fi
+ local qdisc qdwd
+ for ((qdwd=$subcword; qdwd < ${#words[@]}-1; qdwd++)); do
+ if [[ $QDISC_KIND =~ ' '${words[qdwd]}' ' ]]; then
+ qdisc=${words[qdwd]}
+ _tc_qdisc_options $qdisc && return 0
+ fi
+ done
+ _tc_one_of_list $QDISC_KIND
+ _tc_one_of_list 'root ingress parent clsact'
+ _tc_once_attr 'handle estimator stab'
+ ;;
+ show)
+ _tc_once_attr 'dev'
+ _tc_one_of_list 'ingress clsact'
+ _tc_once_attr '-statistics -details -raw -pretty -iec \
+ -graph -name'
+ ;;
+ help)
+ return 0
+ ;;
+ *)
+ [[ $cword -eq $subcword ]] && \
+ COMPREPLY=( $( compgen -W 'help add delete change \
+ replace link show' -- "$cur" ) )
+ ;;
+ esac
+ ;;
+
+ class)
+ case $subcmd in
+ add|change|replace|del|delete)
+ if [[ $(($cword-$subcword)) -eq 1 ]]; then
+ COMPREPLY=( $( compgen -W 'dev' -- "$cur" ) )
+ return 0
+ fi
+ local qdisc qdwd
+ for ((qdwd=$subcword; qdwd < ${#words[@]}-1; qdwd++)); do
+ if [[ $QDISC_KIND =~ ' '${words[qdwd]}' ' ]]; then
+ qdisc=${words[qdwd]}
+ _tc_qdisc_options $qdisc && return 0
+ fi
+ done
+ _tc_one_of_list $QDISC_KIND
+ _tc_one_of_list 'root parent'
+ _tc_once_attr 'classid'
+ ;;
+ show)
+ _tc_once_attr 'dev'
+ _tc_one_of_list 'root parent'
+ _tc_once_attr '-statistics -details -raw -pretty -iec \
+ -graph -name'
+ ;;
+ help)
+ return 0
+ ;;
+ *)
+ [[ $cword -eq $subcword ]] && \
+ COMPREPLY=( $( compgen -W 'help add delete change \
+ replace show' -- "$cur" ) )
+ ;;
+ esac
+ ;;
+
+ filter)
+ case $subcmd in
+ add|change|replace|del|delete)
+ if [[ $(($cword-$subcword)) -eq 1 ]]; then
+ COMPREPLY=( $( compgen -W 'dev' -- "$cur" ) )
+ return 0
+ fi
+ local filter fltwd
+ for ((fltwd=$subcword; fltwd < ${#words[@]}-1; fltwd++));
+ do
+ if [[ $FILTER_KIND =~ ' '${words[fltwd]}' ' ]]; then
+ _tc_filter_options $fltwd && return 0
+ fi
+ done
+ _tc_one_of_list $FILTER_KIND
+ _tc_one_of_list 'root ingress egress parent'
+ _tc_once_attr 'handle estimator pref protocol'
+ ;;
+ show)
+ _tc_once_attr 'dev'
+ _tc_one_of_list 'root ingress egress parent'
+ _tc_once_attr '-statistics -details -raw -pretty -iec \
+ -graph -name'
+ ;;
+ help)
+ return 0
+ ;;
+ *)
+ [[ $cword -eq $subcword ]] && \
+ COMPREPLY=( $( compgen -W 'help add delete change \
+ replace show' -- "$cur" ) )
+ ;;
+ esac
+ ;;
+
+ action)
+ case $subcmd in
+ add|change|replace)
+ local action acwd
+ for ((acwd=$subcword; acwd < ${#words[@]}-1; acwd++)); do
+ if [[ $ACTION_KIND =~ ' '${words[acwd]}' ' ]]; then
+ _tc_action_options $acwd && return 0
+ fi
+ done
+ _tc_one_of_list $ACTION_KIND
+ ;;
+ get|del|delete)
+ _tc_once_attr 'index'
+ ;;
+ lst|list|flush|show)
+ _tc_one_of_list $ACTION_KIND
+ ;;
+ *)
+ [[ $cword -eq $subcword ]] && \
+ COMPREPLY=( $( compgen -W 'help add delete change \
+ replace show list flush action' -- "$cur" ) )
+ ;;
+ esac
+ ;;
+
+ monitor)
+ COMPREPLY=( $( compgen -W 'help' -- "$cur" ) )
+ ;;
+
+ exec)
+ case $subcmd in
+ bpf)
+ local excmd exwd EXEC_KIND=' import debug graft '
+ for ((exwd=$subcword; exwd < ${#words[@]}-1; exwd++)); do
+ if [[ $EXEC_KIND =~ ' '${words[exwd]}' ' ]]; then
+ excmd=${words[exwd]}
+ _tc_exec_options $excmd && return 0
+ fi
+ done
+ _tc_one_of_list $EXEC_KIND
+ ;;
+ *)
+ [[ $cword -eq $subcword ]] && \
+ COMPREPLY=( $( compgen -W 'bpf' -- "$cur" ) )
+ ;;
+ esac
+ ;;
+ esac
+} &&
+complete -F _tc tc
+
+# ex: ts=4 sw=4 et filetype=sh
diff --git a/bridge/.gitignore b/bridge/.gitignore
new file mode 100644
index 0000000..7096907
--- /dev/null
+++ b/bridge/.gitignore
@@ -0,0 +1 @@
+bridge
diff --git a/bridge/Android.mk b/bridge/Android.mk
new file mode 100644
index 0000000..cf0487f
--- /dev/null
+++ b/bridge/Android.mk
@@ -0,0 +1,25 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := bridge
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := bridge.c \
+ fdb.c \
+ monitor.c \
+ link.c \
+ mdb.c \
+ vlan.c
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
+ $(LOCAL_PATH)/../include/uapi
+LOCAL_STATIC_LIBRARIES := libnetlink \
+ libiprouteutil
+LOCAL_CFLAGS := \
+ -O2 -W -Wall \
+ -Wno-implicit-function-declaration \
+ -Wno-missing-field-initializers \
+ -Wno-pointer-arith \
+ -Wno-sign-compare \
+ -Wno-unused-parameter \
+ -Werror \
+ -D_GNU_SOURCE -DHAVE_SETNS
+include $(BUILD_EXECUTABLE)
diff --git a/bridge/Makefile b/bridge/Makefile
new file mode 100644
index 0000000..c6b7d08
--- /dev/null
+++ b/bridge/Makefile
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: GPL-2.0
+BROBJ = bridge.o fdb.o monitor.o link.o mdb.o vlan.o
+
+include ../config.mk
+
+all: bridge
+
+bridge: $(BROBJ) $(LIBNETLINK)
+ $(QUIET_LINK)$(CC) $^ $(LDFLAGS) $(LDLIBS) -o $@
+
+install: all
+ install -m 0755 bridge $(DESTDIR)$(SBINDIR)
+
+clean:
+ rm -f $(BROBJ) bridge
diff --git a/bridge/br_common.h b/bridge/br_common.h
new file mode 100644
index 0000000..b5798da
--- /dev/null
+++ b/bridge/br_common.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#define MDB_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + RTA_ALIGN(sizeof(struct br_mdb_entry))))
+
+#define MDB_RTR_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + RTA_ALIGN(sizeof(__u32))))
+
+void print_vlan_info(struct rtattr *tb, int ifindex);
+int print_linkinfo(struct nlmsghdr *n, void *arg);
+int print_mdb_mon(struct nlmsghdr *n, void *arg);
+int print_fdb(struct nlmsghdr *n, void *arg);
+
+int do_fdb(int argc, char **argv);
+int do_mdb(int argc, char **argv);
+int do_monitor(int argc, char **argv);
+int do_vlan(int argc, char **argv);
+int do_link(int argc, char **argv);
+
+extern int preferred_family;
+extern int show_stats;
+extern int show_details;
+extern int timestamp;
+extern int compress_vlans;
+extern int json;
+extern struct rtnl_handle rth;
diff --git a/bridge/bridge.c b/bridge/bridge.c
new file mode 100644
index 0000000..a50d9d5
--- /dev/null
+++ b/bridge/bridge.c
@@ -0,0 +1,217 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Get/set/delete bridge with netlink
+ *
+ * Authors: Stephen Hemminger <shemminger@vyatta.com>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <string.h>
+#include <errno.h>
+
+#include "SNAPSHOT.h"
+#include "utils.h"
+#include "br_common.h"
+#include "namespace.h"
+#include "color.h"
+
+struct rtnl_handle rth = { .fd = -1 };
+int preferred_family = AF_UNSPEC;
+int oneline;
+int show_stats;
+int show_details;
+static int color;
+int compress_vlans;
+int json;
+int timestamp;
+static const char *batch_file;
+int force;
+
+static void usage(void) __attribute__((noreturn));
+
+static void usage(void)
+{
+ fprintf(stderr,
+"Usage: bridge [ OPTIONS ] OBJECT { COMMAND | help }\n"
+" bridge [ -force ] -batch filename\n"
+"where OBJECT := { link | fdb | mdb | vlan | monitor }\n"
+" OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] |\n"
+" -o[neline] | -t[imestamp] | -n[etns] name |\n"
+" -c[ompressvlans] -color -p[retty] -j[son] }\n");
+ exit(-1);
+}
+
+static int do_help(int argc, char **argv)
+{
+ usage();
+}
+
+
+static const struct cmd {
+ const char *cmd;
+ int (*func)(int argc, char **argv);
+} cmds[] = {
+ { "link", do_link },
+ { "fdb", do_fdb },
+ { "mdb", do_mdb },
+ { "vlan", do_vlan },
+ { "monitor", do_monitor },
+ { "help", do_help },
+ { 0 }
+};
+
+static int do_cmd(const char *argv0, int argc, char **argv)
+{
+ const struct cmd *c;
+
+ for (c = cmds; c->cmd; ++c) {
+ if (matches(argv0, c->cmd) == 0)
+ return c->func(argc-1, argv+1);
+ }
+
+ fprintf(stderr,
+ "Object \"%s\" is unknown, try \"bridge help\".\n", argv0);
+ return -1;
+}
+
+static int batch(const char *name)
+{
+ char *line = NULL;
+ size_t len = 0;
+ int ret = EXIT_SUCCESS;
+
+ if (name && strcmp(name, "-") != 0) {
+ if (freopen(name, "r", stdin) == NULL) {
+ fprintf(stderr,
+ "Cannot open file \"%s\" for reading: %s\n",
+ name, strerror(errno));
+ return EXIT_FAILURE;
+ }
+ }
+
+ if (rtnl_open(&rth, 0) < 0) {
+ fprintf(stderr, "Cannot open rtnetlink\n");
+ return EXIT_FAILURE;
+ }
+
+ rtnl_set_strict_dump(&rth);
+
+ cmdlineno = 0;
+ while (getcmdline(&line, &len, stdin) != -1) {
+ char *largv[100];
+ int largc;
+
+ largc = makeargs(line, largv, 100);
+ if (largc == 0)
+ continue; /* blank line */
+
+ if (do_cmd(largv[0], largc, largv)) {
+ fprintf(stderr, "Command failed %s:%d\n",
+ name, cmdlineno);
+ ret = EXIT_FAILURE;
+ if (!force)
+ break;
+ }
+ }
+ if (line)
+ free(line);
+
+ rtnl_close(&rth);
+ return ret;
+}
+
+int
+main(int argc, char **argv)
+{
+ while (argc > 1) {
+ const char *opt = argv[1];
+
+ if (strcmp(opt, "--") == 0) {
+ argc--; argv++;
+ break;
+ }
+ if (opt[0] != '-')
+ break;
+ if (opt[1] == '-')
+ opt++;
+
+ if (matches(opt, "-help") == 0) {
+ usage();
+ } else if (matches(opt, "-Version") == 0) {
+ printf("bridge utility, 0.0\n");
+ exit(0);
+ } else if (matches(opt, "-stats") == 0 ||
+ matches(opt, "-statistics") == 0) {
+ ++show_stats;
+ } else if (matches(opt, "-details") == 0) {
+ ++show_details;
+ } else if (matches(opt, "-oneline") == 0) {
+ ++oneline;
+ } else if (matches(opt, "-timestamp") == 0) {
+ ++timestamp;
+ } else if (matches(opt, "-family") == 0) {
+ argc--;
+ argv++;
+ if (argc <= 1)
+ usage();
+ if (strcmp(argv[1], "inet") == 0)
+ preferred_family = AF_INET;
+ else if (strcmp(argv[1], "inet6") == 0)
+ preferred_family = AF_INET6;
+ else if (strcmp(argv[1], "help") == 0)
+ usage();
+ else
+ invarg("invalid protocol family", argv[1]);
+ } else if (strcmp(opt, "-4") == 0) {
+ preferred_family = AF_INET;
+ } else if (strcmp(opt, "-6") == 0) {
+ preferred_family = AF_INET6;
+ } else if (matches(opt, "-netns") == 0) {
+ NEXT_ARG();
+ if (netns_switch(argv[1]))
+ exit(-1);
+ } else if (matches(opt, "-compressvlans") == 0) {
+ ++compress_vlans;
+ } else if (matches_color(opt, &color)) {
+ } else if (matches(opt, "-force") == 0) {
+ ++force;
+ } else if (matches(opt, "-json") == 0) {
+ ++json;
+ } else if (matches(opt, "-pretty") == 0) {
+ ++pretty;
+ } else if (matches(opt, "-batch") == 0) {
+ argc--;
+ argv++;
+ if (argc <= 1)
+ usage();
+ batch_file = argv[1];
+ } else {
+ fprintf(stderr,
+ "Option \"%s\" is unknown, try \"bridge help\".\n",
+ opt);
+ exit(-1);
+ }
+ argc--; argv++;
+ }
+
+ _SL_ = oneline ? "\\" : "\n";
+
+ check_enable_color(color, json);
+
+ if (batch_file)
+ return batch(batch_file);
+
+ if (rtnl_open(&rth, 0) < 0)
+ exit(1);
+
+ rtnl_set_strict_dump(&rth);
+
+ if (argc > 1)
+ return do_cmd(argv[1], argc-1, argv+1);
+
+ rtnl_close(&rth);
+ usage();
+}
diff --git a/bridge/fdb.c b/bridge/fdb.c
new file mode 100644
index 0000000..941ce2d
--- /dev/null
+++ b/bridge/fdb.c
@@ -0,0 +1,545 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Get/set/delete fdb table with netlink
+ *
+ * TODO: merge/replace this with ip neighbour
+ *
+ * Authors: Stephen Hemminger <shemminger@vyatta.com>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <time.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <linux/if_bridge.h>
+#include <linux/if_ether.h>
+#include <linux/neighbour.h>
+#include <string.h>
+#include <limits.h>
+#include <stdbool.h>
+
+#include "json_print.h"
+#include "libnetlink.h"
+#include "br_common.h"
+#include "rt_names.h"
+#include "utils.h"
+
+static unsigned int filter_index, filter_vlan, filter_state, filter_master;
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: bridge fdb { add | append | del | replace } ADDR dev DEV\n"
+ " [ self ] [ master ] [ use ] [ router ] [ extern_learn ]\n"
+ " [ sticky ] [ local | static | dynamic ] [ dst IPADDR ]\n"
+ " [ vlan VID ] [ port PORT] [ vni VNI ] [ via DEV ]\n"
+ " [ src_vni VNI ]\n"
+ " bridge fdb [ show [ br BRDEV ] [ brport DEV ] [ vlan VID ] [ state STATE ] ]\n");
+ exit(-1);
+}
+
+static const char *state_n2a(unsigned int s)
+{
+ static char buf[32];
+
+ if (s & NUD_PERMANENT)
+ return "permanent";
+
+ if (s & NUD_NOARP)
+ return "static";
+
+ if (s & NUD_STALE)
+ return "stale";
+
+ if (s & NUD_REACHABLE)
+ return "";
+
+ sprintf(buf, "state=%#x", s);
+ return buf;
+}
+
+static int state_a2n(unsigned int *s, const char *arg)
+{
+ if (matches(arg, "permanent") == 0)
+ *s = NUD_PERMANENT;
+ else if (matches(arg, "static") == 0 || matches(arg, "temp") == 0)
+ *s = NUD_NOARP;
+ else if (matches(arg, "stale") == 0)
+ *s = NUD_STALE;
+ else if (matches(arg, "reachable") == 0 || matches(arg, "dynamic") == 0)
+ *s = NUD_REACHABLE;
+ else if (strcmp(arg, "all") == 0)
+ *s = ~0;
+ else if (get_unsigned(s, arg, 0))
+ return -1;
+
+ return 0;
+}
+
+static void fdb_print_flags(FILE *fp, unsigned int flags)
+{
+ open_json_array(PRINT_JSON,
+ is_json_context() ? "flags" : "");
+
+ if (flags & NTF_SELF)
+ print_string(PRINT_ANY, NULL, "%s ", "self");
+
+ if (flags & NTF_ROUTER)
+ print_string(PRINT_ANY, NULL, "%s ", "router");
+
+ if (flags & NTF_EXT_LEARNED)
+ print_string(PRINT_ANY, NULL, "%s ", "extern_learn");
+
+ if (flags & NTF_OFFLOADED)
+ print_string(PRINT_ANY, NULL, "%s ", "offload");
+
+ if (flags & NTF_MASTER)
+ print_string(PRINT_ANY, NULL, "%s ", "master");
+
+ if (flags & NTF_STICKY)
+ print_string(PRINT_ANY, NULL, "%s ", "sticky");
+
+ close_json_array(PRINT_JSON, NULL);
+}
+
+static void fdb_print_stats(FILE *fp, const struct nda_cacheinfo *ci)
+{
+ static int hz;
+
+ if (!hz)
+ hz = get_user_hz();
+
+ if (is_json_context()) {
+ print_uint(PRINT_JSON, "used", NULL,
+ ci->ndm_used / hz);
+ print_uint(PRINT_JSON, "updated", NULL,
+ ci->ndm_updated / hz);
+ } else {
+ fprintf(fp, "used %d/%d ", ci->ndm_used / hz,
+ ci->ndm_updated / hz);
+
+ }
+}
+
+int print_fdb(struct nlmsghdr *n, void *arg)
+{
+ FILE *fp = arg;
+ struct ndmsg *r = NLMSG_DATA(n);
+ int len = n->nlmsg_len;
+ struct rtattr *tb[NDA_MAX+1];
+ __u16 vid = 0;
+
+ if (n->nlmsg_type != RTM_NEWNEIGH && n->nlmsg_type != RTM_DELNEIGH) {
+ fprintf(stderr, "Not RTM_NEWNEIGH: %08x %08x %08x\n",
+ n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
+ return 0;
+ }
+
+ len -= NLMSG_LENGTH(sizeof(*r));
+ if (len < 0) {
+ fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
+ return -1;
+ }
+
+ if (r->ndm_family != AF_BRIDGE)
+ return 0;
+
+ if (filter_index && filter_index != r->ndm_ifindex)
+ return 0;
+
+ if (filter_state && !(r->ndm_state & filter_state))
+ return 0;
+
+ parse_rtattr(tb, NDA_MAX, NDA_RTA(r),
+ n->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
+
+ if (tb[NDA_VLAN])
+ vid = rta_getattr_u16(tb[NDA_VLAN]);
+
+ if (filter_vlan && filter_vlan != vid)
+ return 0;
+
+ open_json_object(NULL);
+ if (n->nlmsg_type == RTM_DELNEIGH)
+ print_bool(PRINT_ANY, "deleted", "Deleted ", true);
+
+ if (tb[NDA_LLADDR]) {
+ const char *lladdr;
+ SPRINT_BUF(b1);
+
+ lladdr = ll_addr_n2a(RTA_DATA(tb[NDA_LLADDR]),
+ RTA_PAYLOAD(tb[NDA_LLADDR]),
+ ll_index_to_type(r->ndm_ifindex),
+ b1, sizeof(b1));
+
+ print_color_string(PRINT_ANY, COLOR_MAC,
+ "mac", "%s ", lladdr);
+ }
+
+ if (!filter_index && r->ndm_ifindex)
+ print_color_string(PRINT_ANY, COLOR_IFNAME,
+ "ifname", "dev %s ",
+ ll_index_to_name(r->ndm_ifindex));
+
+ if (tb[NDA_DST]) {
+ int family = AF_INET;
+ const char *dst;
+
+ if (RTA_PAYLOAD(tb[NDA_DST]) == sizeof(struct in6_addr))
+ family = AF_INET6;
+
+ dst = format_host(family,
+ RTA_PAYLOAD(tb[NDA_DST]),
+ RTA_DATA(tb[NDA_DST]));
+
+ print_color_string(PRINT_ANY,
+ ifa_family_color(family),
+ "dst", "dst %s ", dst);
+ }
+
+ if (vid)
+ print_uint(PRINT_ANY,
+ "vlan", "vlan %hu ", vid);
+
+ if (tb[NDA_PORT])
+ print_uint(PRINT_ANY,
+ "port", "port %u ",
+ rta_getattr_be16(tb[NDA_PORT]));
+
+ if (tb[NDA_VNI])
+ print_uint(PRINT_ANY,
+ "vni", "vni %u ",
+ rta_getattr_u32(tb[NDA_VNI]));
+
+ if (tb[NDA_SRC_VNI])
+ print_uint(PRINT_ANY,
+ "src_vni", "src_vni %u ",
+ rta_getattr_u32(tb[NDA_SRC_VNI]));
+
+ if (tb[NDA_IFINDEX]) {
+ unsigned int ifindex = rta_getattr_u32(tb[NDA_IFINDEX]);
+
+ if (tb[NDA_LINK_NETNSID])
+ print_uint(PRINT_ANY,
+ "viaIfIndex", "via ifindex %u ",
+ ifindex);
+ else
+ print_string(PRINT_ANY,
+ "viaIf", "via %s ",
+ ll_index_to_name(ifindex));
+ }
+
+ if (tb[NDA_LINK_NETNSID])
+ print_uint(PRINT_ANY,
+ "linkNetNsId", "link-netnsid %d ",
+ rta_getattr_u32(tb[NDA_LINK_NETNSID]));
+
+ if (show_stats && tb[NDA_CACHEINFO])
+ fdb_print_stats(fp, RTA_DATA(tb[NDA_CACHEINFO]));
+
+ fdb_print_flags(fp, r->ndm_flags);
+
+
+ if (tb[NDA_MASTER])
+ print_string(PRINT_ANY, "master", "master %s ",
+ ll_index_to_name(rta_getattr_u32(tb[NDA_MASTER])));
+
+ print_string(PRINT_ANY, "state", "%s\n",
+ state_n2a(r->ndm_state));
+ close_json_object();
+ fflush(fp);
+ return 0;
+}
+
+static int fdb_linkdump_filter(struct nlmsghdr *nlh, int reqlen)
+{
+ int err;
+
+ if (filter_index) {
+ struct ifinfomsg *ifm = NLMSG_DATA(nlh);
+
+ ifm->ifi_index = filter_index;
+ }
+
+ if (filter_master) {
+ err = addattr32(nlh, reqlen, IFLA_MASTER, filter_master);
+ if (err)
+ return err;
+ }
+
+ return 0;
+}
+
+static int fdb_dump_filter(struct nlmsghdr *nlh, int reqlen)
+{
+ int err;
+
+ if (filter_index) {
+ struct ndmsg *ndm = NLMSG_DATA(nlh);
+
+ ndm->ndm_ifindex = filter_index;
+ }
+
+ if (filter_master) {
+ err = addattr32(nlh, reqlen, NDA_MASTER, filter_master);
+ if (err)
+ return err;
+ }
+
+ return 0;
+}
+
+static int fdb_show(int argc, char **argv)
+{
+ char *filter_dev = NULL;
+ char *br = NULL;
+ int rc;
+
+ while (argc > 0) {
+ if ((strcmp(*argv, "brport") == 0) || strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ filter_dev = *argv;
+ } else if (strcmp(*argv, "br") == 0) {
+ NEXT_ARG();
+ br = *argv;
+ } else if (strcmp(*argv, "vlan") == 0) {
+ NEXT_ARG();
+ if (filter_vlan)
+ duparg("vlan", *argv);
+ filter_vlan = atoi(*argv);
+ } else if (strcmp(*argv, "state") == 0) {
+ unsigned int state;
+
+ NEXT_ARG();
+ if (state_a2n(&state, *argv))
+ invarg("invalid state", *argv);
+ filter_state |= state;
+ } else {
+ if (matches(*argv, "help") == 0)
+ usage();
+ }
+ argc--; argv++;
+ }
+
+ if (br) {
+ int br_ifindex = ll_name_to_index(br);
+
+ if (br_ifindex == 0) {
+ fprintf(stderr, "Cannot find bridge device \"%s\"\n", br);
+ return -1;
+ }
+ filter_master = br_ifindex;
+ }
+
+ /*we'll keep around filter_dev for older kernels */
+ if (filter_dev) {
+ filter_index = ll_name_to_index(filter_dev);
+ if (!filter_index)
+ return nodev(filter_dev);
+ }
+
+ if (rth.flags & RTNL_HANDLE_F_STRICT_CHK)
+ rc = rtnl_neighdump_req(&rth, PF_BRIDGE, fdb_dump_filter);
+ else
+ rc = rtnl_fdb_linkdump_req_filter_fn(&rth, fdb_linkdump_filter);
+ if (rc < 0) {
+ perror("Cannot send dump request");
+ exit(1);
+ }
+
+ new_json_obj(json);
+ if (rtnl_dump_filter(&rth, print_fdb, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ exit(1);
+ }
+ delete_json_obj();
+ fflush(stdout);
+
+ return 0;
+}
+
+static int fdb_modify(int cmd, int flags, int argc, char **argv)
+{
+ struct {
+ struct nlmsghdr n;
+ struct ndmsg ndm;
+ char buf[256];
+ } req = {
+ .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg)),
+ .n.nlmsg_flags = NLM_F_REQUEST | flags,
+ .n.nlmsg_type = cmd,
+ .ndm.ndm_family = PF_BRIDGE,
+ .ndm.ndm_state = NUD_NOARP,
+ };
+ char *addr = NULL;
+ char *d = NULL;
+ char abuf[ETH_ALEN];
+ int dst_ok = 0;
+ inet_prefix dst;
+ unsigned long port = 0;
+ unsigned long vni = ~0;
+ unsigned long src_vni = ~0;
+ unsigned int via = 0;
+ char *endptr;
+ short vid = -1;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ d = *argv;
+ } else if (strcmp(*argv, "dst") == 0) {
+ NEXT_ARG();
+ if (dst_ok)
+ duparg2("dst", *argv);
+ get_addr(&dst, *argv, preferred_family);
+ dst_ok = 1;
+ } else if (strcmp(*argv, "port") == 0) {
+
+ NEXT_ARG();
+ port = strtoul(*argv, &endptr, 0);
+ if (endptr && *endptr) {
+ struct servent *pse;
+
+ pse = getservbyname(*argv, "udp");
+ if (!pse)
+ invarg("invalid port\n", *argv);
+ port = ntohs(pse->s_port);
+ } else if (port > 0xffff)
+ invarg("invalid port\n", *argv);
+ } else if (strcmp(*argv, "vni") == 0) {
+ NEXT_ARG();
+ vni = strtoul(*argv, &endptr, 0);
+ if ((endptr && *endptr) ||
+ (vni >> 24) || vni == ULONG_MAX)
+ invarg("invalid VNI\n", *argv);
+ } else if (strcmp(*argv, "src_vni") == 0) {
+ NEXT_ARG();
+ src_vni = strtoul(*argv, &endptr, 0);
+ if ((endptr && *endptr) ||
+ (src_vni >> 24) || src_vni == ULONG_MAX)
+ invarg("invalid src VNI\n", *argv);
+ } else if (strcmp(*argv, "via") == 0) {
+ NEXT_ARG();
+ via = ll_name_to_index(*argv);
+ if (!via)
+ exit(nodev(*argv));
+ } else if (strcmp(*argv, "self") == 0) {
+ req.ndm.ndm_flags |= NTF_SELF;
+ } else if (matches(*argv, "master") == 0) {
+ req.ndm.ndm_flags |= NTF_MASTER;
+ } else if (matches(*argv, "router") == 0) {
+ req.ndm.ndm_flags |= NTF_ROUTER;
+ } else if (matches(*argv, "local") == 0 ||
+ matches(*argv, "permanent") == 0) {
+ req.ndm.ndm_state |= NUD_PERMANENT;
+ } else if (matches(*argv, "temp") == 0 ||
+ matches(*argv, "static") == 0) {
+ req.ndm.ndm_state |= NUD_REACHABLE;
+ } else if (matches(*argv, "dynamic") == 0) {
+ req.ndm.ndm_state |= NUD_REACHABLE;
+ req.ndm.ndm_state &= ~NUD_NOARP;
+ } else if (matches(*argv, "vlan") == 0) {
+ if (vid >= 0)
+ duparg2("vlan", *argv);
+ NEXT_ARG();
+ vid = atoi(*argv);
+ } else if (matches(*argv, "use") == 0) {
+ req.ndm.ndm_flags |= NTF_USE;
+ } else if (matches(*argv, "extern_learn") == 0) {
+ req.ndm.ndm_flags |= NTF_EXT_LEARNED;
+ } else if (matches(*argv, "sticky") == 0) {
+ req.ndm.ndm_flags |= NTF_STICKY;
+ } else {
+ if (strcmp(*argv, "to") == 0)
+ NEXT_ARG();
+
+ if (matches(*argv, "help") == 0)
+ usage();
+ if (addr)
+ duparg2("to", *argv);
+ addr = *argv;
+ }
+ argc--; argv++;
+ }
+
+ if (d == NULL || addr == NULL) {
+ fprintf(stderr, "Device and address are required arguments.\n");
+ return -1;
+ }
+
+ /* Assume self */
+ if (!(req.ndm.ndm_flags&(NTF_SELF|NTF_MASTER)))
+ req.ndm.ndm_flags |= NTF_SELF;
+
+ /* Assume permanent */
+ if (!(req.ndm.ndm_state&(NUD_PERMANENT|NUD_REACHABLE)))
+ req.ndm.ndm_state |= NUD_PERMANENT;
+
+ if (sscanf(addr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
+ abuf, abuf+1, abuf+2,
+ abuf+3, abuf+4, abuf+5) != 6) {
+ fprintf(stderr, "Invalid mac address %s\n", addr);
+ return -1;
+ }
+
+ addattr_l(&req.n, sizeof(req), NDA_LLADDR, abuf, ETH_ALEN);
+ if (dst_ok)
+ addattr_l(&req.n, sizeof(req), NDA_DST, &dst.data, dst.bytelen);
+
+ if (vid >= 0)
+ addattr16(&req.n, sizeof(req), NDA_VLAN, vid);
+
+ if (port) {
+ unsigned short dport;
+
+ dport = htons((unsigned short)port);
+ addattr16(&req.n, sizeof(req), NDA_PORT, dport);
+ }
+ if (vni != ~0)
+ addattr32(&req.n, sizeof(req), NDA_VNI, vni);
+ if (src_vni != ~0)
+ addattr32(&req.n, sizeof(req), NDA_SRC_VNI, src_vni);
+ if (via)
+ addattr32(&req.n, sizeof(req), NDA_IFINDEX, via);
+
+ req.ndm.ndm_ifindex = ll_name_to_index(d);
+ if (!req.ndm.ndm_ifindex)
+ return nodev(d);
+
+ if (rtnl_talk(&rth, &req.n, NULL) < 0)
+ return -1;
+
+ return 0;
+}
+
+int do_fdb(int argc, char **argv)
+{
+ ll_init_map(&rth);
+
+ if (argc > 0) {
+ if (matches(*argv, "add") == 0)
+ return fdb_modify(RTM_NEWNEIGH, NLM_F_CREATE|NLM_F_EXCL, argc-1, argv+1);
+ if (matches(*argv, "append") == 0)
+ return fdb_modify(RTM_NEWNEIGH, NLM_F_CREATE|NLM_F_APPEND, argc-1, argv+1);
+ if (matches(*argv, "replace") == 0)
+ return fdb_modify(RTM_NEWNEIGH, NLM_F_CREATE|NLM_F_REPLACE, argc-1, argv+1);
+ if (matches(*argv, "delete") == 0)
+ return fdb_modify(RTM_DELNEIGH, 0, argc-1, argv+1);
+ if (matches(*argv, "show") == 0 ||
+ matches(*argv, "lst") == 0 ||
+ matches(*argv, "list") == 0)
+ return fdb_show(argc-1, argv+1);
+ if (matches(*argv, "help") == 0)
+ usage();
+ } else
+ return fdb_show(0, NULL);
+
+ fprintf(stderr, "Command \"%s\" is unknown, try \"bridge fdb help\".\n", *argv);
+ exit(-1);
+}
diff --git a/bridge/link.c b/bridge/link.c
new file mode 100644
index 0000000..074edf0
--- /dev/null
+++ b/bridge/link.c
@@ -0,0 +1,586 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <linux/if.h>
+#include <linux/if_bridge.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include "json_print.h"
+#include "libnetlink.h"
+#include "utils.h"
+#include "br_common.h"
+
+static unsigned int filter_index;
+
+static const char *port_states[] = {
+ [BR_STATE_DISABLED] = "disabled",
+ [BR_STATE_LISTENING] = "listening",
+ [BR_STATE_LEARNING] = "learning",
+ [BR_STATE_FORWARDING] = "forwarding",
+ [BR_STATE_BLOCKING] = "blocking",
+};
+
+static const char *hw_mode[] = {
+ "VEB", "VEPA"
+};
+
+static void print_link_flags(FILE *fp, unsigned int flags, unsigned int mdown)
+{
+ open_json_array(PRINT_ANY, is_json_context() ? "flags" : "<");
+ if (flags & IFF_UP && !(flags & IFF_RUNNING))
+ print_string(PRINT_ANY, NULL,
+ flags ? "%s," : "%s", "NO-CARRIER");
+ flags &= ~IFF_RUNNING;
+
+#define _PF(f) if (flags&IFF_##f) { \
+ flags &= ~IFF_##f ; \
+ print_string(PRINT_ANY, NULL, flags ? "%s," : "%s", #f); }
+ _PF(LOOPBACK);
+ _PF(BROADCAST);
+ _PF(POINTOPOINT);
+ _PF(MULTICAST);
+ _PF(NOARP);
+ _PF(ALLMULTI);
+ _PF(PROMISC);
+ _PF(MASTER);
+ _PF(SLAVE);
+ _PF(DEBUG);
+ _PF(DYNAMIC);
+ _PF(AUTOMEDIA);
+ _PF(PORTSEL);
+ _PF(NOTRAILERS);
+ _PF(UP);
+ _PF(LOWER_UP);
+ _PF(DORMANT);
+ _PF(ECHO);
+#undef _PF
+ if (flags)
+ print_hex(PRINT_ANY, NULL, "%x", flags);
+ if (mdown)
+ print_string(PRINT_ANY, NULL, ",%s", "M-DOWN");
+ close_json_array(PRINT_ANY, "> ");
+}
+
+static void print_portstate(__u8 state)
+{
+ if (state <= BR_STATE_BLOCKING)
+ print_string(PRINT_ANY, "state",
+ "state %s ", port_states[state]);
+ else
+ print_uint(PRINT_ANY, "state",
+ "state (%d) ", state);
+}
+
+static void print_onoff(FILE *fp, const char *flag, __u8 val)
+{
+ if (is_json_context())
+ print_bool(PRINT_JSON, flag, NULL, val);
+ else
+ fprintf(fp, "%s %s ", flag, val ? "on" : "off");
+}
+
+static void print_hwmode(__u16 mode)
+{
+ if (mode >= ARRAY_SIZE(hw_mode))
+ print_0xhex(PRINT_ANY, "hwmode",
+ "hwmode %#llx ", mode);
+ else
+ print_string(PRINT_ANY, "hwmode",
+ "hwmode %s ", hw_mode[mode]);
+}
+
+static void print_protinfo(FILE *fp, struct rtattr *attr)
+{
+ if (attr->rta_type & NLA_F_NESTED) {
+ struct rtattr *prtb[IFLA_BRPORT_MAX + 1];
+
+ parse_rtattr_nested(prtb, IFLA_BRPORT_MAX, attr);
+
+ if (prtb[IFLA_BRPORT_STATE])
+ print_portstate(rta_getattr_u8(prtb[IFLA_BRPORT_STATE]));
+
+ if (prtb[IFLA_BRPORT_PRIORITY])
+ print_uint(PRINT_ANY, "priority",
+ "priority %u ",
+ rta_getattr_u16(prtb[IFLA_BRPORT_PRIORITY]));
+
+ if (prtb[IFLA_BRPORT_COST])
+ print_uint(PRINT_ANY, "cost",
+ "cost %u ",
+ rta_getattr_u32(prtb[IFLA_BRPORT_COST]));
+
+ if (!show_details)
+ return;
+
+ if (!is_json_context())
+ fprintf(fp, "%s ", _SL_);
+
+ if (prtb[IFLA_BRPORT_MODE])
+ print_onoff(fp, "hairpin",
+ rta_getattr_u8(prtb[IFLA_BRPORT_MODE]));
+ if (prtb[IFLA_BRPORT_GUARD])
+ print_onoff(fp, "guard",
+ rta_getattr_u8(prtb[IFLA_BRPORT_GUARD]));
+ if (prtb[IFLA_BRPORT_PROTECT])
+ print_onoff(fp, "root_block",
+ rta_getattr_u8(prtb[IFLA_BRPORT_PROTECT]));
+ if (prtb[IFLA_BRPORT_FAST_LEAVE])
+ print_onoff(fp, "fastleave",
+ rta_getattr_u8(prtb[IFLA_BRPORT_FAST_LEAVE]));
+ if (prtb[IFLA_BRPORT_LEARNING])
+ print_onoff(fp, "learning",
+ rta_getattr_u8(prtb[IFLA_BRPORT_LEARNING]));
+ if (prtb[IFLA_BRPORT_LEARNING_SYNC])
+ print_onoff(fp, "learning_sync",
+ rta_getattr_u8(prtb[IFLA_BRPORT_LEARNING_SYNC]));
+ if (prtb[IFLA_BRPORT_UNICAST_FLOOD])
+ print_onoff(fp, "flood",
+ rta_getattr_u8(prtb[IFLA_BRPORT_UNICAST_FLOOD]));
+ if (prtb[IFLA_BRPORT_MCAST_FLOOD])
+ print_onoff(fp, "mcast_flood",
+ rta_getattr_u8(prtb[IFLA_BRPORT_MCAST_FLOOD]));
+ if (prtb[IFLA_BRPORT_MCAST_TO_UCAST])
+ print_onoff(fp, "mcast_to_unicast",
+ rta_getattr_u8(prtb[IFLA_BRPORT_MCAST_TO_UCAST]));
+ if (prtb[IFLA_BRPORT_NEIGH_SUPPRESS])
+ print_onoff(fp, "neigh_suppress",
+ rta_getattr_u8(prtb[IFLA_BRPORT_NEIGH_SUPPRESS]));
+ if (prtb[IFLA_BRPORT_VLAN_TUNNEL])
+ print_onoff(fp, "vlan_tunnel",
+ rta_getattr_u8(prtb[IFLA_BRPORT_VLAN_TUNNEL]));
+
+ if (prtb[IFLA_BRPORT_BACKUP_PORT]) {
+ int ifidx;
+
+ ifidx = rta_getattr_u32(prtb[IFLA_BRPORT_BACKUP_PORT]);
+ print_string(PRINT_ANY,
+ "backup_port", "backup_port %s ",
+ ll_index_to_name(ifidx));
+ }
+
+ if (prtb[IFLA_BRPORT_ISOLATED])
+ print_onoff(fp, "isolated",
+ rta_getattr_u8(prtb[IFLA_BRPORT_ISOLATED]));
+ } else
+ print_portstate(rta_getattr_u8(attr));
+}
+
+
+/*
+ * This is reported by HW devices that have some bridging
+ * capabilities.
+ */
+static void print_af_spec(struct rtattr *attr, int ifindex)
+{
+ struct rtattr *aftb[IFLA_BRIDGE_MAX+1];
+
+ parse_rtattr_nested(aftb, IFLA_BRIDGE_MAX, attr);
+
+ if (aftb[IFLA_BRIDGE_MODE])
+ print_hwmode(rta_getattr_u16(aftb[IFLA_BRIDGE_MODE]));
+
+ if (!show_details)
+ return;
+
+ if (aftb[IFLA_BRIDGE_VLAN_INFO])
+ print_vlan_info(aftb[IFLA_BRIDGE_VLAN_INFO], ifindex);
+}
+
+int print_linkinfo(struct nlmsghdr *n, void *arg)
+{
+ FILE *fp = arg;
+ struct ifinfomsg *ifi = NLMSG_DATA(n);
+ struct rtattr *tb[IFLA_MAX+1];
+ unsigned int m_flag = 0;
+ int len = n->nlmsg_len;
+ const char *name;
+
+ len -= NLMSG_LENGTH(sizeof(*ifi));
+ if (len < 0) {
+ fprintf(stderr, "Message too short!\n");
+ return -1;
+ }
+
+ if (!(ifi->ifi_family == AF_BRIDGE || ifi->ifi_family == AF_UNSPEC))
+ return 0;
+
+ if (filter_index && filter_index != ifi->ifi_index)
+ return 0;
+
+ parse_rtattr_flags(tb, IFLA_MAX, IFLA_RTA(ifi), len, NLA_F_NESTED);
+
+ name = get_ifname_rta(ifi->ifi_index, tb[IFLA_IFNAME]);
+ if (!name)
+ return -1;
+
+ open_json_object(NULL);
+ if (n->nlmsg_type == RTM_DELLINK)
+ print_bool(PRINT_ANY, "deleted", "Deleted ", true);
+
+ print_int(PRINT_ANY, "ifindex", "%d: ", ifi->ifi_index);
+ m_flag = print_name_and_link("%s: ", name, tb);
+ print_link_flags(fp, ifi->ifi_flags, m_flag);
+
+ if (tb[IFLA_MTU])
+ print_int(PRINT_ANY,
+ "mtu", "mtu %u ",
+ rta_getattr_u32(tb[IFLA_MTU]));
+
+ if (tb[IFLA_MASTER]) {
+ int master = rta_getattr_u32(tb[IFLA_MASTER]);
+
+ print_string(PRINT_ANY, "master", "master %s ",
+ ll_index_to_name(master));
+ }
+
+ if (tb[IFLA_PROTINFO])
+ print_protinfo(fp, tb[IFLA_PROTINFO]);
+
+ if (tb[IFLA_AF_SPEC])
+ print_af_spec(tb[IFLA_AF_SPEC], ifi->ifi_index);
+
+ print_string(PRINT_FP, NULL, "%s", "\n");
+ close_json_object();
+ fflush(fp);
+ return 0;
+}
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: bridge link set dev DEV [ cost COST ] [ priority PRIO ] [ state STATE ]\n"
+ " [ guard {on | off} ]\n"
+ " [ hairpin {on | off} ]\n"
+ " [ fastleave {on | off} ]\n"
+ " [ root_block {on | off} ]\n"
+ " [ learning {on | off} ]\n"
+ " [ learning_sync {on | off} ]\n"
+ " [ flood {on | off} ]\n"
+ " [ mcast_flood {on | off} ]\n"
+ " [ mcast_to_unicast {on | off} ]\n"
+ " [ neigh_suppress {on | off} ]\n"
+ " [ vlan_tunnel {on | off} ]\n"
+ " [ isolated {on | off} ]\n"
+ " [ hwmode {vepa | veb} ]\n"
+ " [ backup_port DEVICE ] [ nobackup_port ]\n"
+ " [ self ] [ master ]\n"
+ " bridge link show [dev DEV]\n");
+ exit(-1);
+}
+
+static bool on_off(char *arg, __s8 *attr, char *val)
+{
+ if (strcmp(val, "on") == 0)
+ *attr = 1;
+ else if (strcmp(val, "off") == 0)
+ *attr = 0;
+ else {
+ fprintf(stderr,
+ "Error: argument of \"%s\" must be \"on\" or \"off\"\n",
+ arg);
+ return false;
+ }
+
+ return true;
+}
+
+static int brlink_modify(int argc, char **argv)
+{
+ struct {
+ struct nlmsghdr n;
+ struct ifinfomsg ifm;
+ char buf[512];
+ } req = {
+ .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
+ .n.nlmsg_flags = NLM_F_REQUEST,
+ .n.nlmsg_type = RTM_SETLINK,
+ .ifm.ifi_family = PF_BRIDGE,
+ };
+ char *d = NULL;
+ int backup_port_idx = -1;
+ __s8 neigh_suppress = -1;
+ __s8 learning = -1;
+ __s8 learning_sync = -1;
+ __s8 flood = -1;
+ __s8 vlan_tunnel = -1;
+ __s8 mcast_flood = -1;
+ __s8 mcast_to_unicast = -1;
+ __s8 isolated = -1;
+ __s8 hairpin = -1;
+ __s8 bpdu_guard = -1;
+ __s8 fast_leave = -1;
+ __s8 root_block = -1;
+ __u32 cost = 0;
+ __s16 priority = -1;
+ __s8 state = -1;
+ __s16 mode = -1;
+ __u16 flags = 0;
+ struct rtattr *nest;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ d = *argv;
+ } else if (strcmp(*argv, "guard") == 0) {
+ NEXT_ARG();
+ if (!on_off("guard", &bpdu_guard, *argv))
+ return -1;
+ } else if (strcmp(*argv, "hairpin") == 0) {
+ NEXT_ARG();
+ if (!on_off("hairpin", &hairpin, *argv))
+ return -1;
+ } else if (strcmp(*argv, "fastleave") == 0) {
+ NEXT_ARG();
+ if (!on_off("fastleave", &fast_leave, *argv))
+ return -1;
+ } else if (strcmp(*argv, "root_block") == 0) {
+ NEXT_ARG();
+ if (!on_off("root_block", &root_block, *argv))
+ return -1;
+ } else if (strcmp(*argv, "learning") == 0) {
+ NEXT_ARG();
+ if (!on_off("learning", &learning, *argv))
+ return -1;
+ } else if (strcmp(*argv, "learning_sync") == 0) {
+ NEXT_ARG();
+ if (!on_off("learning_sync", &learning_sync, *argv))
+ return -1;
+ } else if (strcmp(*argv, "flood") == 0) {
+ NEXT_ARG();
+ if (!on_off("flood", &flood, *argv))
+ return -1;
+ } else if (strcmp(*argv, "mcast_flood") == 0) {
+ NEXT_ARG();
+ if (!on_off("mcast_flood", &mcast_flood, *argv))
+ return -1;
+ } else if (strcmp(*argv, "mcast_to_unicast") == 0) {
+ NEXT_ARG();
+ if (!on_off("mcast_to_unicast", &mcast_to_unicast, *argv))
+ return -1;
+ } else if (strcmp(*argv, "cost") == 0) {
+ NEXT_ARG();
+ cost = atoi(*argv);
+ } else if (strcmp(*argv, "priority") == 0) {
+ NEXT_ARG();
+ priority = atoi(*argv);
+ } else if (strcmp(*argv, "state") == 0) {
+ NEXT_ARG();
+ char *endptr;
+ size_t nstates = ARRAY_SIZE(port_states);
+
+ state = strtol(*argv, &endptr, 10);
+ if (!(**argv != '\0' && *endptr == '\0')) {
+ for (state = 0; state < nstates; state++)
+ if (strcmp(port_states[state], *argv) == 0)
+ break;
+ if (state == nstates) {
+ fprintf(stderr,
+ "Error: invalid STP port state\n");
+ return -1;
+ }
+ }
+ } else if (strcmp(*argv, "hwmode") == 0) {
+ NEXT_ARG();
+ flags = BRIDGE_FLAGS_SELF;
+ if (strcmp(*argv, "vepa") == 0)
+ mode = BRIDGE_MODE_VEPA;
+ else if (strcmp(*argv, "veb") == 0)
+ mode = BRIDGE_MODE_VEB;
+ else {
+ fprintf(stderr,
+ "Mode argument must be \"vepa\" or \"veb\".\n");
+ return -1;
+ }
+ } else if (strcmp(*argv, "self") == 0) {
+ flags |= BRIDGE_FLAGS_SELF;
+ } else if (strcmp(*argv, "master") == 0) {
+ flags |= BRIDGE_FLAGS_MASTER;
+ } else if (strcmp(*argv, "neigh_suppress") == 0) {
+ NEXT_ARG();
+ if (!on_off("neigh_suppress", &neigh_suppress,
+ *argv))
+ return -1;
+ } else if (strcmp(*argv, "vlan_tunnel") == 0) {
+ NEXT_ARG();
+ if (!on_off("vlan_tunnel", &vlan_tunnel,
+ *argv))
+ return -1;
+ } else if (strcmp(*argv, "isolated") == 0) {
+ NEXT_ARG();
+ if (!on_off("isolated", &isolated, *argv))
+ return -1;
+ } else if (strcmp(*argv, "backup_port") == 0) {
+ NEXT_ARG();
+ backup_port_idx = ll_name_to_index(*argv);
+ if (!backup_port_idx) {
+ fprintf(stderr, "Error: device %s does not exist\n",
+ *argv);
+ return -1;
+ }
+ } else if (strcmp(*argv, "nobackup_port") == 0) {
+ backup_port_idx = 0;
+ } else {
+ usage();
+ }
+ argc--; argv++;
+ }
+ if (d == NULL) {
+ fprintf(stderr, "Device is a required argument.\n");
+ return -1;
+ }
+
+
+ req.ifm.ifi_index = ll_name_to_index(d);
+ if (req.ifm.ifi_index == 0) {
+ fprintf(stderr, "Cannot find bridge device \"%s\"\n", d);
+ return -1;
+ }
+
+ /* Nested PROTINFO attribute. Contains: port flags, cost, priority and
+ * state.
+ */
+ nest = addattr_nest(&req.n, sizeof(req),
+ IFLA_PROTINFO | NLA_F_NESTED);
+ /* Flags first */
+ if (bpdu_guard >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_GUARD, bpdu_guard);
+ if (hairpin >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_MODE, hairpin);
+ if (fast_leave >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_FAST_LEAVE,
+ fast_leave);
+ if (root_block >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_PROTECT, root_block);
+ if (flood >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_UNICAST_FLOOD, flood);
+ if (mcast_flood >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_MCAST_FLOOD,
+ mcast_flood);
+ if (mcast_to_unicast >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_MCAST_TO_UCAST,
+ mcast_to_unicast);
+ if (learning >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_LEARNING, learning);
+ if (learning_sync >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_LEARNING_SYNC,
+ learning_sync);
+
+ if (cost > 0)
+ addattr32(&req.n, sizeof(req), IFLA_BRPORT_COST, cost);
+
+ if (priority >= 0)
+ addattr16(&req.n, sizeof(req), IFLA_BRPORT_PRIORITY, priority);
+
+ if (state >= 0)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_STATE, state);
+
+ if (neigh_suppress != -1)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_NEIGH_SUPPRESS,
+ neigh_suppress);
+ if (vlan_tunnel != -1)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_VLAN_TUNNEL,
+ vlan_tunnel);
+ if (isolated != -1)
+ addattr8(&req.n, sizeof(req), IFLA_BRPORT_ISOLATED, isolated);
+
+ if (backup_port_idx != -1)
+ addattr32(&req.n, sizeof(req), IFLA_BRPORT_BACKUP_PORT,
+ backup_port_idx);
+
+ addattr_nest_end(&req.n, nest);
+
+ /* IFLA_AF_SPEC nested attribute. Contains IFLA_BRIDGE_FLAGS that
+ * designates master or self operation and IFLA_BRIDGE_MODE
+ * for hw 'vepa' or 'veb' operation modes. The hwmodes are
+ * only valid in 'self' mode on some devices so far.
+ */
+ if (mode >= 0 || flags > 0) {
+ nest = addattr_nest(&req.n, sizeof(req), IFLA_AF_SPEC);
+
+ if (flags > 0)
+ addattr16(&req.n, sizeof(req), IFLA_BRIDGE_FLAGS, flags);
+
+ if (mode >= 0)
+ addattr16(&req.n, sizeof(req), IFLA_BRIDGE_MODE, mode);
+
+ addattr_nest_end(&req.n, nest);
+ }
+
+ if (rtnl_talk(&rth, &req.n, NULL) < 0)
+ return -1;
+
+ return 0;
+}
+
+static int brlink_show(int argc, char **argv)
+{
+ char *filter_dev = NULL;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ if (filter_dev)
+ duparg("dev", *argv);
+ filter_dev = *argv;
+ }
+ argc--; argv++;
+ }
+
+ if (filter_dev) {
+ filter_index = ll_name_to_index(filter_dev);
+ if (!filter_index)
+ return nodev(filter_dev);
+ }
+
+ if (show_details) {
+ if (rtnl_linkdump_req_filter(&rth, PF_BRIDGE,
+ (compress_vlans ?
+ RTEXT_FILTER_BRVLAN_COMPRESSED :
+ RTEXT_FILTER_BRVLAN)) < 0) {
+ perror("Cannon send dump request");
+ exit(1);
+ }
+ } else {
+ if (rtnl_linkdump_req(&rth, PF_BRIDGE) < 0) {
+ perror("Cannon send dump request");
+ exit(1);
+ }
+ }
+
+ new_json_obj(json);
+ if (rtnl_dump_filter(&rth, print_linkinfo, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ exit(1);
+ }
+
+ delete_json_obj();
+ fflush(stdout);
+ return 0;
+}
+
+int do_link(int argc, char **argv)
+{
+ ll_init_map(&rth);
+ if (argc > 0) {
+ if (matches(*argv, "set") == 0 ||
+ matches(*argv, "change") == 0)
+ return brlink_modify(argc-1, argv+1);
+ if (matches(*argv, "show") == 0 ||
+ matches(*argv, "lst") == 0 ||
+ matches(*argv, "list") == 0)
+ return brlink_show(argc-1, argv+1);
+ if (matches(*argv, "help") == 0)
+ usage();
+ } else
+ return brlink_show(0, NULL);
+
+ fprintf(stderr, "Command \"%s\" is unknown, try \"bridge link help\".\n", *argv);
+ exit(-1);
+}
diff --git a/bridge/mdb.c b/bridge/mdb.c
new file mode 100644
index 0000000..928ae56
--- /dev/null
+++ b/bridge/mdb.c
@@ -0,0 +1,462 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Get mdb table with netlink
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <linux/if_bridge.h>
+#include <linux/if_ether.h>
+#include <string.h>
+#include <arpa/inet.h>
+
+#include "libnetlink.h"
+#include "br_common.h"
+#include "rt_names.h"
+#include "utils.h"
+#include "json_print.h"
+
+#ifndef MDBA_RTA
+#define MDBA_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct br_port_msg))))
+#endif
+
+static unsigned int filter_index, filter_vlan;
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: bridge mdb { add | del } dev DEV port PORT grp GROUP [permanent | temp] [vid VID]\n"
+ " bridge mdb {show} [ dev DEV ] [ vid VID ]\n");
+ exit(-1);
+}
+
+static bool is_temp_mcast_rtr(__u8 type)
+{
+ return type == MDB_RTR_TYPE_TEMP_QUERY || type == MDB_RTR_TYPE_TEMP;
+}
+
+static const char *format_timer(__u32 ticks)
+{
+ struct timeval tv;
+ static char tbuf[32];
+
+ __jiffies_to_tv(&tv, ticks);
+ snprintf(tbuf, sizeof(tbuf), "%4lu.%.2lu",
+ (unsigned long)tv.tv_sec,
+ (unsigned long)tv.tv_usec / 10000);
+
+ return tbuf;
+}
+
+static void __print_router_port_stats(FILE *f, struct rtattr *pattr)
+{
+ struct rtattr *tb[MDBA_ROUTER_PATTR_MAX + 1];
+
+ parse_rtattr(tb, MDBA_ROUTER_PATTR_MAX, MDB_RTR_RTA(RTA_DATA(pattr)),
+ RTA_PAYLOAD(pattr) - RTA_ALIGN(sizeof(uint32_t)));
+
+ if (tb[MDBA_ROUTER_PATTR_TIMER]) {
+ __u32 timer = rta_getattr_u32(tb[MDBA_ROUTER_PATTR_TIMER]);
+
+ print_string(PRINT_ANY, "timer", " %s",
+ format_timer(timer));
+ }
+
+ if (tb[MDBA_ROUTER_PATTR_TYPE]) {
+ __u8 type = rta_getattr_u8(tb[MDBA_ROUTER_PATTR_TYPE]);
+
+ print_string(PRINT_ANY, "type", " %s",
+ is_temp_mcast_rtr(type) ? "temp" : "permanent");
+ }
+}
+
+static void br_print_router_ports(FILE *f, struct rtattr *attr,
+ const char *brifname)
+{
+ int rem = RTA_PAYLOAD(attr);
+ struct rtattr *i;
+
+ if (is_json_context())
+ open_json_array(PRINT_JSON, brifname);
+ else if (!show_stats)
+ fprintf(f, "router ports on %s: ", brifname);
+
+ for (i = RTA_DATA(attr); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
+ uint32_t *port_ifindex = RTA_DATA(i);
+ const char *port_ifname = ll_index_to_name(*port_ifindex);
+
+ if (is_json_context()) {
+ open_json_object(NULL);
+ print_string(PRINT_JSON, "port", NULL, port_ifname);
+
+ if (show_stats)
+ __print_router_port_stats(f, i);
+ close_json_object();
+ } else if (show_stats) {
+ fprintf(f, "router ports on %s: %s",
+ brifname, port_ifname);
+
+ __print_router_port_stats(f, i);
+ fprintf(f, "\n");
+ } else {
+ fprintf(f, "%s ", port_ifname);
+ }
+ }
+
+ if (!show_stats)
+ print_nl();
+
+ close_json_array(PRINT_JSON, NULL);
+}
+
+static void print_mdb_entry(FILE *f, int ifindex, const struct br_mdb_entry *e,
+ struct nlmsghdr *n, struct rtattr **tb)
+{
+ SPRINT_BUF(abuf);
+ const char *dev;
+ const void *src;
+ int af;
+
+ if (filter_vlan && e->vid != filter_vlan)
+ return;
+
+ af = e->addr.proto == htons(ETH_P_IP) ? AF_INET : AF_INET6;
+ src = af == AF_INET ? (const void *)&e->addr.u.ip4 :
+ (const void *)&e->addr.u.ip6;
+ dev = ll_index_to_name(ifindex);
+
+ open_json_object(NULL);
+
+ print_int(PRINT_JSON, "index", NULL, ifindex);
+ print_color_string(PRINT_ANY, COLOR_IFNAME, "dev", "dev %s", dev);
+ print_string(PRINT_ANY, "port", " port %s",
+ ll_index_to_name(e->ifindex));
+
+ print_color_string(PRINT_ANY, ifa_family_color(af),
+ "grp", " grp %s",
+ inet_ntop(af, src, abuf, sizeof(abuf)));
+
+ print_string(PRINT_ANY, "state", " %s",
+ (e->state & MDB_PERMANENT) ? "permanent" : "temp");
+
+ open_json_array(PRINT_JSON, "flags");
+ if (e->flags & MDB_FLAGS_OFFLOAD)
+ print_string(PRINT_ANY, NULL, " %s", "offload");
+ close_json_array(PRINT_JSON, NULL);
+
+ if (e->vid)
+ print_uint(PRINT_ANY, "vid", " vid %u", e->vid);
+
+ if (show_stats && tb && tb[MDBA_MDB_EATTR_TIMER]) {
+ __u32 timer = rta_getattr_u32(tb[MDBA_MDB_EATTR_TIMER]);
+
+ print_string(PRINT_ANY, "timer", " %s",
+ format_timer(timer));
+ }
+
+ print_nl();
+ close_json_object();
+}
+
+static void br_print_mdb_entry(FILE *f, int ifindex, struct rtattr *attr,
+ struct nlmsghdr *n)
+{
+ struct rtattr *etb[MDBA_MDB_EATTR_MAX + 1];
+ struct br_mdb_entry *e;
+ struct rtattr *i;
+ int rem;
+
+ rem = RTA_PAYLOAD(attr);
+ for (i = RTA_DATA(attr); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
+ e = RTA_DATA(i);
+ parse_rtattr(etb, MDBA_MDB_EATTR_MAX, MDB_RTA(RTA_DATA(i)),
+ RTA_PAYLOAD(i) - RTA_ALIGN(sizeof(*e)));
+ print_mdb_entry(f, ifindex, e, n, etb);
+ }
+}
+
+static void print_mdb_entries(FILE *fp, struct nlmsghdr *n,
+ int ifindex, struct rtattr *mdb)
+{
+ int rem = RTA_PAYLOAD(mdb);
+ struct rtattr *i;
+
+ for (i = RTA_DATA(mdb); RTA_OK(i, rem); i = RTA_NEXT(i, rem))
+ br_print_mdb_entry(fp, ifindex, i, n);
+}
+
+static void print_router_entries(FILE *fp, struct nlmsghdr *n,
+ int ifindex, struct rtattr *router)
+{
+ const char *brifname = ll_index_to_name(ifindex);
+
+ if (n->nlmsg_type == RTM_GETMDB) {
+ if (show_details)
+ br_print_router_ports(fp, router, brifname);
+ } else {
+ struct rtattr *i = RTA_DATA(router);
+ uint32_t *port_ifindex = RTA_DATA(i);
+ const char *port_name = ll_index_to_name(*port_ifindex);
+
+ if (is_json_context()) {
+ open_json_array(PRINT_JSON, brifname);
+ open_json_object(NULL);
+
+ print_string(PRINT_JSON, "port", NULL,
+ port_name);
+ close_json_object();
+ close_json_array(PRINT_JSON, NULL);
+ } else {
+ fprintf(fp, "router port dev %s master %s\n",
+ port_name, brifname);
+ }
+ }
+}
+
+static int __parse_mdb_nlmsg(struct nlmsghdr *n, struct rtattr **tb)
+{
+ struct br_port_msg *r = NLMSG_DATA(n);
+ int len = n->nlmsg_len;
+
+ if (n->nlmsg_type != RTM_GETMDB &&
+ n->nlmsg_type != RTM_NEWMDB &&
+ n->nlmsg_type != RTM_DELMDB) {
+ fprintf(stderr,
+ "Not RTM_GETMDB, RTM_NEWMDB or RTM_DELMDB: %08x %08x %08x\n",
+ n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
+
+ return 0;
+ }
+
+ len -= NLMSG_LENGTH(sizeof(*r));
+ if (len < 0) {
+ fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
+ return -1;
+ }
+
+ if (filter_index && filter_index != r->ifindex)
+ return 0;
+
+ parse_rtattr(tb, MDBA_MAX, MDBA_RTA(r), n->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
+
+ return 1;
+}
+
+static int print_mdbs(struct nlmsghdr *n, void *arg)
+{
+ struct br_port_msg *r = NLMSG_DATA(n);
+ struct rtattr *tb[MDBA_MAX+1];
+ FILE *fp = arg;
+ int ret;
+
+ ret = __parse_mdb_nlmsg(n, tb);
+ if (ret != 1)
+ return ret;
+
+ if (tb[MDBA_MDB])
+ print_mdb_entries(fp, n, r->ifindex, tb[MDBA_MDB]);
+
+ return 0;
+}
+
+static int print_rtrs(struct nlmsghdr *n, void *arg)
+{
+ struct br_port_msg *r = NLMSG_DATA(n);
+ struct rtattr *tb[MDBA_MAX+1];
+ FILE *fp = arg;
+ int ret;
+
+ ret = __parse_mdb_nlmsg(n, tb);
+ if (ret != 1)
+ return ret;
+
+ if (tb[MDBA_ROUTER])
+ print_router_entries(fp, n, r->ifindex, tb[MDBA_ROUTER]);
+
+ return 0;
+}
+
+int print_mdb_mon(struct nlmsghdr *n, void *arg)
+{
+ struct br_port_msg *r = NLMSG_DATA(n);
+ struct rtattr *tb[MDBA_MAX+1];
+ FILE *fp = arg;
+ int ret;
+
+ ret = __parse_mdb_nlmsg(n, tb);
+ if (ret != 1)
+ return ret;
+
+ if (n->nlmsg_type == RTM_DELMDB)
+ print_bool(PRINT_ANY, "deleted", "Deleted ", true);
+
+ if (tb[MDBA_MDB])
+ print_mdb_entries(fp, n, r->ifindex, tb[MDBA_MDB]);
+
+ if (tb[MDBA_ROUTER])
+ print_router_entries(fp, n, r->ifindex, tb[MDBA_ROUTER]);
+
+ return 0;
+}
+
+static int mdb_show(int argc, char **argv)
+{
+ char *filter_dev = NULL;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ if (filter_dev)
+ duparg("dev", *argv);
+ filter_dev = *argv;
+ } else if (strcmp(*argv, "vid") == 0) {
+ NEXT_ARG();
+ if (filter_vlan)
+ duparg("vid", *argv);
+ filter_vlan = atoi(*argv);
+ }
+ argc--; argv++;
+ }
+
+ if (filter_dev) {
+ filter_index = ll_name_to_index(filter_dev);
+ if (!filter_index)
+ return nodev(filter_dev);
+ }
+
+ new_json_obj(json);
+ open_json_object(NULL);
+
+ /* get mdb entries */
+ if (rtnl_mdbdump_req(&rth, PF_BRIDGE) < 0) {
+ perror("Cannot send dump request");
+ return -1;
+ }
+
+ open_json_array(PRINT_JSON, "mdb");
+ if (rtnl_dump_filter(&rth, print_mdbs, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ return -1;
+ }
+ close_json_array(PRINT_JSON, NULL);
+
+ /* get router ports */
+ if (rtnl_mdbdump_req(&rth, PF_BRIDGE) < 0) {
+ perror("Cannot send dump request");
+ return -1;
+ }
+
+ open_json_object("router");
+ if (rtnl_dump_filter(&rth, print_rtrs, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ return -1;
+ }
+ close_json_object();
+
+ close_json_object();
+ delete_json_obj();
+ fflush(stdout);
+
+ return 0;
+}
+
+static int mdb_modify(int cmd, int flags, int argc, char **argv)
+{
+ struct {
+ struct nlmsghdr n;
+ struct br_port_msg bpm;
+ char buf[1024];
+ } req = {
+ .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct br_port_msg)),
+ .n.nlmsg_flags = NLM_F_REQUEST | flags,
+ .n.nlmsg_type = cmd,
+ .bpm.family = PF_BRIDGE,
+ };
+ struct br_mdb_entry entry = {};
+ char *d = NULL, *p = NULL, *grp = NULL;
+ short vid = 0;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ d = *argv;
+ } else if (strcmp(*argv, "grp") == 0) {
+ NEXT_ARG();
+ grp = *argv;
+ } else if (strcmp(*argv, "port") == 0) {
+ NEXT_ARG();
+ p = *argv;
+ } else if (strcmp(*argv, "permanent") == 0) {
+ if (cmd == RTM_NEWMDB)
+ entry.state |= MDB_PERMANENT;
+ } else if (strcmp(*argv, "temp") == 0) {
+ ;/* nothing */
+ } else if (strcmp(*argv, "vid") == 0) {
+ NEXT_ARG();
+ vid = atoi(*argv);
+ } else {
+ if (matches(*argv, "help") == 0)
+ usage();
+ }
+ argc--; argv++;
+ }
+
+ if (d == NULL || grp == NULL || p == NULL) {
+ fprintf(stderr, "Device, group address and port name are required arguments.\n");
+ return -1;
+ }
+
+ req.bpm.ifindex = ll_name_to_index(d);
+ if (!req.bpm.ifindex)
+ return nodev(d);
+
+ entry.ifindex = ll_name_to_index(p);
+ if (!entry.ifindex)
+ return nodev(p);
+
+ if (!inet_pton(AF_INET, grp, &entry.addr.u.ip4)) {
+ if (!inet_pton(AF_INET6, grp, &entry.addr.u.ip6)) {
+ fprintf(stderr, "Invalid address \"%s\"\n", grp);
+ return -1;
+ } else
+ entry.addr.proto = htons(ETH_P_IPV6);
+ } else
+ entry.addr.proto = htons(ETH_P_IP);
+
+ entry.vid = vid;
+ addattr_l(&req.n, sizeof(req), MDBA_SET_ENTRY, &entry, sizeof(entry));
+
+ if (rtnl_talk(&rth, &req.n, NULL) < 0)
+ return -1;
+
+ return 0;
+}
+
+int do_mdb(int argc, char **argv)
+{
+ ll_init_map(&rth);
+
+ if (argc > 0) {
+ if (matches(*argv, "add") == 0)
+ return mdb_modify(RTM_NEWMDB, NLM_F_CREATE|NLM_F_EXCL, argc-1, argv+1);
+ if (matches(*argv, "delete") == 0)
+ return mdb_modify(RTM_DELMDB, 0, argc-1, argv+1);
+
+ if (matches(*argv, "show") == 0 ||
+ matches(*argv, "lst") == 0 ||
+ matches(*argv, "list") == 0)
+ return mdb_show(argc-1, argv+1);
+ if (matches(*argv, "help") == 0)
+ usage();
+ } else
+ return mdb_show(0, NULL);
+
+ fprintf(stderr, "Command \"%s\" is unknown, try \"bridge mdb help\".\n", *argv);
+ exit(-1);
+}
diff --git a/bridge/monitor.c b/bridge/monitor.c
new file mode 100644
index 0000000..08439a6
--- /dev/null
+++ b/bridge/monitor.c
@@ -0,0 +1,143 @@
+/*
+ * brmonitor.c "bridge monitor"
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Stephen Hemminger <shemminger@vyatta.com>
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <time.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <linux/if_bridge.h>
+#include <linux/neighbour.h>
+#include <string.h>
+
+#include "utils.h"
+#include "br_common.h"
+
+
+static void usage(void) __attribute__((noreturn));
+static int prefix_banner;
+
+static void usage(void)
+{
+ fprintf(stderr, "Usage: bridge monitor [file | link | fdb | mdb | all]\n");
+ exit(-1);
+}
+
+static int accept_msg(struct rtnl_ctrl_data *ctrl,
+ struct nlmsghdr *n, void *arg)
+{
+ FILE *fp = arg;
+
+ if (timestamp)
+ print_timestamp(fp);
+
+ switch (n->nlmsg_type) {
+ case RTM_NEWLINK:
+ case RTM_DELLINK:
+ if (prefix_banner)
+ fprintf(fp, "[LINK]");
+
+ return print_linkinfo(n, arg);
+
+ case RTM_NEWNEIGH:
+ case RTM_DELNEIGH:
+ if (prefix_banner)
+ fprintf(fp, "[NEIGH]");
+ return print_fdb(n, arg);
+
+ case RTM_NEWMDB:
+ case RTM_DELMDB:
+ if (prefix_banner)
+ fprintf(fp, "[MDB]");
+ return print_mdb_mon(n, arg);
+
+ case NLMSG_TSTAMP:
+ print_nlmsg_timestamp(fp, n);
+ return 0;
+
+ default:
+ return 0;
+ }
+}
+
+int do_monitor(int argc, char **argv)
+{
+ char *file = NULL;
+ unsigned int groups = ~RTMGRP_TC;
+ int llink = 0;
+ int lneigh = 0;
+ int lmdb = 0;
+
+ rtnl_close(&rth);
+
+ while (argc > 0) {
+ if (matches(*argv, "file") == 0) {
+ NEXT_ARG();
+ file = *argv;
+ } else if (matches(*argv, "link") == 0) {
+ llink = 1;
+ groups = 0;
+ } else if (matches(*argv, "fdb") == 0) {
+ lneigh = 1;
+ groups = 0;
+ } else if (matches(*argv, "mdb") == 0) {
+ lmdb = 1;
+ groups = 0;
+ } else if (strcmp(*argv, "all") == 0) {
+ groups = ~RTMGRP_TC;
+ prefix_banner = 1;
+ } else if (matches(*argv, "help") == 0) {
+ usage();
+ } else {
+ fprintf(stderr, "Argument \"%s\" is unknown, try \"bridge monitor help\".\n", *argv);
+ exit(-1);
+ }
+ argc--; argv++;
+ }
+
+ if (llink)
+ groups |= nl_mgrp(RTNLGRP_LINK);
+
+ if (lneigh) {
+ groups |= nl_mgrp(RTNLGRP_NEIGH);
+ }
+
+ if (lmdb) {
+ groups |= nl_mgrp(RTNLGRP_MDB);
+ }
+
+ if (file) {
+ FILE *fp;
+ int err;
+
+ fp = fopen(file, "r");
+ if (fp == NULL) {
+ perror("Cannot fopen");
+ exit(-1);
+ }
+ err = rtnl_from_file(fp, accept_msg, stdout);
+ fclose(fp);
+ return err;
+ }
+
+ if (rtnl_open(&rth, groups) < 0)
+ exit(1);
+ ll_init_map(&rth);
+
+ if (rtnl_listen(&rth, accept_msg, stdout) < 0)
+ exit(2);
+
+ return 0;
+}
diff --git a/bridge/vlan.c b/bridge/vlan.c
new file mode 100644
index 0000000..6d33b0a
--- /dev/null
+++ b/bridge/vlan.c
@@ -0,0 +1,693 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <linux/if_bridge.h>
+#include <linux/if_ether.h>
+#include <string.h>
+
+#include "json_print.h"
+#include "libnetlink.h"
+#include "br_common.h"
+#include "utils.h"
+
+static unsigned int filter_index, filter_vlan;
+static int show_vlan_tunnel_info = 0;
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: bridge vlan { add | del } vid VLAN_ID dev DEV [ tunnel_info id TUNNEL_ID ]\n"
+ " [ pvid ] [ untagged ]\n"
+ " [ self ] [ master ]\n"
+ " bridge vlan { show } [ dev DEV ] [ vid VLAN_ID ]\n"
+ " bridge vlan { tunnelshow } [ dev DEV ] [ vid VLAN_ID ]\n");
+ exit(-1);
+}
+
+static int parse_tunnel_info(int *argcp, char ***argvp, __u32 *tun_id_start,
+ __u32 *tun_id_end)
+{
+ char **argv = *argvp;
+ int argc = *argcp;
+ char *t;
+
+ NEXT_ARG();
+ if (!matches(*argv, "id")) {
+ NEXT_ARG();
+ t = strchr(*argv, '-');
+ if (t) {
+ *t = '\0';
+ if (get_u32(tun_id_start, *argv, 0) ||
+ *tun_id_start >= 1u << 24)
+ invarg("invalid tun id", *argv);
+ if (get_u32(tun_id_end, t + 1, 0) ||
+ *tun_id_end >= 1u << 24)
+ invarg("invalid tun id", *argv);
+
+ } else {
+ if (get_u32(tun_id_start, *argv, 0) ||
+ *tun_id_start >= 1u << 24)
+ invarg("invalid tun id", *argv);
+ }
+ } else {
+ invarg("tunnel id expected", *argv);
+ }
+
+ *argcp = argc;
+ *argvp = argv;
+
+ return 0;
+}
+
+static int add_tunnel_info(struct nlmsghdr *n, int reqsize,
+ __u16 vid, __u32 tun_id, __u16 flags)
+{
+ struct rtattr *tinfo;
+
+ tinfo = addattr_nest(n, reqsize, IFLA_BRIDGE_VLAN_TUNNEL_INFO);
+ addattr32(n, reqsize, IFLA_BRIDGE_VLAN_TUNNEL_ID, tun_id);
+ addattr32(n, reqsize, IFLA_BRIDGE_VLAN_TUNNEL_VID, vid);
+ addattr32(n, reqsize, IFLA_BRIDGE_VLAN_TUNNEL_FLAGS, flags);
+
+ addattr_nest_end(n, tinfo);
+
+ return 0;
+}
+
+static int add_tunnel_info_range(struct nlmsghdr *n, int reqsize,
+ __u16 vid_start, int16_t vid_end,
+ __u32 tun_id_start, __u32 tun_id_end)
+{
+ if (vid_end != -1 && (vid_end - vid_start) > 0) {
+ add_tunnel_info(n, reqsize, vid_start, tun_id_start,
+ BRIDGE_VLAN_INFO_RANGE_BEGIN);
+
+ add_tunnel_info(n, reqsize, vid_end, tun_id_end,
+ BRIDGE_VLAN_INFO_RANGE_END);
+ } else {
+ add_tunnel_info(n, reqsize, vid_start, tun_id_start, 0);
+ }
+
+ return 0;
+}
+
+static int add_vlan_info_range(struct nlmsghdr *n, int reqsize, __u16 vid_start,
+ int16_t vid_end, __u16 flags)
+{
+ struct bridge_vlan_info vinfo = {};
+
+ vinfo.flags = flags;
+ vinfo.vid = vid_start;
+ if (vid_end != -1) {
+ /* send vlan range start */
+ addattr_l(n, reqsize, IFLA_BRIDGE_VLAN_INFO, &vinfo,
+ sizeof(vinfo));
+ vinfo.flags &= ~BRIDGE_VLAN_INFO_RANGE_BEGIN;
+
+ /* Now send the vlan range end */
+ vinfo.flags |= BRIDGE_VLAN_INFO_RANGE_END;
+ vinfo.vid = vid_end;
+ addattr_l(n, reqsize, IFLA_BRIDGE_VLAN_INFO, &vinfo,
+ sizeof(vinfo));
+ } else {
+ addattr_l(n, reqsize, IFLA_BRIDGE_VLAN_INFO, &vinfo,
+ sizeof(vinfo));
+ }
+
+ return 0;
+}
+
+static int vlan_modify(int cmd, int argc, char **argv)
+{
+ struct {
+ struct nlmsghdr n;
+ struct ifinfomsg ifm;
+ char buf[1024];
+ } req = {
+ .n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)),
+ .n.nlmsg_flags = NLM_F_REQUEST,
+ .n.nlmsg_type = cmd,
+ .ifm.ifi_family = PF_BRIDGE,
+ };
+ char *d = NULL;
+ short vid = -1;
+ short vid_end = -1;
+ struct rtattr *afspec;
+ struct bridge_vlan_info vinfo = {};
+ bool tunnel_info_set = false;
+ unsigned short flags = 0;
+ __u32 tun_id_start = 0;
+ __u32 tun_id_end = 0;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ d = *argv;
+ } else if (strcmp(*argv, "vid") == 0) {
+ char *p;
+
+ NEXT_ARG();
+ p = strchr(*argv, '-');
+ if (p) {
+ *p = '\0';
+ p++;
+ vid = atoi(*argv);
+ vid_end = atoi(p);
+ vinfo.flags |= BRIDGE_VLAN_INFO_RANGE_BEGIN;
+ } else {
+ vid = atoi(*argv);
+ }
+ } else if (strcmp(*argv, "self") == 0) {
+ flags |= BRIDGE_FLAGS_SELF;
+ } else if (strcmp(*argv, "master") == 0) {
+ flags |= BRIDGE_FLAGS_MASTER;
+ } else if (strcmp(*argv, "pvid") == 0) {
+ vinfo.flags |= BRIDGE_VLAN_INFO_PVID;
+ } else if (strcmp(*argv, "untagged") == 0) {
+ vinfo.flags |= BRIDGE_VLAN_INFO_UNTAGGED;
+ } else if (strcmp(*argv, "tunnel_info") == 0) {
+ if (parse_tunnel_info(&argc, &argv,
+ &tun_id_start,
+ &tun_id_end))
+ return -1;
+ tunnel_info_set = true;
+ } else {
+ if (matches(*argv, "help") == 0)
+ NEXT_ARG();
+ }
+ argc--; argv++;
+ }
+
+ if (d == NULL || vid == -1) {
+ fprintf(stderr, "Device and VLAN ID are required arguments.\n");
+ return -1;
+ }
+
+ req.ifm.ifi_index = ll_name_to_index(d);
+ if (req.ifm.ifi_index == 0) {
+ fprintf(stderr, "Cannot find bridge device \"%s\"\n", d);
+ return -1;
+ }
+
+ if (vid >= 4096) {
+ fprintf(stderr, "Invalid VLAN ID \"%hu\"\n", vid);
+ return -1;
+ }
+
+ if (vinfo.flags & BRIDGE_VLAN_INFO_RANGE_BEGIN) {
+ if (vid_end == -1 || vid_end >= 4096 || vid >= vid_end) {
+ fprintf(stderr, "Invalid VLAN range \"%hu-%hu\"\n",
+ vid, vid_end);
+ return -1;
+ }
+ if (vinfo.flags & BRIDGE_VLAN_INFO_PVID) {
+ fprintf(stderr,
+ "pvid cannot be configured for a vlan range\n");
+ return -1;
+ }
+ }
+
+ afspec = addattr_nest(&req.n, sizeof(req), IFLA_AF_SPEC);
+
+ if (flags)
+ addattr16(&req.n, sizeof(req), IFLA_BRIDGE_FLAGS, flags);
+
+ if (tunnel_info_set)
+ add_tunnel_info_range(&req.n, sizeof(req), vid, vid_end,
+ tun_id_start, tun_id_end);
+ else
+ add_vlan_info_range(&req.n, sizeof(req), vid, vid_end,
+ vinfo.flags);
+
+ addattr_nest_end(&req.n, afspec);
+
+ if (rtnl_talk(&rth, &req.n, NULL) < 0)
+ return -1;
+
+ return 0;
+}
+
+/* In order to use this function for both filtering and non-filtering cases
+ * we need to make it a tristate:
+ * return -1 - if filtering we've gone over so don't continue
+ * return 0 - skip entry and continue (applies to range start or to entries
+ * which are less than filter_vlan)
+ * return 1 - print the entry and continue
+ */
+static int filter_vlan_check(__u16 vid, __u16 flags)
+{
+ /* if we're filtering we should stop on the first greater entry */
+ if (filter_vlan && vid > filter_vlan &&
+ !(flags & BRIDGE_VLAN_INFO_RANGE_END))
+ return -1;
+ if ((flags & BRIDGE_VLAN_INFO_RANGE_BEGIN) ||
+ vid < filter_vlan)
+ return 0;
+
+ return 1;
+}
+
+static void open_vlan_port(int ifi_index, const char *fmt)
+{
+ open_json_object(NULL);
+ print_color_string(PRINT_ANY, COLOR_IFNAME, "ifname", fmt,
+ ll_index_to_name(ifi_index));
+ open_json_array(PRINT_JSON, "vlans");
+}
+
+static void close_vlan_port(void)
+{
+ close_json_array(PRINT_JSON, NULL);
+ close_json_object();
+}
+
+static void print_range(const char *name, __u16 start, __u16 id)
+{
+ char end[64];
+
+ snprintf(end, sizeof(end), "%sEnd", name);
+
+ print_hu(PRINT_ANY, name, "\t %hu", start);
+ if (start != id)
+ print_hu(PRINT_ANY, end, "-%hu", id);
+
+}
+
+static void print_vlan_tunnel_info(FILE *fp, struct rtattr *tb, int ifindex)
+{
+ struct rtattr *i, *list = tb;
+ int rem = RTA_PAYLOAD(list);
+ __u16 last_vid_start = 0;
+ __u32 last_tunid_start = 0;
+
+ if (!filter_vlan)
+ open_vlan_port(ifindex, "%s");
+
+ open_json_array(PRINT_JSON, "tunnel");
+ for (i = RTA_DATA(list); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
+ struct rtattr *ttb[IFLA_BRIDGE_VLAN_TUNNEL_MAX+1];
+ __u32 tunnel_id = 0;
+ __u16 tunnel_vid = 0;
+ __u16 tunnel_flags = 0;
+ int vcheck_ret;
+
+ if (i->rta_type != IFLA_BRIDGE_VLAN_TUNNEL_INFO)
+ continue;
+
+ parse_rtattr(ttb, IFLA_BRIDGE_VLAN_TUNNEL_MAX,
+ RTA_DATA(i), RTA_PAYLOAD(i));
+
+ if (ttb[IFLA_BRIDGE_VLAN_TUNNEL_VID])
+ tunnel_vid =
+ rta_getattr_u32(ttb[IFLA_BRIDGE_VLAN_TUNNEL_VID]);
+ else
+ continue;
+
+ if (ttb[IFLA_BRIDGE_VLAN_TUNNEL_ID])
+ tunnel_id =
+ rta_getattr_u32(ttb[IFLA_BRIDGE_VLAN_TUNNEL_ID]);
+
+ if (ttb[IFLA_BRIDGE_VLAN_TUNNEL_FLAGS])
+ tunnel_flags =
+ rta_getattr_u32(ttb[IFLA_BRIDGE_VLAN_TUNNEL_FLAGS]);
+
+ if (!(tunnel_flags & BRIDGE_VLAN_INFO_RANGE_END)) {
+ last_vid_start = tunnel_vid;
+ last_tunid_start = tunnel_id;
+ }
+
+ vcheck_ret = filter_vlan_check(tunnel_vid, tunnel_flags);
+ if (vcheck_ret == -1)
+ break;
+ else if (vcheck_ret == 0)
+ continue;
+
+ if (tunnel_flags & BRIDGE_VLAN_INFO_RANGE_BEGIN)
+ continue;
+
+ if (filter_vlan)
+ open_vlan_port(ifindex, "%s");
+
+ open_json_object(NULL);
+ print_range("vlan", last_vid_start, tunnel_vid);
+ print_range("tunid", last_tunid_start, tunnel_id);
+ close_json_object();
+
+ print_string(PRINT_FP, NULL, "%s", _SL_);
+ if (filter_vlan)
+ close_vlan_port();
+ }
+
+ if (!filter_vlan)
+ close_vlan_port();
+}
+
+static int print_vlan_tunnel(struct nlmsghdr *n, void *arg)
+{
+ struct ifinfomsg *ifm = NLMSG_DATA(n);
+ struct rtattr *tb[IFLA_MAX+1];
+ int len = n->nlmsg_len;
+ FILE *fp = arg;
+
+ if (n->nlmsg_type != RTM_NEWLINK) {
+ fprintf(stderr, "Not RTM_NEWLINK: %08x %08x %08x\n",
+ n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
+ return 0;
+ }
+
+ len -= NLMSG_LENGTH(sizeof(*ifm));
+ if (len < 0) {
+ fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
+ return -1;
+ }
+
+ if (ifm->ifi_family != AF_BRIDGE)
+ return 0;
+
+ if (filter_index && filter_index != ifm->ifi_index)
+ return 0;
+
+ parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifm), len);
+
+ /* if AF_SPEC isn't there, vlan table is not preset for this port */
+ if (!tb[IFLA_AF_SPEC]) {
+ if (!filter_vlan && !is_json_context()) {
+ color_fprintf(fp, COLOR_IFNAME, "%s",
+ ll_index_to_name(ifm->ifi_index));
+ fprintf(fp, "\tNone\n");
+ }
+ return 0;
+ }
+
+ print_vlan_tunnel_info(fp, tb[IFLA_AF_SPEC], ifm->ifi_index);
+
+ fflush(fp);
+ return 0;
+}
+
+static int print_vlan(struct nlmsghdr *n, void *arg)
+{
+ FILE *fp = arg;
+ struct ifinfomsg *ifm = NLMSG_DATA(n);
+ int len = n->nlmsg_len;
+ struct rtattr *tb[IFLA_MAX+1];
+
+ if (n->nlmsg_type != RTM_NEWLINK) {
+ fprintf(stderr, "Not RTM_NEWLINK: %08x %08x %08x\n",
+ n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
+ return 0;
+ }
+
+ len -= NLMSG_LENGTH(sizeof(*ifm));
+ if (len < 0) {
+ fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
+ return -1;
+ }
+
+ if (ifm->ifi_family != AF_BRIDGE)
+ return 0;
+
+ if (filter_index && filter_index != ifm->ifi_index)
+ return 0;
+
+ parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifm), len);
+
+ /* if AF_SPEC isn't there, vlan table is not preset for this port */
+ if (!tb[IFLA_AF_SPEC]) {
+ if (!filter_vlan && !is_json_context()) {
+ color_fprintf(fp, COLOR_IFNAME, "%s",
+ ll_index_to_name(ifm->ifi_index));
+ fprintf(fp, "\tNone\n");
+ }
+ return 0;
+ }
+
+ print_vlan_info(tb[IFLA_AF_SPEC], ifm->ifi_index);
+ print_string(PRINT_FP, NULL, "%s", _SL_);
+
+ fflush(fp);
+ return 0;
+}
+
+static void print_vlan_flags(__u16 flags)
+{
+ if (flags == 0)
+ return;
+
+ open_json_array(PRINT_JSON, "flags");
+ if (flags & BRIDGE_VLAN_INFO_PVID)
+ print_string(PRINT_ANY, NULL, " %s", "PVID");
+
+ if (flags & BRIDGE_VLAN_INFO_UNTAGGED)
+ print_string(PRINT_ANY, NULL, " %s", "Egress Untagged");
+ close_json_array(PRINT_JSON, NULL);
+}
+
+static void print_one_vlan_stats(const struct bridge_vlan_xstats *vstats)
+{
+ open_json_object(NULL);
+ print_hu(PRINT_ANY, "vid", " %hu", vstats->vid);
+
+ print_vlan_flags(vstats->flags);
+
+ print_lluint(PRINT_ANY, "rx_bytes",
+ "\n RX: %llu bytes",
+ vstats->rx_bytes);
+ print_lluint(PRINT_ANY, "rx_packets", " %llu packets\n",
+ vstats->rx_packets);
+ print_lluint(PRINT_ANY, "tx_bytes",
+ " TX: %llu bytes",
+ vstats->tx_bytes);
+ print_lluint(PRINT_ANY, "tx_packets", " %llu packets\n",
+ vstats->tx_packets);
+ close_json_object();
+}
+
+static void print_vlan_stats_attr(struct rtattr *attr, int ifindex)
+{
+ struct rtattr *brtb[LINK_XSTATS_TYPE_MAX+1];
+ struct rtattr *i, *list;
+ bool found_vlan = false;
+ int rem;
+
+ parse_rtattr(brtb, LINK_XSTATS_TYPE_MAX, RTA_DATA(attr),
+ RTA_PAYLOAD(attr));
+ if (!brtb[LINK_XSTATS_TYPE_BRIDGE])
+ return;
+
+ list = brtb[LINK_XSTATS_TYPE_BRIDGE];
+ rem = RTA_PAYLOAD(list);
+
+ for (i = RTA_DATA(list); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
+ const struct bridge_vlan_xstats *vstats = RTA_DATA(i);
+
+ if (i->rta_type != BRIDGE_XSTATS_VLAN)
+ continue;
+
+ if (filter_vlan && filter_vlan != vstats->vid)
+ continue;
+
+ /* skip pure port entries, they'll be dumped via the slave stats call */
+ if ((vstats->flags & BRIDGE_VLAN_INFO_MASTER) &&
+ !(vstats->flags & BRIDGE_VLAN_INFO_BRENTRY))
+ continue;
+
+ /* found vlan stats, first time print the interface name */
+ if (!found_vlan) {
+ open_vlan_port(ifindex, "%-16s");
+ found_vlan = true;
+ } else {
+ print_string(PRINT_FP, NULL, "%-16s", "");
+ }
+ print_one_vlan_stats(vstats);
+ }
+
+ /* vlan_port is opened only if there are any vlan stats */
+ if (found_vlan)
+ close_vlan_port();
+}
+
+static int print_vlan_stats(struct nlmsghdr *n, void *arg)
+{
+ struct if_stats_msg *ifsm = NLMSG_DATA(n);
+ struct rtattr *tb[IFLA_STATS_MAX+1];
+ int len = n->nlmsg_len;
+ FILE *fp = arg;
+
+ len -= NLMSG_LENGTH(sizeof(*ifsm));
+ if (len < 0) {
+ fprintf(stderr, "BUG: wrong nlmsg len %d\n", len);
+ return -1;
+ }
+
+ if (filter_index && filter_index != ifsm->ifindex)
+ return 0;
+
+ parse_rtattr(tb, IFLA_STATS_MAX, IFLA_STATS_RTA(ifsm), len);
+
+ /* We have to check if any of the two attrs are usable */
+ if (tb[IFLA_STATS_LINK_XSTATS])
+ print_vlan_stats_attr(tb[IFLA_STATS_LINK_XSTATS],
+ ifsm->ifindex);
+
+ if (tb[IFLA_STATS_LINK_XSTATS_SLAVE])
+ print_vlan_stats_attr(tb[IFLA_STATS_LINK_XSTATS_SLAVE],
+ ifsm->ifindex);
+
+ fflush(fp);
+ return 0;
+}
+
+static int vlan_show(int argc, char **argv)
+{
+ char *filter_dev = NULL;
+ int ret = 0;
+
+ while (argc > 0) {
+ if (strcmp(*argv, "dev") == 0) {
+ NEXT_ARG();
+ if (filter_dev)
+ duparg("dev", *argv);
+ filter_dev = *argv;
+ } else if (strcmp(*argv, "vid") == 0) {
+ NEXT_ARG();
+ if (filter_vlan)
+ duparg("vid", *argv);
+ filter_vlan = atoi(*argv);
+ }
+ argc--; argv++;
+ }
+
+ if (filter_dev) {
+ filter_index = ll_name_to_index(filter_dev);
+ if (!filter_index)
+ return nodev(filter_dev);
+ }
+
+ new_json_obj(json);
+
+ if (!show_stats) {
+ if (rtnl_linkdump_req_filter(&rth, PF_BRIDGE,
+ (compress_vlans ?
+ RTEXT_FILTER_BRVLAN_COMPRESSED :
+ RTEXT_FILTER_BRVLAN)) < 0) {
+ perror("Cannont send dump request");
+ exit(1);
+ }
+
+ if (!is_json_context()) {
+ if (show_vlan_tunnel_info)
+ printf("port\tvlan ids\ttunnel id\n");
+ else
+ printf("port\tvlan ids\n");
+ }
+
+ if (show_vlan_tunnel_info)
+ ret = rtnl_dump_filter(&rth, print_vlan_tunnel,
+ stdout);
+ else
+ ret = rtnl_dump_filter(&rth, print_vlan, stdout);
+ if (ret < 0) {
+ fprintf(stderr, "Dump ternminated\n");
+ exit(1);
+ }
+ } else {
+ __u32 filt_mask;
+
+ filt_mask = IFLA_STATS_FILTER_BIT(IFLA_STATS_LINK_XSTATS);
+ if (rtnl_statsdump_req_filter(&rth, AF_UNSPEC, filt_mask) < 0) {
+ perror("Cannont send dump request");
+ exit(1);
+ }
+
+ if (!is_json_context())
+ printf("%-16s vlan id\n", "port");
+
+ if (rtnl_dump_filter(&rth, print_vlan_stats, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ exit(1);
+ }
+
+ filt_mask = IFLA_STATS_FILTER_BIT(IFLA_STATS_LINK_XSTATS_SLAVE);
+ if (rtnl_statsdump_req_filter(&rth, AF_UNSPEC, filt_mask) < 0) {
+ perror("Cannont send slave dump request");
+ exit(1);
+ }
+
+ if (rtnl_dump_filter(&rth, print_vlan_stats, stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ exit(1);
+ }
+ }
+
+ delete_json_obj();
+ fflush(stdout);
+ return 0;
+}
+
+void print_vlan_info(struct rtattr *tb, int ifindex)
+{
+ struct rtattr *i, *list = tb;
+ int rem = RTA_PAYLOAD(list);
+ __u16 last_vid_start = 0;
+
+ open_vlan_port(ifindex, "%s");
+
+ for (i = RTA_DATA(list); RTA_OK(i, rem); i = RTA_NEXT(i, rem)) {
+ struct bridge_vlan_info *vinfo;
+ int vcheck_ret;
+
+ if (i->rta_type != IFLA_BRIDGE_VLAN_INFO)
+ continue;
+
+ vinfo = RTA_DATA(i);
+
+ if (!(vinfo->flags & BRIDGE_VLAN_INFO_RANGE_END))
+ last_vid_start = vinfo->vid;
+ vcheck_ret = filter_vlan_check(vinfo->vid, vinfo->flags);
+ if (vcheck_ret == -1)
+ break;
+ else if (vcheck_ret == 0)
+ continue;
+
+ open_json_object(NULL);
+ print_range("vlan", last_vid_start, vinfo->vid);
+
+ print_vlan_flags(vinfo->flags);
+ close_json_object();
+ print_string(PRINT_FP, NULL, "%s", _SL_);
+ }
+ close_vlan_port();
+}
+
+int do_vlan(int argc, char **argv)
+{
+ ll_init_map(&rth);
+
+ if (argc > 0) {
+ if (matches(*argv, "add") == 0)
+ return vlan_modify(RTM_SETLINK, argc-1, argv+1);
+ if (matches(*argv, "delete") == 0)
+ return vlan_modify(RTM_DELLINK, argc-1, argv+1);
+ if (matches(*argv, "show") == 0 ||
+ matches(*argv, "lst") == 0 ||
+ matches(*argv, "list") == 0)
+ return vlan_show(argc-1, argv+1);
+ if (matches(*argv, "tunnelshow") == 0) {
+ show_vlan_tunnel_info = 1;
+ return vlan_show(argc-1, argv+1);
+ }
+ if (matches(*argv, "help") == 0)
+ usage();
+ } else {
+ return vlan_show(0, NULL);
+ }
+
+ fprintf(stderr, "Command \"%s\" is unknown, try \"bridge vlan help\".\n", *argv);
+ exit(-1);
+}
diff --git a/configure b/configure
new file mode 100755
index 0000000..45fcffb
--- /dev/null
+++ b/configure
@@ -0,0 +1,403 @@
+#!/bin/sh
+# SPDX-License-Identifier: GPL-2.0
+# This is not an autoconf generated configure
+#
+INCLUDE=${1:-"$PWD/include"}
+
+# Output file which is input to Makefile
+CONFIG=config.mk
+
+# Make a temp directory in build tree.
+TMPDIR=$(mktemp -d config.XXXXXX)
+trap 'status=$?; rm -rf $TMPDIR; exit $status' EXIT HUP INT QUIT TERM
+
+check_toolchain()
+{
+ : ${PKG_CONFIG:=pkg-config}
+ : ${AR=ar}
+ : ${CC=gcc}
+ echo "PKG_CONFIG:=${PKG_CONFIG}" >>$CONFIG
+ echo "AR:=${AR}" >>$CONFIG
+ echo "CC:=${CC}" >>$CONFIG
+}
+
+check_atm()
+{
+ cat >$TMPDIR/atmtest.c <<EOF
+#include <atm.h>
+int main(int argc, char **argv) {
+ struct atm_qos qos;
+ (void) text2qos("aal5,ubr:sdu=9180,rx:none",&qos,0);
+ return 0;
+}
+EOF
+
+ if $CC -I$INCLUDE -o $TMPDIR/atmtest $TMPDIR/atmtest.c -latm >/dev/null 2>&1; then
+ echo "TC_CONFIG_ATM:=y" >>$CONFIG
+ echo yes
+ else
+ echo no
+ fi
+ rm -f $TMPDIR/atmtest.c $TMPDIR/atmtest
+}
+
+check_xtables()
+{
+ if ! ${PKG_CONFIG} xtables --exists; then
+ echo "TC_CONFIG_NO_XT:=y" >>$CONFIG
+ fi
+}
+
+check_xt()
+{
+ #check if we have xtables from iptables >= 1.4.5.
+ cat >$TMPDIR/ipttest.c <<EOF
+#include <xtables.h>
+#include <linux/netfilter.h>
+static struct xtables_globals test_globals = {
+ .option_offset = 0,
+ .program_name = "tc-ipt",
+ .program_version = XTABLES_VERSION,
+ .orig_opts = NULL,
+ .opts = NULL,
+ .exit_err = NULL,
+};
+
+int main(int argc, char **argv)
+{
+ xtables_init_all(&test_globals, NFPROTO_IPV4);
+ return 0;
+}
+EOF
+
+ if $CC -I$INCLUDE $IPTC -o $TMPDIR/ipttest $TMPDIR/ipttest.c $IPTL \
+ $(${PKG_CONFIG} xtables --cflags --libs) -ldl >/dev/null 2>&1; then
+ echo "TC_CONFIG_XT:=y" >>$CONFIG
+ echo "using xtables"
+ fi
+ rm -f $TMPDIR/ipttest.c $TMPDIR/ipttest
+}
+
+check_xt_old()
+{
+ # bail if previous XT checks has already succeeded.
+ grep -q TC_CONFIG_XT $CONFIG && return
+
+ #check if we don't need our internal header ..
+ cat >$TMPDIR/ipttest.c <<EOF
+#include <xtables.h>
+char *lib_dir;
+unsigned int global_option_offset = 0;
+const char *program_version = XTABLES_VERSION;
+const char *program_name = "tc-ipt";
+struct afinfo afinfo = {
+ .libprefix = "libxt_",
+};
+
+void exit_error(enum exittype status, const char *msg, ...)
+{
+}
+
+int main(int argc, char **argv) {
+
+ return 0;
+}
+
+EOF
+
+ if $CC -I$INCLUDE $IPTC -o $TMPDIR/ipttest $TMPDIR/ipttest.c $IPTL -ldl >/dev/null 2>&1; then
+ echo "TC_CONFIG_XT_OLD:=y" >>$CONFIG
+ echo "using old xtables (no need for xt-internal.h)"
+ fi
+ rm -f $TMPDIR/ipttest.c $TMPDIR/ipttest
+}
+
+check_xt_old_internal_h()
+{
+ # bail if previous XT checks has already succeeded.
+ grep -q TC_CONFIG_XT $CONFIG && return
+
+ #check if we need our own internal.h
+ cat >$TMPDIR/ipttest.c <<EOF
+#include <xtables.h>
+#include "xt-internal.h"
+char *lib_dir;
+unsigned int global_option_offset = 0;
+const char *program_version = XTABLES_VERSION;
+const char *program_name = "tc-ipt";
+struct afinfo afinfo = {
+ .libprefix = "libxt_",
+};
+
+void exit_error(enum exittype status, const char *msg, ...)
+{
+}
+
+int main(int argc, char **argv) {
+
+ return 0;
+}
+
+EOF
+ if $CC -I$INCLUDE $IPTC -o $TMPDIR/ipttest $TMPDIR/ipttest.c $IPTL -ldl >/dev/null 2>&1; then
+ echo "using old xtables with xt-internal.h"
+ echo "TC_CONFIG_XT_OLD_H:=y" >>$CONFIG
+ fi
+ rm -f $TMPDIR/ipttest.c $TMPDIR/ipttest
+}
+
+check_ipt()
+{
+ if ! grep TC_CONFIG_XT $CONFIG > /dev/null; then
+ echo "using iptables"
+ fi
+}
+
+check_ipt_lib_dir()
+{
+ IPT_LIB_DIR=$(${PKG_CONFIG} --variable=xtlibdir xtables)
+ if [ -n "$IPT_LIB_DIR" ]; then
+ echo $IPT_LIB_DIR
+ echo "IPT_LIB_DIR:=$IPT_LIB_DIR" >> $CONFIG
+ return
+ fi
+
+ for dir in /lib /usr/lib /usr/local/lib; do
+ for file in "xtables" "iptables"; do
+ file="$dir/$file/lib*t_*so"
+ if [ -f $file ]; then
+ echo ${file%/*}
+ echo "IPT_LIB_DIR:=${file%/*}" >> $CONFIG
+ return
+ fi
+ done
+ done
+ echo "not found!"
+}
+
+check_setns()
+{
+ cat >$TMPDIR/setnstest.c <<EOF
+#include <sched.h>
+int main(int argc, char **argv)
+{
+ (void)setns(0,0);
+ return 0;
+}
+EOF
+ if $CC -I$INCLUDE -o $TMPDIR/setnstest $TMPDIR/setnstest.c >/dev/null 2>&1; then
+ echo "IP_CONFIG_SETNS:=y" >>$CONFIG
+ echo "yes"
+ echo "CFLAGS += -DHAVE_SETNS" >>$CONFIG
+ else
+ echo "no"
+ fi
+ rm -f $TMPDIR/setnstest.c $TMPDIR/setnstest
+}
+
+check_ipset()
+{
+ cat >$TMPDIR/ipsettest.c <<EOF
+#include <linux/netfilter/ipset/ip_set.h>
+#ifndef IP_SET_INVALID
+#define IPSET_DIM_MAX 3
+typedef unsigned short ip_set_id_t;
+#endif
+#include <linux/netfilter/xt_set.h>
+
+struct xt_set_info info;
+#if IPSET_PROTOCOL == 6
+int main(void)
+{
+ return IPSET_MAXNAMELEN;
+}
+#else
+#error unknown ipset version
+#endif
+EOF
+
+ if $CC -I$INCLUDE -o $TMPDIR/ipsettest $TMPDIR/ipsettest.c >/dev/null 2>&1; then
+ echo "TC_CONFIG_IPSET:=y" >>$CONFIG
+ echo "yes"
+ else
+ echo "no"
+ fi
+ rm -f $TMPDIR/ipsettest.c $TMPDIR/ipsettest
+}
+
+check_elf()
+{
+ if ${PKG_CONFIG} libelf --exists; then
+ echo "HAVE_ELF:=y" >>$CONFIG
+ echo "yes"
+
+ echo 'CFLAGS += -DHAVE_ELF' `${PKG_CONFIG} libelf --cflags` >> $CONFIG
+ echo 'LDLIBS += ' `${PKG_CONFIG} libelf --libs` >>$CONFIG
+ else
+ echo "no"
+ fi
+}
+
+check_selinux()
+# SELinux is a compile time option in the ss utility
+{
+ if ${PKG_CONFIG} libselinux --exists; then
+ echo "HAVE_SELINUX:=y" >>$CONFIG
+ echo "yes"
+
+ echo 'LDLIBS +=' `${PKG_CONFIG} --libs libselinux` >>$CONFIG
+ echo 'CFLAGS += -DHAVE_SELINUX' `${PKG_CONFIG} --cflags libselinux` >>$CONFIG
+ else
+ echo "no"
+ fi
+}
+
+check_mnl()
+{
+ if ${PKG_CONFIG} libmnl --exists; then
+ echo "HAVE_MNL:=y" >>$CONFIG
+ echo "yes"
+
+ echo 'CFLAGS += -DHAVE_LIBMNL' `${PKG_CONFIG} libmnl --cflags` >>$CONFIG
+ echo 'LDLIBS +=' `${PKG_CONFIG} libmnl --libs` >> $CONFIG
+ else
+ echo "no"
+ fi
+}
+
+check_berkeley_db()
+{
+ cat >$TMPDIR/dbtest.c <<EOF
+#include <fcntl.h>
+#include <stdlib.h>
+#include <db_185.h>
+int main(int argc, char **argv) {
+ dbopen("/tmp/xxx_test_db.db", O_CREAT|O_RDWR, 0644, DB_HASH, NULL);
+ return 0;
+}
+EOF
+ if $CC -I$INCLUDE -o $TMPDIR/dbtest $TMPDIR/dbtest.c -ldb >/dev/null 2>&1; then
+ echo "HAVE_BERKELEY_DB:=y" >>$CONFIG
+ echo "yes"
+ else
+ echo "no"
+ fi
+ rm -f $TMPDIR/dbtest.c $TMPDIR/dbtest
+}
+
+check_strlcpy()
+{
+ cat >$TMPDIR/strtest.c <<EOF
+#include <string.h>
+int main(int argc, char **argv) {
+ char dst[10];
+ strlcpy(dst, "test", sizeof(dst));
+ return 0;
+}
+EOF
+ if $CC -I$INCLUDE -o $TMPDIR/strtest $TMPDIR/strtest.c >/dev/null 2>&1; then
+ echo "no"
+ else
+ if ${PKG_CONFIG} libbsd --exists; then
+ echo 'CFLAGS += -DHAVE_LIBBSD' `${PKG_CONFIG} libbsd --cflags` >>$CONFIG
+ echo 'LDLIBS +=' `${PKG_CONFIG} libbsd --libs` >> $CONFIG
+ echo "no"
+ else
+ echo 'CFLAGS += -DNEED_STRLCPY' >>$CONFIG
+ echo "yes"
+ fi
+ fi
+ rm -f $TMPDIR/strtest.c $TMPDIR/strtest
+}
+
+check_cap()
+{
+ if ${PKG_CONFIG} libcap --exists; then
+ echo "HAVE_CAP:=y" >>$CONFIG
+ echo "yes"
+
+ echo 'CFLAGS += -DHAVE_LIBCAP' `${PKG_CONFIG} libcap --cflags` >>$CONFIG
+ echo 'LDLIBS +=' `${PKG_CONFIG} libcap --libs` >> $CONFIG
+ else
+ echo "no"
+ fi
+}
+
+quiet_config()
+{
+ cat <<EOF
+# user can control verbosity similar to kernel builds (e.g., V=1)
+ifeq ("\$(origin V)", "command line")
+ VERBOSE = \$(V)
+endif
+ifndef VERBOSE
+ VERBOSE = 0
+endif
+ifeq (\$(VERBOSE),1)
+ Q =
+else
+ Q = @
+endif
+
+ifeq (\$(VERBOSE), 0)
+ QUIET_CC = @echo ' CC '\$@;
+ QUIET_AR = @echo ' AR '\$@;
+ QUIET_LINK = @echo ' LINK '\$@;
+ QUIET_YACC = @echo ' YACC '\$@;
+ QUIET_LEX = @echo ' LEX '\$@;
+endif
+EOF
+}
+
+echo "# Generated config based on" $INCLUDE >$CONFIG
+quiet_config >> $CONFIG
+
+check_toolchain
+
+echo "TC schedulers"
+
+echo -n " ATM "
+check_atm
+
+check_xtables
+if ! grep -q TC_CONFIG_NO_XT $CONFIG; then
+ echo -n " IPT "
+ check_xt
+ check_xt_old
+ check_xt_old_internal_h
+ check_ipt
+
+ echo -n " IPSET "
+ check_ipset
+fi
+
+echo
+if ! grep -q TC_CONFIG_NO_XT $CONFIG; then
+ echo -n "iptables modules directory: "
+ check_ipt_lib_dir
+fi
+
+echo -n "libc has setns: "
+check_setns
+
+echo -n "SELinux support: "
+check_selinux
+
+echo -n "ELF support: "
+check_elf
+
+echo -n "libmnl support: "
+check_mnl
+
+echo -n "Berkeley DB: "
+check_berkeley_db
+
+echo -n "need for strlcpy: "
+check_strlcpy
+
+echo -n "libcap support: "
+check_cap
+
+echo >> $CONFIG
+echo "%.o: %.c" >> $CONFIG
+echo ' $(QUIET_CC)$(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(CPPFLAGS) -c -o $@ $<' >> $CONFIG
diff --git a/devlink/.gitignore b/devlink/.gitignore
new file mode 100644
index 0000000..08d175f
--- /dev/null
+++ b/devlink/.gitignore
@@ -0,0 +1 @@
+devlink
diff --git a/devlink/Makefile b/devlink/Makefile
new file mode 100644
index 0000000..7da7d1f
--- /dev/null
+++ b/devlink/Makefile
@@ -0,0 +1,24 @@
+# SPDX-License-Identifier: GPL-2.0
+include ../config.mk
+
+TARGETS :=
+
+ifeq ($(HAVE_MNL),y)
+
+DEVLINKOBJ = devlink.o mnlg.o
+TARGETS += devlink
+
+endif
+
+all: $(TARGETS) $(LIBS)
+
+devlink: $(DEVLINKOBJ)
+ $(QUIET_LINK)$(CC) $^ $(LDFLAGS) $(LDLIBS) -o $@
+
+install: all
+ for i in $(TARGETS); \
+ do install -m 0755 $$i $(DESTDIR)$(SBINDIR); \
+ done
+
+clean:
+ rm -f $(DEVLINKOBJ) $(TARGETS)
diff --git a/devlink/devlink.c b/devlink/devlink.c
new file mode 100644
index 0000000..056ac95
--- /dev/null
+++ b/devlink/devlink.c
@@ -0,0 +1,7257 @@
+/*
+ * devlink.c Devlink tool
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Jiri Pirko <jiri@mellanox.com>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <limits.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <sys/sysinfo.h>
+#define _LINUX_SYSINFO_H /* avoid collision with musl header */
+#include <linux/genetlink.h>
+#include <linux/devlink.h>
+#include <libmnl/libmnl.h>
+#include <netinet/ether.h>
+#include <sys/types.h>
+
+#include "SNAPSHOT.h"
+#include "list.h"
+#include "mnlg.h"
+#include "json_writer.h"
+#include "utils.h"
+
+#define ESWITCH_MODE_LEGACY "legacy"
+#define ESWITCH_MODE_SWITCHDEV "switchdev"
+#define ESWITCH_INLINE_MODE_NONE "none"
+#define ESWITCH_INLINE_MODE_LINK "link"
+#define ESWITCH_INLINE_MODE_NETWORK "network"
+#define ESWITCH_INLINE_MODE_TRANSPORT "transport"
+
+#define PARAM_CMODE_RUNTIME_STR "runtime"
+#define PARAM_CMODE_DRIVERINIT_STR "driverinit"
+#define PARAM_CMODE_PERMANENT_STR "permanent"
+#define DL_ARGS_REQUIRED_MAX_ERR_LEN 80
+
+#define HEALTH_REPORTER_STATE_HEALTHY_STR "healthy"
+#define HEALTH_REPORTER_STATE_ERROR_STR "error"
+#define HEALTH_REPORTER_TIMESTAMP_FMT_LEN 80
+
+static int g_new_line_count;
+static int g_indent_level;
+static bool g_indent_newline;
+
+#define INDENT_STR_STEP 2
+#define INDENT_STR_MAXLEN 32
+static char g_indent_str[INDENT_STR_MAXLEN + 1] = "";
+
+static void __attribute__((format(printf, 1, 2)))
+pr_err(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+}
+
+static void __attribute__((format(printf, 1, 2)))
+pr_out(const char *fmt, ...)
+{
+ va_list ap;
+
+ if (g_indent_newline) {
+ printf("%s", g_indent_str);
+ g_indent_newline = false;
+ }
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+ g_new_line_count = 0;
+}
+
+static void __attribute__((format(printf, 2, 3)))
+pr_out_sp(unsigned int num, const char *fmt, ...)
+{
+ va_list ap;
+ int ret;
+
+ va_start(ap, fmt);
+ ret = vprintf(fmt, ap);
+ va_end(ap);
+
+ if (ret < num)
+ printf("%*s", num - ret, "");
+ g_new_line_count = 0; \
+}
+
+static void __attribute__((format(printf, 1, 2)))
+pr_out_tty(const char *fmt, ...)
+{
+ va_list ap;
+
+ if (!isatty(STDOUT_FILENO))
+ return;
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+}
+
+static void __pr_out_indent_inc(void)
+{
+ if (g_indent_level + INDENT_STR_STEP > INDENT_STR_MAXLEN)
+ return;
+ g_indent_level += INDENT_STR_STEP;
+ memset(g_indent_str, ' ', sizeof(g_indent_str));
+ g_indent_str[g_indent_level] = '\0';
+}
+
+static void __pr_out_indent_dec(void)
+{
+ if (g_indent_level - INDENT_STR_STEP < 0)
+ return;
+ g_indent_level -= INDENT_STR_STEP;
+ g_indent_str[g_indent_level] = '\0';
+}
+
+static void __pr_out_newline(void)
+{
+ if (g_new_line_count < 1) {
+ pr_out("\n");
+ g_indent_newline = true;
+ }
+ g_new_line_count++;
+}
+
+static int _mnlg_socket_recv_run(struct mnlg_socket *nlg,
+ mnl_cb_t data_cb, void *data)
+{
+ int err;
+
+ err = mnlg_socket_recv_run(nlg, data_cb, data);
+ if (err < 0) {
+ pr_err("devlink answers: %s\n", strerror(errno));
+ return -errno;
+ }
+ return 0;
+}
+
+static int _mnlg_socket_send(struct mnlg_socket *nlg,
+ const struct nlmsghdr *nlh)
+{
+ int err;
+
+ err = mnlg_socket_send(nlg, nlh);
+ if (err < 0) {
+ pr_err("Failed to call mnlg_socket_send\n");
+ return -errno;
+ }
+ return 0;
+}
+
+static int _mnlg_socket_sndrcv(struct mnlg_socket *nlg,
+ const struct nlmsghdr *nlh,
+ mnl_cb_t data_cb, void *data)
+{
+ int err;
+
+ err = _mnlg_socket_send(nlg, nlh);
+ if (err)
+ return err;
+ return _mnlg_socket_recv_run(nlg, data_cb, data);
+}
+
+static int _mnlg_socket_group_add(struct mnlg_socket *nlg,
+ const char *group_name)
+{
+ int err;
+
+ err = mnlg_socket_group_add(nlg, group_name);
+ if (err < 0) {
+ pr_err("Failed to call mnlg_socket_group_add\n");
+ return -errno;
+ }
+ return 0;
+}
+
+struct ifname_map {
+ struct list_head list;
+ char *bus_name;
+ char *dev_name;
+ uint32_t port_index;
+ char *ifname;
+};
+
+static struct ifname_map *ifname_map_alloc(const char *bus_name,
+ const char *dev_name,
+ uint32_t port_index,
+ const char *ifname)
+{
+ struct ifname_map *ifname_map;
+
+ ifname_map = calloc(1, sizeof(*ifname_map));
+ if (!ifname_map)
+ return NULL;
+ ifname_map->bus_name = strdup(bus_name);
+ ifname_map->dev_name = strdup(dev_name);
+ ifname_map->port_index = port_index;
+ ifname_map->ifname = strdup(ifname);
+ if (!ifname_map->bus_name || !ifname_map->dev_name ||
+ !ifname_map->ifname) {
+ free(ifname_map->ifname);
+ free(ifname_map->dev_name);
+ free(ifname_map->bus_name);
+ free(ifname_map);
+ return NULL;
+ }
+ return ifname_map;
+}
+
+static void ifname_map_free(struct ifname_map *ifname_map)
+{
+ free(ifname_map->ifname);
+ free(ifname_map->dev_name);
+ free(ifname_map->bus_name);
+ free(ifname_map);
+}
+
+#define DL_OPT_HANDLE BIT(0)
+#define DL_OPT_HANDLEP BIT(1)
+#define DL_OPT_PORT_TYPE BIT(2)
+#define DL_OPT_PORT_COUNT BIT(3)
+#define DL_OPT_SB BIT(4)
+#define DL_OPT_SB_POOL BIT(5)
+#define DL_OPT_SB_SIZE BIT(6)
+#define DL_OPT_SB_TYPE BIT(7)
+#define DL_OPT_SB_THTYPE BIT(8)
+#define DL_OPT_SB_TH BIT(9)
+#define DL_OPT_SB_TC BIT(10)
+#define DL_OPT_ESWITCH_MODE BIT(11)
+#define DL_OPT_ESWITCH_INLINE_MODE BIT(12)
+#define DL_OPT_DPIPE_TABLE_NAME BIT(13)
+#define DL_OPT_DPIPE_TABLE_COUNTERS BIT(14)
+#define DL_OPT_ESWITCH_ENCAP_MODE BIT(15)
+#define DL_OPT_RESOURCE_PATH BIT(16)
+#define DL_OPT_RESOURCE_SIZE BIT(17)
+#define DL_OPT_PARAM_NAME BIT(18)
+#define DL_OPT_PARAM_VALUE BIT(19)
+#define DL_OPT_PARAM_CMODE BIT(20)
+#define DL_OPT_HANDLE_REGION BIT(21)
+#define DL_OPT_REGION_SNAPSHOT_ID BIT(22)
+#define DL_OPT_REGION_ADDRESS BIT(23)
+#define DL_OPT_REGION_LENGTH BIT(24)
+#define DL_OPT_FLASH_FILE_NAME BIT(25)
+#define DL_OPT_FLASH_COMPONENT BIT(26)
+#define DL_OPT_HEALTH_REPORTER_NAME BIT(27)
+#define DL_OPT_HEALTH_REPORTER_GRACEFUL_PERIOD BIT(28)
+#define DL_OPT_HEALTH_REPORTER_AUTO_RECOVER BIT(29)
+#define DL_OPT_TRAP_NAME BIT(30)
+#define DL_OPT_TRAP_ACTION BIT(31)
+#define DL_OPT_TRAP_GROUP_NAME BIT(32)
+
+struct dl_opts {
+ uint64_t present; /* flags of present items */
+ char *bus_name;
+ char *dev_name;
+ uint32_t port_index;
+ enum devlink_port_type port_type;
+ uint32_t port_count;
+ uint32_t sb_index;
+ uint16_t sb_pool_index;
+ uint32_t sb_pool_size;
+ enum devlink_sb_pool_type sb_pool_type;
+ enum devlink_sb_threshold_type sb_pool_thtype;
+ uint32_t sb_threshold;
+ uint16_t sb_tc_index;
+ enum devlink_eswitch_mode eswitch_mode;
+ enum devlink_eswitch_inline_mode eswitch_inline_mode;
+ const char *dpipe_table_name;
+ bool dpipe_counters_enable;
+ bool eswitch_encap_mode;
+ const char *resource_path;
+ uint32_t resource_size;
+ uint32_t resource_id;
+ bool resource_id_valid;
+ const char *param_name;
+ const char *param_value;
+ enum devlink_param_cmode cmode;
+ char *region_name;
+ uint32_t region_snapshot_id;
+ uint64_t region_address;
+ uint64_t region_length;
+ const char *flash_file_name;
+ const char *flash_component;
+ const char *reporter_name;
+ uint64_t reporter_graceful_period;
+ bool reporter_auto_recover;
+ const char *trap_name;
+ const char *trap_group_name;
+ enum devlink_trap_action trap_action;
+};
+
+struct dl {
+ struct mnlg_socket *nlg;
+ struct list_head ifname_map_list;
+ int argc;
+ char **argv;
+ bool no_nice_names;
+ struct dl_opts opts;
+ json_writer_t *jw;
+ bool json_output;
+ bool pretty_output;
+ bool verbose;
+ bool stats;
+ struct {
+ bool present;
+ char *bus_name;
+ char *dev_name;
+ uint32_t port_index;
+ } arr_last;
+};
+
+static int dl_argc(struct dl *dl)
+{
+ return dl->argc;
+}
+
+static char *dl_argv(struct dl *dl)
+{
+ if (dl_argc(dl) == 0)
+ return NULL;
+ return *dl->argv;
+}
+
+static void dl_arg_inc(struct dl *dl)
+{
+ if (dl_argc(dl) == 0)
+ return;
+ dl->argc--;
+ dl->argv++;
+}
+
+static char *dl_argv_next(struct dl *dl)
+{
+ char *ret;
+
+ if (dl_argc(dl) == 0)
+ return NULL;
+
+ ret = *dl->argv;
+ dl_arg_inc(dl);
+ return ret;
+}
+
+static char *dl_argv_index(struct dl *dl, unsigned int index)
+{
+ if (index >= dl_argc(dl))
+ return NULL;
+ return dl->argv[index];
+}
+
+static int strcmpx(const char *str1, const char *str2)
+{
+ if (strlen(str1) > strlen(str2))
+ return -1;
+ return strncmp(str1, str2, strlen(str1));
+}
+
+static bool dl_argv_match(struct dl *dl, const char *pattern)
+{
+ if (dl_argc(dl) == 0)
+ return false;
+ return strcmpx(dl_argv(dl), pattern) == 0;
+}
+
+static bool dl_no_arg(struct dl *dl)
+{
+ return dl_argc(dl) == 0;
+}
+
+static void __pr_out_indent_newline(struct dl *dl)
+{
+ if (!g_indent_newline && !dl->json_output)
+ pr_out(" ");
+}
+
+static const enum mnl_attr_data_type devlink_policy[DEVLINK_ATTR_MAX + 1] = {
+ [DEVLINK_ATTR_BUS_NAME] = MNL_TYPE_NUL_STRING,
+ [DEVLINK_ATTR_DEV_NAME] = MNL_TYPE_NUL_STRING,
+ [DEVLINK_ATTR_PORT_INDEX] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_PORT_TYPE] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_PORT_DESIRED_TYPE] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_PORT_NETDEV_IFINDEX] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_PORT_NETDEV_NAME] = MNL_TYPE_NUL_STRING,
+ [DEVLINK_ATTR_PORT_IBDEV_NAME] = MNL_TYPE_NUL_STRING,
+ [DEVLINK_ATTR_SB_INDEX] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_SB_SIZE] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_SB_INGRESS_POOL_COUNT] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_EGRESS_POOL_COUNT] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_INGRESS_TC_COUNT] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_EGRESS_TC_COUNT] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_POOL_INDEX] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_POOL_TYPE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_SB_POOL_SIZE] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_SB_POOL_THRESHOLD_TYPE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_SB_THRESHOLD] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_SB_TC_INDEX] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_SB_OCC_CUR] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_SB_OCC_MAX] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_ESWITCH_MODE] = MNL_TYPE_U16,
+ [DEVLINK_ATTR_ESWITCH_INLINE_MODE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_ESWITCH_ENCAP_MODE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_DPIPE_TABLES] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_TABLE] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_TABLE_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_DPIPE_TABLE_SIZE] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_DPIPE_TABLE_MATCHES] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_TABLE_ACTIONS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_TABLE_COUNTERS_ENABLED] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_DPIPE_ENTRIES] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ENTRY] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ENTRY_INDEX] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_DPIPE_ENTRY_MATCH_VALUES] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ENTRY_ACTION_VALUES] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ENTRY_COUNTER] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_DPIPE_MATCH] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_MATCH_VALUE] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_MATCH_TYPE] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_ACTION] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ACTION_VALUE] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_ACTION_TYPE] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_VALUE_MAPPING] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_HEADERS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_HEADER] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_HEADER_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_DPIPE_HEADER_ID] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_HEADER_FIELDS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_HEADER_GLOBAL] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_DPIPE_HEADER_INDEX] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_FIELD] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_DPIPE_FIELD_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_DPIPE_FIELD_ID] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_FIELD_BITWIDTH] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_DPIPE_FIELD_MAPPING_TYPE] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_PARAM] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_PARAM_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_PARAM_TYPE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_PARAM_VALUES_LIST] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_PARAM_VALUE] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_PARAM_VALUE_CMODE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_REGION_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_REGION_SIZE] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_REGION_SNAPSHOTS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_REGION_SNAPSHOT] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_REGION_SNAPSHOT_ID] = MNL_TYPE_U32,
+ [DEVLINK_ATTR_REGION_CHUNKS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_REGION_CHUNK] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_REGION_CHUNK_DATA] = MNL_TYPE_BINARY,
+ [DEVLINK_ATTR_REGION_CHUNK_ADDR] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_REGION_CHUNK_LEN] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_INFO_DRIVER_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_INFO_SERIAL_NUMBER] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_INFO_VERSION_FIXED] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_INFO_VERSION_RUNNING] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_INFO_VERSION_STORED] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_INFO_VERSION_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_INFO_VERSION_VALUE] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_HEALTH_REPORTER] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_HEALTH_REPORTER_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_HEALTH_REPORTER_STATE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_HEALTH_REPORTER_ERR_COUNT] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_HEALTH_REPORTER_RECOVER_COUNT] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_HEALTH_REPORTER_DUMP_TS] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_HEALTH_REPORTER_GRACEFUL_PERIOD] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_FLASH_UPDATE_COMPONENT] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_STATS] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_TRAP_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_TRAP_ACTION] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_TRAP_TYPE] = MNL_TYPE_U8,
+ [DEVLINK_ATTR_TRAP_GENERIC] = MNL_TYPE_FLAG,
+ [DEVLINK_ATTR_TRAP_METADATA] = MNL_TYPE_NESTED,
+ [DEVLINK_ATTR_TRAP_GROUP_NAME] = MNL_TYPE_STRING,
+ [DEVLINK_ATTR_RELOAD_FAILED] = MNL_TYPE_U8,
+};
+
+static const enum mnl_attr_data_type
+devlink_stats_policy[DEVLINK_ATTR_STATS_MAX + 1] = {
+ [DEVLINK_ATTR_STATS_RX_PACKETS] = MNL_TYPE_U64,
+ [DEVLINK_ATTR_STATS_RX_BYTES] = MNL_TYPE_U64,
+};
+
+static int attr_cb(const struct nlattr *attr, void *data)
+{
+ const struct nlattr **tb = data;
+ int type;
+
+ if (mnl_attr_type_valid(attr, DEVLINK_ATTR_MAX) < 0)
+ return MNL_CB_OK;
+
+ type = mnl_attr_get_type(attr);
+ if (mnl_attr_validate(attr, devlink_policy[type]) < 0)
+ return MNL_CB_ERROR;
+
+ tb[type] = attr;
+ return MNL_CB_OK;
+}
+
+static int attr_stats_cb(const struct nlattr *attr, void *data)
+{
+ const struct nlattr **tb = data;
+ int type;
+
+ /* Allow the tool to work on top of newer kernels that might contain
+ * more attributes.
+ */
+ if (mnl_attr_type_valid(attr, DEVLINK_ATTR_STATS_MAX) < 0)
+ return MNL_CB_OK;
+
+ type = mnl_attr_get_type(attr);
+ if (mnl_attr_validate(attr, devlink_stats_policy[type]) < 0)
+ return MNL_CB_ERROR;
+
+ tb[type] = attr;
+ return MNL_CB_OK;
+}
+
+static int ifname_map_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct dl *dl = data;
+ struct ifname_map *ifname_map;
+ const char *bus_name;
+ const char *dev_name;
+ uint32_t port_ifindex;
+ const char *port_ifname;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX])
+ return MNL_CB_ERROR;
+
+ if (!tb[DEVLINK_ATTR_PORT_NETDEV_NAME])
+ return MNL_CB_OK;
+
+ bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ port_ifindex = mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_INDEX]);
+ port_ifname = mnl_attr_get_str(tb[DEVLINK_ATTR_PORT_NETDEV_NAME]);
+ ifname_map = ifname_map_alloc(bus_name, dev_name,
+ port_ifindex, port_ifname);
+ if (!ifname_map)
+ return MNL_CB_ERROR;
+ list_add(&ifname_map->list, &dl->ifname_map_list);
+
+ return MNL_CB_OK;
+}
+
+static void ifname_map_fini(struct dl *dl)
+{
+ struct ifname_map *ifname_map, *tmp;
+
+ list_for_each_entry_safe(ifname_map, tmp,
+ &dl->ifname_map_list, list) {
+ list_del(&ifname_map->list);
+ ifname_map_free(ifname_map);
+ }
+}
+
+static int ifname_map_init(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ INIT_LIST_HEAD(&dl->ifname_map_list);
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PORT_GET,
+ NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP);
+
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, ifname_map_cb, dl);
+ if (err) {
+ ifname_map_fini(dl);
+ return err;
+ }
+ return 0;
+}
+
+static int ifname_map_lookup(struct dl *dl, const char *ifname,
+ char **p_bus_name, char **p_dev_name,
+ uint32_t *p_port_index)
+{
+ struct ifname_map *ifname_map;
+
+ list_for_each_entry(ifname_map, &dl->ifname_map_list, list) {
+ if (strcmp(ifname, ifname_map->ifname) == 0) {
+ *p_bus_name = ifname_map->bus_name;
+ *p_dev_name = ifname_map->dev_name;
+ *p_port_index = ifname_map->port_index;
+ return 0;
+ }
+ }
+ return -ENOENT;
+}
+
+static int ifname_map_rev_lookup(struct dl *dl, const char *bus_name,
+ const char *dev_name, uint32_t port_index,
+ char **p_ifname)
+{
+ struct ifname_map *ifname_map;
+
+ list_for_each_entry(ifname_map, &dl->ifname_map_list, list) {
+ if (strcmp(bus_name, ifname_map->bus_name) == 0 &&
+ strcmp(dev_name, ifname_map->dev_name) == 0 &&
+ port_index == ifname_map->port_index) {
+ *p_ifname = ifname_map->ifname;
+ return 0;
+ }
+ }
+ return -ENOENT;
+}
+
+static unsigned int strslashcount(char *str)
+{
+ unsigned int count = 0;
+ char *pos = str;
+
+ while ((pos = strchr(pos, '/'))) {
+ count++;
+ pos++;
+ }
+ return count;
+}
+
+static int strslashrsplit(char *str, char **before, char **after)
+{
+ char *slash;
+
+ slash = strrchr(str, '/');
+ if (!slash)
+ return -EINVAL;
+ *slash = '\0';
+ *before = str;
+ *after = slash + 1;
+ return 0;
+}
+
+static int strtouint64_t(const char *str, uint64_t *p_val)
+{
+ char *endptr;
+ unsigned long long int val;
+
+ val = strtoull(str, &endptr, 10);
+ if (endptr == str || *endptr != '\0')
+ return -EINVAL;
+ if (val > ULONG_MAX)
+ return -ERANGE;
+ *p_val = val;
+ return 0;
+}
+
+static int strtouint32_t(const char *str, uint32_t *p_val)
+{
+ char *endptr;
+ unsigned long int val;
+
+ val = strtoul(str, &endptr, 10);
+ if (endptr == str || *endptr != '\0')
+ return -EINVAL;
+ if (val > UINT_MAX)
+ return -ERANGE;
+ *p_val = val;
+ return 0;
+}
+
+static int strtouint16_t(const char *str, uint16_t *p_val)
+{
+ char *endptr;
+ unsigned long int val;
+
+ val = strtoul(str, &endptr, 10);
+ if (endptr == str || *endptr != '\0')
+ return -EINVAL;
+ if (val > USHRT_MAX)
+ return -ERANGE;
+ *p_val = val;
+ return 0;
+}
+
+static int strtouint8_t(const char *str, uint8_t *p_val)
+{
+ char *endptr;
+ unsigned long int val;
+
+ val = strtoul(str, &endptr, 10);
+ if (endptr == str || *endptr != '\0')
+ return -EINVAL;
+ if (val > UCHAR_MAX)
+ return -ERANGE;
+ *p_val = val;
+ return 0;
+}
+
+static int strtobool(const char *str, bool *p_val)
+{
+ bool val;
+
+ if (!strcmp(str, "true") || !strcmp(str, "1"))
+ val = true;
+ else if (!strcmp(str, "false") || !strcmp(str, "0"))
+ val = false;
+ else
+ return -EINVAL;
+ *p_val = val;
+ return 0;
+}
+
+static int __dl_argv_handle(char *str, char **p_bus_name, char **p_dev_name)
+{
+ strslashrsplit(str, p_bus_name, p_dev_name);
+ return 0;
+}
+
+static int dl_argv_handle(struct dl *dl, char **p_bus_name, char **p_dev_name)
+{
+ char *str = dl_argv_next(dl);
+
+ if (!str) {
+ pr_err("Devlink identification (\"bus_name/dev_name\") expected\n");
+ return -EINVAL;
+ }
+ if (strslashcount(str) != 1) {
+ pr_err("Wrong devlink identification string format.\n");
+ pr_err("Expected \"bus_name/dev_name\".\n");
+ return -EINVAL;
+ }
+ return __dl_argv_handle(str, p_bus_name, p_dev_name);
+}
+
+static int __dl_argv_handle_port(char *str,
+ char **p_bus_name, char **p_dev_name,
+ uint32_t *p_port_index)
+{
+ char *handlestr;
+ char *portstr;
+ int err;
+
+ err = strslashrsplit(str, &handlestr, &portstr);
+ if (err) {
+ pr_err("Port identification \"%s\" is invalid\n", str);
+ return err;
+ }
+ err = strtouint32_t(portstr, p_port_index);
+ if (err) {
+ pr_err("Port index \"%s\" is not a number or not within range\n",
+ portstr);
+ return err;
+ }
+ err = strslashrsplit(handlestr, p_bus_name, p_dev_name);
+ if (err) {
+ pr_err("Port identification \"%s\" is invalid\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int __dl_argv_handle_port_ifname(struct dl *dl, char *str,
+ char **p_bus_name, char **p_dev_name,
+ uint32_t *p_port_index)
+{
+ int err;
+
+ err = ifname_map_lookup(dl, str, p_bus_name, p_dev_name,
+ p_port_index);
+ if (err) {
+ pr_err("Netdevice \"%s\" not found\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_handle_port(struct dl *dl, char **p_bus_name,
+ char **p_dev_name, uint32_t *p_port_index)
+{
+ char *str = dl_argv_next(dl);
+ unsigned int slash_count;
+
+ if (!str) {
+ pr_err("Port identification (\"bus_name/dev_name/port_index\" or \"netdev ifname\") expected.\n");
+ return -EINVAL;
+ }
+ slash_count = strslashcount(str);
+ switch (slash_count) {
+ case 0:
+ return __dl_argv_handle_port_ifname(dl, str, p_bus_name,
+ p_dev_name, p_port_index);
+ case 2:
+ return __dl_argv_handle_port(str, p_bus_name,
+ p_dev_name, p_port_index);
+ default:
+ pr_err("Wrong port identification string format.\n");
+ pr_err("Expected \"bus_name/dev_name/port_index\" or \"netdev_ifname\".\n");
+ return -EINVAL;
+ }
+}
+
+static int dl_argv_handle_both(struct dl *dl, char **p_bus_name,
+ char **p_dev_name, uint32_t *p_port_index,
+ uint64_t *p_handle_bit)
+{
+ char *str = dl_argv_next(dl);
+ unsigned int slash_count;
+ int err;
+
+ if (!str) {
+ pr_err("One of following identifications expected:\n"
+ "Devlink identification (\"bus_name/dev_name\")\n"
+ "Port identification (\"bus_name/dev_name/port_index\" or \"netdev ifname\")\n");
+ return -EINVAL;
+ }
+ slash_count = strslashcount(str);
+ if (slash_count == 1) {
+ err = __dl_argv_handle(str, p_bus_name, p_dev_name);
+ if (err)
+ return err;
+ *p_handle_bit = DL_OPT_HANDLE;
+ } else if (slash_count == 2) {
+ err = __dl_argv_handle_port(str, p_bus_name,
+ p_dev_name, p_port_index);
+ if (err)
+ return err;
+ *p_handle_bit = DL_OPT_HANDLEP;
+ } else if (slash_count == 0) {
+ err = __dl_argv_handle_port_ifname(dl, str, p_bus_name,
+ p_dev_name, p_port_index);
+ if (err)
+ return err;
+ *p_handle_bit = DL_OPT_HANDLEP;
+ } else {
+ pr_err("Wrong port identification string format.\n");
+ pr_err("Expected \"bus_name/dev_name\" or \"bus_name/dev_name/port_index\" or \"netdev_ifname\".\n");
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int __dl_argv_handle_region(char *str, char **p_bus_name,
+ char **p_dev_name, char **p_region)
+{
+ char *handlestr;
+ int err;
+
+ err = strslashrsplit(str, &handlestr, p_region);
+ if (err) {
+ pr_err("Region identification \"%s\" is invalid\n", str);
+ return err;
+ }
+ err = strslashrsplit(handlestr, p_bus_name, p_dev_name);
+ if (err) {
+ pr_err("Region identification \"%s\" is invalid\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_handle_region(struct dl *dl, char **p_bus_name,
+ char **p_dev_name, char **p_region)
+{
+ char *str = dl_argv_next(dl);
+ unsigned int slash_count;
+
+ if (!str) {
+ pr_err("Expected \"bus_name/dev_name/region\" identification.\n");
+ return -EINVAL;
+ }
+
+ slash_count = strslashcount(str);
+ if (slash_count != 2) {
+ pr_err("Wrong region identification string format.\n");
+ pr_err("Expected \"bus_name/dev_name/region\" identification.\n"".\n");
+ return -EINVAL;
+ }
+
+ return __dl_argv_handle_region(str, p_bus_name, p_dev_name, p_region);
+}
+
+static int dl_argv_uint64_t(struct dl *dl, uint64_t *p_val)
+{
+ char *str = dl_argv_next(dl);
+ int err;
+
+ if (!str) {
+ pr_err("Unsigned number argument expected\n");
+ return -EINVAL;
+ }
+
+ err = strtouint64_t(str, p_val);
+ if (err) {
+ pr_err("\"%s\" is not a number or not within range\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_uint32_t(struct dl *dl, uint32_t *p_val)
+{
+ char *str = dl_argv_next(dl);
+ int err;
+
+ if (!str) {
+ pr_err("Unsigned number argument expected\n");
+ return -EINVAL;
+ }
+
+ err = strtouint32_t(str, p_val);
+ if (err) {
+ pr_err("\"%s\" is not a number or not within range\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_uint16_t(struct dl *dl, uint16_t *p_val)
+{
+ char *str = dl_argv_next(dl);
+ int err;
+
+ if (!str) {
+ pr_err("Unsigned number argument expected\n");
+ return -EINVAL;
+ }
+
+ err = strtouint16_t(str, p_val);
+ if (err) {
+ pr_err("\"%s\" is not a number or not within range\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_bool(struct dl *dl, bool *p_val)
+{
+ char *str = dl_argv_next(dl);
+ int err;
+
+ if (!str) {
+ pr_err("Boolean argument expected\n");
+ return -EINVAL;
+ }
+
+ err = strtobool(str, p_val);
+ if (err) {
+ pr_err("\"%s\" is not a valid boolean value\n", str);
+ return err;
+ }
+ return 0;
+}
+
+static int dl_argv_str(struct dl *dl, const char **p_str)
+{
+ const char *str = dl_argv_next(dl);
+
+ if (!str) {
+ pr_err("String parameter expected\n");
+ return -EINVAL;
+ }
+ *p_str = str;
+ return 0;
+}
+
+static int port_type_get(const char *typestr, enum devlink_port_type *p_type)
+{
+ if (strcmp(typestr, "auto") == 0) {
+ *p_type = DEVLINK_PORT_TYPE_AUTO;
+ } else if (strcmp(typestr, "eth") == 0) {
+ *p_type = DEVLINK_PORT_TYPE_ETH;
+ } else if (strcmp(typestr, "ib") == 0) {
+ *p_type = DEVLINK_PORT_TYPE_IB;
+ } else {
+ pr_err("Unknown port type \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int pool_type_get(const char *typestr, enum devlink_sb_pool_type *p_type)
+{
+ if (strcmp(typestr, "ingress") == 0) {
+ *p_type = DEVLINK_SB_POOL_TYPE_INGRESS;
+ } else if (strcmp(typestr, "egress") == 0) {
+ *p_type = DEVLINK_SB_POOL_TYPE_EGRESS;
+ } else {
+ pr_err("Unknown pool type \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int threshold_type_get(const char *typestr,
+ enum devlink_sb_threshold_type *p_type)
+{
+ if (strcmp(typestr, "static") == 0) {
+ *p_type = DEVLINK_SB_THRESHOLD_TYPE_STATIC;
+ } else if (strcmp(typestr, "dynamic") == 0) {
+ *p_type = DEVLINK_SB_THRESHOLD_TYPE_DYNAMIC;
+ } else {
+ pr_err("Unknown threshold type \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int eswitch_mode_get(const char *typestr,
+ enum devlink_eswitch_mode *p_mode)
+{
+ if (strcmp(typestr, ESWITCH_MODE_LEGACY) == 0) {
+ *p_mode = DEVLINK_ESWITCH_MODE_LEGACY;
+ } else if (strcmp(typestr, ESWITCH_MODE_SWITCHDEV) == 0) {
+ *p_mode = DEVLINK_ESWITCH_MODE_SWITCHDEV;
+ } else {
+ pr_err("Unknown eswitch mode \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int eswitch_inline_mode_get(const char *typestr,
+ enum devlink_eswitch_inline_mode *p_mode)
+{
+ if (strcmp(typestr, ESWITCH_INLINE_MODE_NONE) == 0) {
+ *p_mode = DEVLINK_ESWITCH_INLINE_MODE_NONE;
+ } else if (strcmp(typestr, ESWITCH_INLINE_MODE_LINK) == 0) {
+ *p_mode = DEVLINK_ESWITCH_INLINE_MODE_LINK;
+ } else if (strcmp(typestr, ESWITCH_INLINE_MODE_NETWORK) == 0) {
+ *p_mode = DEVLINK_ESWITCH_INLINE_MODE_NETWORK;
+ } else if (strcmp(typestr, ESWITCH_INLINE_MODE_TRANSPORT) == 0) {
+ *p_mode = DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT;
+ } else {
+ pr_err("Unknown eswitch inline mode \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int dpipe_counters_enable_get(const char *typestr,
+ bool *counters_enable)
+{
+ if (strcmp(typestr, "enable") == 0) {
+ *counters_enable = 1;
+ } else if (strcmp(typestr, "disable") == 0) {
+ *counters_enable = 0;
+ } else {
+ pr_err("Unknown counter_state \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int eswitch_encap_mode_get(const char *typestr, bool *p_mode)
+{
+ if (strcmp(typestr, "enable") == 0) {
+ *p_mode = true;
+ } else if (strcmp(typestr, "disable") == 0) {
+ *p_mode = false;
+ } else {
+ pr_err("Unknown eswitch encap mode \"%s\"\n", typestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int param_cmode_get(const char *cmodestr,
+ enum devlink_param_cmode *cmode)
+{
+ if (strcmp(cmodestr, PARAM_CMODE_RUNTIME_STR) == 0) {
+ *cmode = DEVLINK_PARAM_CMODE_RUNTIME;
+ } else if (strcmp(cmodestr, PARAM_CMODE_DRIVERINIT_STR) == 0) {
+ *cmode = DEVLINK_PARAM_CMODE_DRIVERINIT;
+ } else if (strcmp(cmodestr, PARAM_CMODE_PERMANENT_STR) == 0) {
+ *cmode = DEVLINK_PARAM_CMODE_PERMANENT;
+ } else {
+ pr_err("Unknown configuration mode \"%s\"\n", cmodestr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int trap_action_get(const char *actionstr,
+ enum devlink_trap_action *p_action)
+{
+ if (strcmp(actionstr, "drop") == 0) {
+ *p_action = DEVLINK_TRAP_ACTION_DROP;
+ } else if (strcmp(actionstr, "trap") == 0) {
+ *p_action = DEVLINK_TRAP_ACTION_TRAP;
+ } else {
+ pr_err("Unknown trap action \"%s\"\n", actionstr);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+struct dl_args_metadata {
+ uint64_t o_flag;
+ char err_msg[DL_ARGS_REQUIRED_MAX_ERR_LEN];
+};
+
+static const struct dl_args_metadata dl_args_required[] = {
+ {DL_OPT_PORT_TYPE, "Port type not set."},
+ {DL_OPT_PORT_COUNT, "Port split count option expected."},
+ {DL_OPT_SB_POOL, "Pool index option expected."},
+ {DL_OPT_SB_SIZE, "Pool size option expected."},
+ {DL_OPT_SB_TYPE, "Pool type option expected."},
+ {DL_OPT_SB_THTYPE, "Pool threshold type option expected."},
+ {DL_OPT_SB_TH, "Threshold option expected."},
+ {DL_OPT_SB_TC, "TC index option expected."},
+ {DL_OPT_ESWITCH_MODE, "E-Switch mode option expected."},
+ {DL_OPT_ESWITCH_INLINE_MODE, "E-Switch inline-mode option expected."},
+ {DL_OPT_DPIPE_TABLE_NAME, "Dpipe table name expected."},
+ {DL_OPT_DPIPE_TABLE_COUNTERS, "Dpipe table counter state expected."},
+ {DL_OPT_ESWITCH_ENCAP_MODE, "E-Switch encapsulation option expected."},
+ {DL_OPT_RESOURCE_PATH, "Resource path expected."},
+ {DL_OPT_RESOURCE_SIZE, "Resource size expected."},
+ {DL_OPT_PARAM_NAME, "Parameter name expected."},
+ {DL_OPT_PARAM_VALUE, "Value to set expected."},
+ {DL_OPT_PARAM_CMODE, "Configuration mode expected."},
+ {DL_OPT_REGION_SNAPSHOT_ID, "Region snapshot id expected."},
+ {DL_OPT_REGION_ADDRESS, "Region address value expected."},
+ {DL_OPT_REGION_LENGTH, "Region length value expected."},
+ {DL_OPT_HEALTH_REPORTER_NAME, "Reporter's name is expected."},
+ {DL_OPT_TRAP_NAME, "Trap's name is expected."},
+ {DL_OPT_TRAP_GROUP_NAME, "Trap group's name is expected."},
+};
+
+static int dl_args_finding_required_validate(uint64_t o_required,
+ uint64_t o_found)
+{
+ uint64_t o_flag;
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(dl_args_required); i++) {
+ o_flag = dl_args_required[i].o_flag;
+ if ((o_required & o_flag) && !(o_found & o_flag)) {
+ pr_err("%s\n", dl_args_required[i].err_msg);
+ return -EINVAL;
+ }
+ }
+ return 0;
+}
+
+static int dl_argv_parse(struct dl *dl, uint64_t o_required,
+ uint64_t o_optional)
+{
+ struct dl_opts *opts = &dl->opts;
+ uint64_t o_all = o_required | o_optional;
+ uint64_t o_found = 0;
+ int err;
+
+ if (o_required & DL_OPT_HANDLE && o_required & DL_OPT_HANDLEP) {
+ uint64_t handle_bit;
+
+ err = dl_argv_handle_both(dl, &opts->bus_name, &opts->dev_name,
+ &opts->port_index, &handle_bit);
+ if (err)
+ return err;
+ o_found |= handle_bit;
+ } else if (o_required & DL_OPT_HANDLE) {
+ err = dl_argv_handle(dl, &opts->bus_name, &opts->dev_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HANDLE;
+ } else if (o_required & DL_OPT_HANDLEP) {
+ err = dl_argv_handle_port(dl, &opts->bus_name, &opts->dev_name,
+ &opts->port_index);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HANDLEP;
+ } else if (o_required & DL_OPT_HANDLE_REGION) {
+ err = dl_argv_handle_region(dl, &opts->bus_name,
+ &opts->dev_name,
+ &opts->region_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HANDLE_REGION;
+ }
+
+ while (dl_argc(dl)) {
+ if (dl_argv_match(dl, "type") &&
+ (o_all & DL_OPT_PORT_TYPE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = port_type_get(typestr, &opts->port_type);
+ if (err)
+ return err;
+ o_found |= DL_OPT_PORT_TYPE;
+ } else if (dl_argv_match(dl, "count") &&
+ (o_all & DL_OPT_PORT_COUNT)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->port_count);
+ if (err)
+ return err;
+ o_found |= DL_OPT_PORT_COUNT;
+ } else if (dl_argv_match(dl, "sb") &&
+ (o_all & DL_OPT_SB)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->sb_index);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB;
+ } else if (dl_argv_match(dl, "pool") &&
+ (o_all & DL_OPT_SB_POOL)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint16_t(dl, &opts->sb_pool_index);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_POOL;
+ } else if (dl_argv_match(dl, "size") &&
+ (o_all & DL_OPT_SB_SIZE)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->sb_pool_size);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_SIZE;
+ } else if (dl_argv_match(dl, "type") &&
+ (o_all & DL_OPT_SB_TYPE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = pool_type_get(typestr, &opts->sb_pool_type);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_TYPE;
+ } else if (dl_argv_match(dl, "thtype") &&
+ (o_all & DL_OPT_SB_THTYPE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = threshold_type_get(typestr,
+ &opts->sb_pool_thtype);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_THTYPE;
+ } else if (dl_argv_match(dl, "th") &&
+ (o_all & DL_OPT_SB_TH)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->sb_threshold);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_TH;
+ } else if (dl_argv_match(dl, "tc") &&
+ (o_all & DL_OPT_SB_TC)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint16_t(dl, &opts->sb_tc_index);
+ if (err)
+ return err;
+ o_found |= DL_OPT_SB_TC;
+ } else if (dl_argv_match(dl, "mode") &&
+ (o_all & DL_OPT_ESWITCH_MODE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = eswitch_mode_get(typestr, &opts->eswitch_mode);
+ if (err)
+ return err;
+ o_found |= DL_OPT_ESWITCH_MODE;
+ } else if (dl_argv_match(dl, "inline-mode") &&
+ (o_all & DL_OPT_ESWITCH_INLINE_MODE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = eswitch_inline_mode_get(
+ typestr, &opts->eswitch_inline_mode);
+ if (err)
+ return err;
+ o_found |= DL_OPT_ESWITCH_INLINE_MODE;
+ } else if (dl_argv_match(dl, "name") &&
+ (o_all & DL_OPT_DPIPE_TABLE_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->dpipe_table_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_DPIPE_TABLE_NAME;
+ } else if (dl_argv_match(dl, "counters") &&
+ (o_all & DL_OPT_DPIPE_TABLE_COUNTERS)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = dpipe_counters_enable_get(typestr,
+ &opts->dpipe_counters_enable);
+ if (err)
+ return err;
+ o_found |= DL_OPT_DPIPE_TABLE_COUNTERS;
+ } else if (dl_argv_match(dl, "encap") &&
+ (o_all & DL_OPT_ESWITCH_ENCAP_MODE)) {
+ const char *typestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &typestr);
+ if (err)
+ return err;
+ err = eswitch_encap_mode_get(typestr,
+ &opts->eswitch_encap_mode);
+ if (err)
+ return err;
+ o_found |= DL_OPT_ESWITCH_ENCAP_MODE;
+ } else if (dl_argv_match(dl, "path") &&
+ (o_all & DL_OPT_RESOURCE_PATH)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->resource_path);
+ if (err)
+ return err;
+ o_found |= DL_OPT_RESOURCE_PATH;
+ } else if (dl_argv_match(dl, "size") &&
+ (o_all & DL_OPT_RESOURCE_SIZE)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->resource_size);
+ if (err)
+ return err;
+ o_found |= DL_OPT_RESOURCE_SIZE;
+ } else if (dl_argv_match(dl, "name") &&
+ (o_all & DL_OPT_PARAM_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->param_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_PARAM_NAME;
+ } else if (dl_argv_match(dl, "value") &&
+ (o_all & DL_OPT_PARAM_VALUE)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->param_value);
+ if (err)
+ return err;
+ o_found |= DL_OPT_PARAM_VALUE;
+ } else if (dl_argv_match(dl, "cmode") &&
+ (o_all & DL_OPT_PARAM_CMODE)) {
+ const char *cmodestr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &cmodestr);
+ if (err)
+ return err;
+ err = param_cmode_get(cmodestr, &opts->cmode);
+ if (err)
+ return err;
+ o_found |= DL_OPT_PARAM_CMODE;
+ } else if (dl_argv_match(dl, "snapshot") &&
+ (o_all & DL_OPT_REGION_SNAPSHOT_ID)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint32_t(dl, &opts->region_snapshot_id);
+ if (err)
+ return err;
+ o_found |= DL_OPT_REGION_SNAPSHOT_ID;
+ } else if (dl_argv_match(dl, "address") &&
+ (o_all & DL_OPT_REGION_ADDRESS)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint64_t(dl, &opts->region_address);
+ if (err)
+ return err;
+ o_found |= DL_OPT_REGION_ADDRESS;
+ } else if (dl_argv_match(dl, "length") &&
+ (o_all & DL_OPT_REGION_LENGTH)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint64_t(dl, &opts->region_length);
+ if (err)
+ return err;
+ o_found |= DL_OPT_REGION_LENGTH;
+ } else if (dl_argv_match(dl, "file") &&
+ (o_all & DL_OPT_FLASH_FILE_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->flash_file_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_FLASH_FILE_NAME;
+ } else if (dl_argv_match(dl, "component") &&
+ (o_all & DL_OPT_FLASH_COMPONENT)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->flash_component);
+ if (err)
+ return err;
+ o_found |= DL_OPT_FLASH_COMPONENT;
+ } else if (dl_argv_match(dl, "reporter") &&
+ (o_all & DL_OPT_HEALTH_REPORTER_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->reporter_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HEALTH_REPORTER_NAME;
+ } else if (dl_argv_match(dl, "grace_period") &&
+ (o_all & DL_OPT_HEALTH_REPORTER_GRACEFUL_PERIOD)) {
+ dl_arg_inc(dl);
+ err = dl_argv_uint64_t(dl,
+ &opts->reporter_graceful_period);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HEALTH_REPORTER_GRACEFUL_PERIOD;
+ } else if (dl_argv_match(dl, "auto_recover") &&
+ (o_all & DL_OPT_HEALTH_REPORTER_AUTO_RECOVER)) {
+ dl_arg_inc(dl);
+ err = dl_argv_bool(dl, &opts->reporter_auto_recover);
+ if (err)
+ return err;
+ o_found |= DL_OPT_HEALTH_REPORTER_AUTO_RECOVER;
+ } else if (dl_argv_match(dl, "trap") &&
+ (o_all & DL_OPT_TRAP_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->trap_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_TRAP_NAME;
+ } else if (dl_argv_match(dl, "group") &&
+ (o_all & DL_OPT_TRAP_GROUP_NAME)) {
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &opts->trap_group_name);
+ if (err)
+ return err;
+ o_found |= DL_OPT_TRAP_GROUP_NAME;
+ } else if (dl_argv_match(dl, "action") &&
+ (o_all & DL_OPT_TRAP_ACTION)) {
+ const char *actionstr;
+
+ dl_arg_inc(dl);
+ err = dl_argv_str(dl, &actionstr);
+ if (err)
+ return err;
+ err = trap_action_get(actionstr, &opts->trap_action);
+ if (err)
+ return err;
+ o_found |= DL_OPT_TRAP_ACTION;
+ } else {
+ pr_err("Unknown option \"%s\"\n", dl_argv(dl));
+ return -EINVAL;
+ }
+ }
+
+ opts->present = o_found;
+
+ if ((o_optional & DL_OPT_SB) && !(o_found & DL_OPT_SB)) {
+ opts->sb_index = 0;
+ opts->present |= DL_OPT_SB;
+ }
+
+ return dl_args_finding_required_validate(o_required, o_found);
+}
+
+static void dl_opts_put(struct nlmsghdr *nlh, struct dl *dl)
+{
+ struct dl_opts *opts = &dl->opts;
+
+ if (opts->present & DL_OPT_HANDLE) {
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_BUS_NAME, opts->bus_name);
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_DEV_NAME, opts->dev_name);
+ } else if (opts->present & DL_OPT_HANDLEP) {
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_BUS_NAME, opts->bus_name);
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_DEV_NAME, opts->dev_name);
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_PORT_INDEX,
+ opts->port_index);
+ } else if (opts->present & DL_OPT_HANDLE_REGION) {
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_BUS_NAME, opts->bus_name);
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_DEV_NAME, opts->dev_name);
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_REGION_NAME,
+ opts->region_name);
+ }
+ if (opts->present & DL_OPT_PORT_TYPE)
+ mnl_attr_put_u16(nlh, DEVLINK_ATTR_PORT_TYPE,
+ opts->port_type);
+ if (opts->present & DL_OPT_PORT_COUNT)
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_PORT_SPLIT_COUNT,
+ opts->port_count);
+ if (opts->present & DL_OPT_SB)
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_SB_INDEX,
+ opts->sb_index);
+ if (opts->present & DL_OPT_SB_POOL)
+ mnl_attr_put_u16(nlh, DEVLINK_ATTR_SB_POOL_INDEX,
+ opts->sb_pool_index);
+ if (opts->present & DL_OPT_SB_SIZE)
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_SB_POOL_SIZE,
+ opts->sb_pool_size);
+ if (opts->present & DL_OPT_SB_TYPE)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_SB_POOL_TYPE,
+ opts->sb_pool_type);
+ if (opts->present & DL_OPT_SB_THTYPE)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_SB_POOL_THRESHOLD_TYPE,
+ opts->sb_pool_thtype);
+ if (opts->present & DL_OPT_SB_TH)
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_SB_THRESHOLD,
+ opts->sb_threshold);
+ if (opts->present & DL_OPT_SB_TC)
+ mnl_attr_put_u16(nlh, DEVLINK_ATTR_SB_TC_INDEX,
+ opts->sb_tc_index);
+ if (opts->present & DL_OPT_ESWITCH_MODE)
+ mnl_attr_put_u16(nlh, DEVLINK_ATTR_ESWITCH_MODE,
+ opts->eswitch_mode);
+ if (opts->present & DL_OPT_ESWITCH_INLINE_MODE)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_ESWITCH_INLINE_MODE,
+ opts->eswitch_inline_mode);
+ if (opts->present & DL_OPT_DPIPE_TABLE_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_DPIPE_TABLE_NAME,
+ opts->dpipe_table_name);
+ if (opts->present & DL_OPT_DPIPE_TABLE_COUNTERS)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_DPIPE_TABLE_COUNTERS_ENABLED,
+ opts->dpipe_counters_enable);
+ if (opts->present & DL_OPT_ESWITCH_ENCAP_MODE)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_ESWITCH_ENCAP_MODE,
+ opts->eswitch_encap_mode);
+ if ((opts->present & DL_OPT_RESOURCE_PATH) && opts->resource_id_valid)
+ mnl_attr_put_u64(nlh, DEVLINK_ATTR_RESOURCE_ID,
+ opts->resource_id);
+ if (opts->present & DL_OPT_RESOURCE_SIZE)
+ mnl_attr_put_u64(nlh, DEVLINK_ATTR_RESOURCE_SIZE,
+ opts->resource_size);
+ if (opts->present & DL_OPT_PARAM_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_PARAM_NAME,
+ opts->param_name);
+ if (opts->present & DL_OPT_PARAM_CMODE)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_PARAM_VALUE_CMODE,
+ opts->cmode);
+ if (opts->present & DL_OPT_REGION_SNAPSHOT_ID)
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_REGION_SNAPSHOT_ID,
+ opts->region_snapshot_id);
+ if (opts->present & DL_OPT_REGION_ADDRESS)
+ mnl_attr_put_u64(nlh, DEVLINK_ATTR_REGION_CHUNK_ADDR,
+ opts->region_address);
+ if (opts->present & DL_OPT_REGION_LENGTH)
+ mnl_attr_put_u64(nlh, DEVLINK_ATTR_REGION_CHUNK_LEN,
+ opts->region_length);
+ if (opts->present & DL_OPT_FLASH_FILE_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_FLASH_UPDATE_FILE_NAME,
+ opts->flash_file_name);
+ if (opts->present & DL_OPT_FLASH_COMPONENT)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_FLASH_UPDATE_COMPONENT,
+ opts->flash_component);
+ if (opts->present & DL_OPT_HEALTH_REPORTER_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_HEALTH_REPORTER_NAME,
+ opts->reporter_name);
+ if (opts->present & DL_OPT_HEALTH_REPORTER_GRACEFUL_PERIOD)
+ mnl_attr_put_u64(nlh,
+ DEVLINK_ATTR_HEALTH_REPORTER_GRACEFUL_PERIOD,
+ opts->reporter_graceful_period);
+ if (opts->present & DL_OPT_HEALTH_REPORTER_AUTO_RECOVER)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_HEALTH_REPORTER_AUTO_RECOVER,
+ opts->reporter_auto_recover);
+ if (opts->present & DL_OPT_TRAP_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_TRAP_NAME,
+ opts->trap_name);
+ if (opts->present & DL_OPT_TRAP_GROUP_NAME)
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_TRAP_GROUP_NAME,
+ opts->trap_group_name);
+ if (opts->present & DL_OPT_TRAP_ACTION)
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_TRAP_ACTION,
+ opts->trap_action);
+
+}
+
+static int dl_argv_parse_put(struct nlmsghdr *nlh, struct dl *dl,
+ uint64_t o_required, uint64_t o_optional)
+{
+ int err;
+
+ err = dl_argv_parse(dl, o_required, o_optional);
+ if (err)
+ return err;
+ dl_opts_put(nlh, dl);
+ return 0;
+}
+
+static bool dl_dump_filter(struct dl *dl, struct nlattr **tb)
+{
+ struct dl_opts *opts = &dl->opts;
+ struct nlattr *attr_bus_name = tb[DEVLINK_ATTR_BUS_NAME];
+ struct nlattr *attr_dev_name = tb[DEVLINK_ATTR_DEV_NAME];
+ struct nlattr *attr_port_index = tb[DEVLINK_ATTR_PORT_INDEX];
+ struct nlattr *attr_sb_index = tb[DEVLINK_ATTR_SB_INDEX];
+
+ if (opts->present & DL_OPT_HANDLE &&
+ attr_bus_name && attr_dev_name) {
+ const char *bus_name = mnl_attr_get_str(attr_bus_name);
+ const char *dev_name = mnl_attr_get_str(attr_dev_name);
+
+ if (strcmp(bus_name, opts->bus_name) != 0 ||
+ strcmp(dev_name, opts->dev_name) != 0)
+ return false;
+ }
+ if (opts->present & DL_OPT_HANDLEP &&
+ attr_bus_name && attr_dev_name && attr_port_index) {
+ const char *bus_name = mnl_attr_get_str(attr_bus_name);
+ const char *dev_name = mnl_attr_get_str(attr_dev_name);
+ uint32_t port_index = mnl_attr_get_u32(attr_port_index);
+
+ if (strcmp(bus_name, opts->bus_name) != 0 ||
+ strcmp(dev_name, opts->dev_name) != 0 ||
+ port_index != opts->port_index)
+ return false;
+ }
+ if (opts->present & DL_OPT_SB && attr_sb_index) {
+ uint32_t sb_index = mnl_attr_get_u32(attr_sb_index);
+
+ if (sb_index != opts->sb_index)
+ return false;
+ }
+ return true;
+}
+
+static void cmd_dev_help(void)
+{
+ pr_err("Usage: devlink dev show [ DEV ]\n");
+ pr_err(" devlink dev eswitch set DEV [ mode { legacy | switchdev } ]\n");
+ pr_err(" [ inline-mode { none | link | network | transport } ]\n");
+ pr_err(" [ encap { disable | enable } ]\n");
+ pr_err(" devlink dev eswitch show DEV\n");
+ pr_err(" devlink dev param set DEV name PARAMETER value VALUE cmode { permanent | driverinit | runtime }\n");
+ pr_err(" devlink dev param show [DEV name PARAMETER]\n");
+ pr_err(" devlink dev reload DEV\n");
+ pr_err(" devlink dev info [ DEV ]\n");
+ pr_err(" devlink dev flash DEV file PATH [ component NAME ]\n");
+}
+
+static bool cmp_arr_last_handle(struct dl *dl, const char *bus_name,
+ const char *dev_name)
+{
+ if (!dl->arr_last.present)
+ return false;
+ return strcmp(dl->arr_last.bus_name, bus_name) == 0 &&
+ strcmp(dl->arr_last.dev_name, dev_name) == 0;
+}
+
+static void arr_last_handle_set(struct dl *dl, const char *bus_name,
+ const char *dev_name)
+{
+ dl->arr_last.present = true;
+ free(dl->arr_last.dev_name);
+ free(dl->arr_last.bus_name);
+ dl->arr_last.bus_name = strdup(bus_name);
+ dl->arr_last.dev_name = strdup(dev_name);
+}
+
+static bool should_arr_last_handle_start(struct dl *dl, const char *bus_name,
+ const char *dev_name)
+{
+ return !cmp_arr_last_handle(dl, bus_name, dev_name);
+}
+
+static bool should_arr_last_handle_end(struct dl *dl, const char *bus_name,
+ const char *dev_name)
+{
+ return dl->arr_last.present &&
+ !cmp_arr_last_handle(dl, bus_name, dev_name);
+}
+
+static void __pr_out_handle_start(struct dl *dl, struct nlattr **tb,
+ bool content, bool array)
+{
+ const char *bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ const char *dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ char buf[64];
+
+ sprintf(buf, "%s/%s", bus_name, dev_name);
+
+ if (dl->json_output) {
+ if (array) {
+ if (should_arr_last_handle_end(dl, bus_name, dev_name))
+ jsonw_end_array(dl->jw);
+ if (should_arr_last_handle_start(dl, bus_name,
+ dev_name)) {
+ jsonw_name(dl->jw, buf);
+ jsonw_start_array(dl->jw);
+ jsonw_start_object(dl->jw);
+ arr_last_handle_set(dl, bus_name, dev_name);
+ } else {
+ jsonw_start_object(dl->jw);
+ }
+ } else {
+ jsonw_name(dl->jw, buf);
+ jsonw_start_object(dl->jw);
+ }
+ } else {
+ if (array) {
+ if (should_arr_last_handle_end(dl, bus_name, dev_name))
+ __pr_out_indent_dec();
+ if (should_arr_last_handle_start(dl, bus_name,
+ dev_name)) {
+ pr_out("%s%s", buf, content ? ":" : "");
+ __pr_out_newline();
+ __pr_out_indent_inc();
+ arr_last_handle_set(dl, bus_name, dev_name);
+ }
+ } else {
+ pr_out("%s%s", buf, content ? ":" : "");
+ }
+ }
+}
+
+static void pr_out_handle_start_arr(struct dl *dl, struct nlattr **tb)
+{
+ __pr_out_handle_start(dl, tb, true, true);
+}
+
+static void pr_out_handle_end(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_end_object(dl->jw);
+ else
+ __pr_out_newline();
+}
+
+static void pr_out_handle(struct dl *dl, struct nlattr **tb)
+{
+ __pr_out_handle_start(dl, tb, false, false);
+ pr_out_handle_end(dl);
+}
+
+static bool cmp_arr_last_port_handle(struct dl *dl, const char *bus_name,
+ const char *dev_name, uint32_t port_index)
+{
+ return cmp_arr_last_handle(dl, bus_name, dev_name) &&
+ dl->arr_last.port_index == port_index;
+}
+
+static void arr_last_port_handle_set(struct dl *dl, const char *bus_name,
+ const char *dev_name, uint32_t port_index)
+{
+ arr_last_handle_set(dl, bus_name, dev_name);
+ dl->arr_last.port_index = port_index;
+}
+
+static bool should_arr_last_port_handle_start(struct dl *dl,
+ const char *bus_name,
+ const char *dev_name,
+ uint32_t port_index)
+{
+ return !cmp_arr_last_port_handle(dl, bus_name, dev_name, port_index);
+}
+
+static bool should_arr_last_port_handle_end(struct dl *dl,
+ const char *bus_name,
+ const char *dev_name,
+ uint32_t port_index)
+{
+ return dl->arr_last.present &&
+ !cmp_arr_last_port_handle(dl, bus_name, dev_name, port_index);
+}
+
+static void __pr_out_port_handle_start(struct dl *dl, const char *bus_name,
+ const char *dev_name,
+ uint32_t port_index, bool try_nice,
+ bool array)
+{
+ static char buf[64];
+ char *ifname = NULL;
+
+ if (dl->no_nice_names || !try_nice ||
+ ifname_map_rev_lookup(dl, bus_name, dev_name,
+ port_index, &ifname) != 0)
+ sprintf(buf, "%s/%s/%d", bus_name, dev_name, port_index);
+ else
+ sprintf(buf, "%s", ifname);
+
+ if (dl->json_output) {
+ if (array) {
+ if (should_arr_last_port_handle_end(dl, bus_name,
+ dev_name,
+ port_index))
+ jsonw_end_array(dl->jw);
+ if (should_arr_last_port_handle_start(dl, bus_name,
+ dev_name,
+ port_index)) {
+ jsonw_name(dl->jw, buf);
+ jsonw_start_array(dl->jw);
+ jsonw_start_object(dl->jw);
+ arr_last_port_handle_set(dl, bus_name, dev_name,
+ port_index);
+ } else {
+ jsonw_start_object(dl->jw);
+ }
+ } else {
+ jsonw_name(dl->jw, buf);
+ jsonw_start_object(dl->jw);
+ }
+ } else {
+ pr_out("%s:", buf);
+ }
+}
+
+static void pr_out_port_handle_start(struct dl *dl, struct nlattr **tb, bool try_nice)
+{
+ const char *bus_name;
+ const char *dev_name;
+ uint32_t port_index;
+
+ bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ port_index = mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_INDEX]);
+ __pr_out_port_handle_start(dl, bus_name, dev_name, port_index, try_nice, false);
+}
+
+static void pr_out_port_handle_start_arr(struct dl *dl, struct nlattr **tb, bool try_nice)
+{
+ const char *bus_name;
+ const char *dev_name;
+ uint32_t port_index;
+
+ bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ port_index = mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_INDEX]);
+ __pr_out_port_handle_start(dl, bus_name, dev_name, port_index, try_nice, true);
+}
+
+static void pr_out_port_handle_end(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_end_object(dl->jw);
+ else
+ pr_out("\n");
+}
+
+
+static void pr_out_str(struct dl *dl, const char *name, const char *val)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_string_field(dl->jw, name, val);
+ else
+ pr_out("%s %s", name, val);
+}
+
+static void pr_out_bool(struct dl *dl, const char *name, bool val)
+{
+ if (dl->json_output)
+ jsonw_bool_field(dl->jw, name, val);
+ else
+ pr_out_str(dl, name, val ? "true" : "false");
+}
+
+static void pr_out_uint(struct dl *dl, const char *name, unsigned int val)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_uint_field(dl->jw, name, val);
+ else
+ pr_out("%s %u", name, val);
+}
+
+static void pr_out_u64(struct dl *dl, const char *name, uint64_t val)
+{
+ __pr_out_indent_newline(dl);
+ if (val == (uint64_t) -1)
+ return pr_out_str(dl, name, "unlimited");
+
+ if (dl->json_output)
+ jsonw_u64_field(dl->jw, name, val);
+ else
+ pr_out("%s %"PRIu64, name, val);
+}
+
+static void pr_out_bool_value(struct dl *dl, bool value)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_bool(dl->jw, value);
+ else
+ pr_out("%s", value ? "true" : "false");
+}
+
+static void pr_out_uint_value(struct dl *dl, unsigned int value)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_uint(dl->jw, value);
+ else
+ pr_out("%u", value);
+}
+
+static void pr_out_uint64_value(struct dl *dl, uint64_t value)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_u64(dl->jw, value);
+ else
+ pr_out("%"PRIu64, value);
+}
+
+static bool is_binary_eol(int i)
+{
+ return !(i%16);
+}
+
+static void pr_out_binary_value(struct dl *dl, uint8_t *data, uint32_t len)
+{
+ int i = 0;
+
+ while (i < len) {
+ if (dl->json_output)
+ jsonw_printf(dl->jw, "%d", data[i]);
+ else
+ pr_out("%02x ", data[i]);
+ i++;
+ if (!dl->json_output && is_binary_eol(i))
+ __pr_out_newline();
+ }
+ if (!dl->json_output && !is_binary_eol(i))
+ __pr_out_newline();
+}
+
+static void pr_out_str_value(struct dl *dl, const char *value)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_string(dl->jw, value);
+ else
+ pr_out("%s", value);
+}
+
+static void pr_out_name(struct dl *dl, const char *name)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output)
+ jsonw_name(dl->jw, name);
+ else
+ pr_out("%s:", name);
+}
+
+static void pr_out_region_chunk_start(struct dl *dl, uint64_t addr)
+{
+ if (dl->json_output) {
+ jsonw_name(dl->jw, "address");
+ jsonw_uint(dl->jw, addr);
+ jsonw_name(dl->jw, "data");
+ jsonw_start_array(dl->jw);
+ }
+}
+
+static void pr_out_region_chunk_end(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_end_array(dl->jw);
+}
+
+static void pr_out_region_chunk(struct dl *dl, uint8_t *data, uint32_t len,
+ uint64_t addr)
+{
+ static uint64_t align_val;
+ uint32_t i = 0;
+
+ pr_out_region_chunk_start(dl, addr);
+ while (i < len) {
+ if (!dl->json_output)
+ if (!(align_val % 16))
+ pr_out("%s%016"PRIx64" ",
+ align_val ? "\n" : "",
+ addr);
+
+ align_val++;
+
+ if (dl->json_output)
+ jsonw_printf(dl->jw, "%d", data[i]);
+ else
+ pr_out("%02x ", data[i]);
+
+ addr++;
+ i++;
+ }
+ pr_out_region_chunk_end(dl);
+}
+
+static void pr_out_section_start(struct dl *dl, const char *name)
+{
+ if (dl->json_output) {
+ jsonw_start_object(dl->jw);
+ jsonw_name(dl->jw, name);
+ jsonw_start_object(dl->jw);
+ }
+}
+
+static void pr_out_section_end(struct dl *dl)
+{
+ if (dl->json_output) {
+ if (dl->arr_last.present)
+ jsonw_end_array(dl->jw);
+ jsonw_end_object(dl->jw);
+ jsonw_end_object(dl->jw);
+ }
+}
+
+static void pr_out_array_start(struct dl *dl, const char *name)
+{
+ if (dl->json_output) {
+ jsonw_name(dl->jw, name);
+ jsonw_start_array(dl->jw);
+ } else {
+ __pr_out_indent_inc();
+ __pr_out_newline();
+ pr_out("%s:", name);
+ __pr_out_indent_inc();
+ __pr_out_newline();
+ }
+}
+
+static void pr_out_array_end(struct dl *dl)
+{
+ if (dl->json_output) {
+ jsonw_end_array(dl->jw);
+ } else {
+ __pr_out_indent_dec();
+ __pr_out_indent_dec();
+ }
+}
+
+static void pr_out_object_start(struct dl *dl, const char *name)
+{
+ if (dl->json_output) {
+ jsonw_name(dl->jw, name);
+ jsonw_start_object(dl->jw);
+ } else {
+ __pr_out_indent_inc();
+ __pr_out_newline();
+ pr_out("%s:", name);
+ __pr_out_indent_inc();
+ __pr_out_newline();
+ }
+}
+
+static void pr_out_object_end(struct dl *dl)
+{
+ if (dl->json_output) {
+ jsonw_end_object(dl->jw);
+ } else {
+ __pr_out_indent_dec();
+ __pr_out_indent_dec();
+ }
+}
+
+static void pr_out_entry_start(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_start_object(dl->jw);
+}
+
+static void pr_out_entry_end(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_end_object(dl->jw);
+ else
+ __pr_out_newline();
+}
+
+static void pr_out_stats(struct dl *dl, struct nlattr *nla_stats)
+{
+ struct nlattr *tb[DEVLINK_ATTR_STATS_MAX + 1] = {};
+ int err;
+
+ if (!dl->stats)
+ return;
+
+ err = mnl_attr_parse_nested(nla_stats, attr_stats_cb, tb);
+ if (err != MNL_CB_OK)
+ return;
+
+ pr_out_object_start(dl, "stats");
+ pr_out_object_start(dl, "rx");
+ if (tb[DEVLINK_ATTR_STATS_RX_BYTES])
+ pr_out_u64(dl, "bytes",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_STATS_RX_BYTES]));
+ if (tb[DEVLINK_ATTR_STATS_RX_PACKETS])
+ pr_out_u64(dl, "packets",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_STATS_RX_PACKETS]));
+ pr_out_object_end(dl);
+ pr_out_object_end(dl);
+}
+
+static const char *param_cmode_name(uint8_t cmode)
+{
+ switch (cmode) {
+ case DEVLINK_PARAM_CMODE_RUNTIME:
+ return PARAM_CMODE_RUNTIME_STR;
+ case DEVLINK_PARAM_CMODE_DRIVERINIT:
+ return PARAM_CMODE_DRIVERINIT_STR;
+ case DEVLINK_PARAM_CMODE_PERMANENT:
+ return PARAM_CMODE_PERMANENT_STR;
+ default: return "<unknown type>";
+ }
+}
+
+static const char *eswitch_mode_name(uint32_t mode)
+{
+ switch (mode) {
+ case DEVLINK_ESWITCH_MODE_LEGACY: return ESWITCH_MODE_LEGACY;
+ case DEVLINK_ESWITCH_MODE_SWITCHDEV: return ESWITCH_MODE_SWITCHDEV;
+ default: return "<unknown mode>";
+ }
+}
+
+static const char *eswitch_inline_mode_name(uint32_t mode)
+{
+ switch (mode) {
+ case DEVLINK_ESWITCH_INLINE_MODE_NONE:
+ return ESWITCH_INLINE_MODE_NONE;
+ case DEVLINK_ESWITCH_INLINE_MODE_LINK:
+ return ESWITCH_INLINE_MODE_LINK;
+ case DEVLINK_ESWITCH_INLINE_MODE_NETWORK:
+ return ESWITCH_INLINE_MODE_NETWORK;
+ case DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT:
+ return ESWITCH_INLINE_MODE_TRANSPORT;
+ default:
+ return "<unknown mode>";
+ }
+}
+
+static void pr_out_eswitch(struct dl *dl, struct nlattr **tb)
+{
+ __pr_out_handle_start(dl, tb, true, false);
+
+ if (tb[DEVLINK_ATTR_ESWITCH_MODE])
+ pr_out_str(dl, "mode",
+ eswitch_mode_name(mnl_attr_get_u16(tb[DEVLINK_ATTR_ESWITCH_MODE])));
+
+ if (tb[DEVLINK_ATTR_ESWITCH_INLINE_MODE])
+ pr_out_str(dl, "inline-mode",
+ eswitch_inline_mode_name(mnl_attr_get_u8(
+ tb[DEVLINK_ATTR_ESWITCH_INLINE_MODE])));
+
+ if (tb[DEVLINK_ATTR_ESWITCH_ENCAP_MODE]) {
+ bool encap_mode = !!mnl_attr_get_u8(tb[DEVLINK_ATTR_ESWITCH_ENCAP_MODE]);
+
+ pr_out_str(dl, "encap", encap_mode ? "enable" : "disable");
+ }
+
+ pr_out_handle_end(dl);
+}
+
+static int cmd_dev_eswitch_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+ pr_out_eswitch(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_dev_eswitch_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_ESWITCH_GET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+
+ pr_out_section_start(dl, "dev");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dev_eswitch_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_dev_eswitch_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_ESWITCH_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE,
+ DL_OPT_ESWITCH_MODE |
+ DL_OPT_ESWITCH_INLINE_MODE |
+ DL_OPT_ESWITCH_ENCAP_MODE);
+
+ if (err)
+ return err;
+
+ if (dl->opts.present == 1) {
+ pr_err("Need to set at least one option\n");
+ return -ENOENT;
+ }
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_dev_eswitch(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dev_help();
+ return 0;
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_dev_eswitch_set(dl);
+ } else if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_dev_eswitch_show(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+struct param_val_conv {
+ const char *name;
+ const char *vstr;
+ uint32_t vuint;
+};
+
+static bool param_val_conv_exists(const struct param_val_conv *param_val_conv,
+ uint32_t len, const char *name)
+{
+ uint32_t i;
+
+ for (i = 0; i < len; i++)
+ if (!strcmp(param_val_conv[i].name, name))
+ return true;
+
+ return false;
+}
+
+static int
+param_val_conv_uint_get(const struct param_val_conv *param_val_conv,
+ uint32_t len, const char *name, const char *vstr,
+ uint32_t *vuint)
+{
+ uint32_t i;
+
+ for (i = 0; i < len; i++)
+ if (!strcmp(param_val_conv[i].name, name) &&
+ !strcmp(param_val_conv[i].vstr, vstr)) {
+ *vuint = param_val_conv[i].vuint;
+ return 0;
+ }
+
+ return -ENOENT;
+}
+
+static int
+param_val_conv_str_get(const struct param_val_conv *param_val_conv,
+ uint32_t len, const char *name, uint32_t vuint,
+ const char **vstr)
+{
+ uint32_t i;
+
+ for (i = 0; i < len; i++)
+ if (!strcmp(param_val_conv[i].name, name) &&
+ param_val_conv[i].vuint == vuint) {
+ *vstr = param_val_conv[i].vstr;
+ return 0;
+ }
+
+ return -ENOENT;
+}
+
+static const struct param_val_conv param_val_conv[] = {
+ {
+ .name = "fw_load_policy",
+ .vstr = "driver",
+ .vuint = DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_DRIVER,
+ },
+ {
+ .name = "fw_load_policy",
+ .vstr = "flash",
+ .vuint = DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_FLASH,
+ },
+ {
+ .name = "reset_dev_on_drv_probe",
+ .vstr = "unknown",
+ .vuint = DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_UNKNOWN,
+ },
+ {
+ .name = "fw_load_policy",
+ .vstr = "unknown",
+ .vuint = DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_UNKNOWN,
+ },
+ {
+ .name = "reset_dev_on_drv_probe",
+ .vstr = "always",
+ .vuint = DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_ALWAYS,
+ },
+ {
+ .name = "reset_dev_on_drv_probe",
+ .vstr = "never",
+ .vuint = DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_NEVER,
+ },
+ {
+ .name = "reset_dev_on_drv_probe",
+ .vstr = "disk",
+ .vuint = DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_DISK,
+ },
+};
+
+#define PARAM_VAL_CONV_LEN ARRAY_SIZE(param_val_conv)
+
+static void pr_out_param_value(struct dl *dl, const char *nla_name,
+ int nla_type, struct nlattr *nl)
+{
+ struct nlattr *nla_value[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *val_attr;
+ const char *vstr;
+ bool conv_exists;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_value);
+ if (err != MNL_CB_OK)
+ return;
+
+ if (!nla_value[DEVLINK_ATTR_PARAM_VALUE_CMODE] ||
+ (nla_type != MNL_TYPE_FLAG &&
+ !nla_value[DEVLINK_ATTR_PARAM_VALUE_DATA]))
+ return;
+
+ pr_out_str(dl, "cmode",
+ param_cmode_name(mnl_attr_get_u8(nla_value[DEVLINK_ATTR_PARAM_VALUE_CMODE])));
+ val_attr = nla_value[DEVLINK_ATTR_PARAM_VALUE_DATA];
+
+ conv_exists = param_val_conv_exists(param_val_conv, PARAM_VAL_CONV_LEN,
+ nla_name);
+
+ switch (nla_type) {
+ case MNL_TYPE_U8:
+ if (conv_exists) {
+ err = param_val_conv_str_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ nla_name,
+ mnl_attr_get_u8(val_attr),
+ &vstr);
+ if (err)
+ return;
+ pr_out_str(dl, "value", vstr);
+ } else {
+ pr_out_uint(dl, "value", mnl_attr_get_u8(val_attr));
+ }
+ break;
+ case MNL_TYPE_U16:
+ if (conv_exists) {
+ err = param_val_conv_str_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ nla_name,
+ mnl_attr_get_u16(val_attr),
+ &vstr);
+ if (err)
+ return;
+ pr_out_str(dl, "value", vstr);
+ } else {
+ pr_out_uint(dl, "value", mnl_attr_get_u16(val_attr));
+ }
+ break;
+ case MNL_TYPE_U32:
+ if (conv_exists) {
+ err = param_val_conv_str_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ nla_name,
+ mnl_attr_get_u32(val_attr),
+ &vstr);
+ if (err)
+ return;
+ pr_out_str(dl, "value", vstr);
+ } else {
+ pr_out_uint(dl, "value", mnl_attr_get_u32(val_attr));
+ }
+ break;
+ case MNL_TYPE_STRING:
+ pr_out_str(dl, "value", mnl_attr_get_str(val_attr));
+ break;
+ case MNL_TYPE_FLAG:
+ pr_out_bool(dl, "value", val_attr ? true : false);
+ break;
+ }
+}
+
+static void pr_out_param(struct dl *dl, struct nlattr **tb, bool array)
+{
+ struct nlattr *nla_param[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *param_value_attr;
+ const char *nla_name;
+ int nla_type;
+ int err;
+
+ err = mnl_attr_parse_nested(tb[DEVLINK_ATTR_PARAM], attr_cb, nla_param);
+ if (err != MNL_CB_OK)
+ return;
+ if (!nla_param[DEVLINK_ATTR_PARAM_NAME] ||
+ !nla_param[DEVLINK_ATTR_PARAM_TYPE] ||
+ !nla_param[DEVLINK_ATTR_PARAM_VALUES_LIST])
+ return;
+
+ if (array)
+ pr_out_handle_start_arr(dl, tb);
+ else
+ __pr_out_handle_start(dl, tb, true, false);
+
+ nla_type = mnl_attr_get_u8(nla_param[DEVLINK_ATTR_PARAM_TYPE]);
+
+ nla_name = mnl_attr_get_str(nla_param[DEVLINK_ATTR_PARAM_NAME]);
+ pr_out_str(dl, "name", nla_name);
+
+ if (!nla_param[DEVLINK_ATTR_PARAM_GENERIC])
+ pr_out_str(dl, "type", "driver-specific");
+ else
+ pr_out_str(dl, "type", "generic");
+
+ pr_out_array_start(dl, "values");
+ mnl_attr_for_each_nested(param_value_attr,
+ nla_param[DEVLINK_ATTR_PARAM_VALUES_LIST]) {
+ pr_out_entry_start(dl);
+ pr_out_param_value(dl, nla_name, nla_type, param_value_attr);
+ pr_out_entry_end(dl);
+ }
+ pr_out_array_end(dl);
+ pr_out_handle_end(dl);
+}
+
+static int cmd_dev_param_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PARAM])
+ return MNL_CB_ERROR;
+ pr_out_param(dl, tb, true);
+ return MNL_CB_OK;
+}
+
+struct param_ctx {
+ struct dl *dl;
+ int nla_type;
+ union {
+ uint8_t vu8;
+ uint16_t vu16;
+ uint32_t vu32;
+ const char *vstr;
+ bool vbool;
+ } value;
+};
+
+static int cmd_dev_param_set_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *nla_param[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *param_value_attr;
+ enum devlink_param_cmode cmode;
+ struct param_ctx *ctx = data;
+ struct dl *dl = ctx->dl;
+ int nla_type;
+ int err;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PARAM])
+ return MNL_CB_ERROR;
+
+ err = mnl_attr_parse_nested(tb[DEVLINK_ATTR_PARAM], attr_cb, nla_param);
+ if (err != MNL_CB_OK)
+ return MNL_CB_ERROR;
+
+ if (!nla_param[DEVLINK_ATTR_PARAM_TYPE] ||
+ !nla_param[DEVLINK_ATTR_PARAM_VALUES_LIST])
+ return MNL_CB_ERROR;
+
+ nla_type = mnl_attr_get_u8(nla_param[DEVLINK_ATTR_PARAM_TYPE]);
+ mnl_attr_for_each_nested(param_value_attr,
+ nla_param[DEVLINK_ATTR_PARAM_VALUES_LIST]) {
+ struct nlattr *nla_value[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *val_attr;
+
+ err = mnl_attr_parse_nested(param_value_attr,
+ attr_cb, nla_value);
+ if (err != MNL_CB_OK)
+ return MNL_CB_ERROR;
+
+ if (!nla_value[DEVLINK_ATTR_PARAM_VALUE_CMODE] ||
+ (nla_type != MNL_TYPE_FLAG &&
+ !nla_value[DEVLINK_ATTR_PARAM_VALUE_DATA]))
+ return MNL_CB_ERROR;
+
+ cmode = mnl_attr_get_u8(nla_value[DEVLINK_ATTR_PARAM_VALUE_CMODE]);
+ if (cmode == dl->opts.cmode) {
+ val_attr = nla_value[DEVLINK_ATTR_PARAM_VALUE_DATA];
+ switch (nla_type) {
+ case MNL_TYPE_U8:
+ ctx->value.vu8 = mnl_attr_get_u8(val_attr);
+ break;
+ case MNL_TYPE_U16:
+ ctx->value.vu16 = mnl_attr_get_u16(val_attr);
+ break;
+ case MNL_TYPE_U32:
+ ctx->value.vu32 = mnl_attr_get_u32(val_attr);
+ break;
+ case MNL_TYPE_STRING:
+ ctx->value.vstr = mnl_attr_get_str(val_attr);
+ break;
+ case MNL_TYPE_FLAG:
+ ctx->value.vbool = val_attr ? true : false;
+ break;
+ }
+ break;
+ }
+ }
+ ctx->nla_type = nla_type;
+ return MNL_CB_OK;
+}
+
+static int cmd_dev_param_set(struct dl *dl)
+{
+ struct param_ctx ctx = {};
+ struct nlmsghdr *nlh;
+ bool conv_exists;
+ uint32_t val_u32;
+ uint16_t val_u16;
+ uint8_t val_u8;
+ bool val_bool;
+ int err;
+
+ err = dl_argv_parse(dl, DL_OPT_HANDLE |
+ DL_OPT_PARAM_NAME |
+ DL_OPT_PARAM_VALUE |
+ DL_OPT_PARAM_CMODE, 0);
+ if (err)
+ return err;
+
+ /* Get value type */
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PARAM_GET,
+ NLM_F_REQUEST | NLM_F_ACK);
+ dl_opts_put(nlh, dl);
+
+ ctx.dl = dl;
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dev_param_set_cb, &ctx);
+ if (err)
+ return err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PARAM_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+ dl_opts_put(nlh, dl);
+
+ conv_exists = param_val_conv_exists(param_val_conv, PARAM_VAL_CONV_LEN,
+ dl->opts.param_name);
+
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_PARAM_TYPE, ctx.nla_type);
+ switch (ctx.nla_type) {
+ case MNL_TYPE_U8:
+ if (conv_exists) {
+ err = param_val_conv_uint_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ dl->opts.param_name,
+ dl->opts.param_value,
+ &val_u32);
+ val_u8 = val_u32;
+ } else {
+ err = strtouint8_t(dl->opts.param_value, &val_u8);
+ }
+ if (err)
+ goto err_param_value_parse;
+ if (val_u8 == ctx.value.vu8)
+ return 0;
+ mnl_attr_put_u8(nlh, DEVLINK_ATTR_PARAM_VALUE_DATA, val_u8);
+ break;
+ case MNL_TYPE_U16:
+ if (conv_exists) {
+ err = param_val_conv_uint_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ dl->opts.param_name,
+ dl->opts.param_value,
+ &val_u32);
+ val_u16 = val_u32;
+ } else {
+ err = strtouint16_t(dl->opts.param_value, &val_u16);
+ }
+ if (err)
+ goto err_param_value_parse;
+ if (val_u16 == ctx.value.vu16)
+ return 0;
+ mnl_attr_put_u16(nlh, DEVLINK_ATTR_PARAM_VALUE_DATA, val_u16);
+ break;
+ case MNL_TYPE_U32:
+ if (conv_exists)
+ err = param_val_conv_uint_get(param_val_conv,
+ PARAM_VAL_CONV_LEN,
+ dl->opts.param_name,
+ dl->opts.param_value,
+ &val_u32);
+ else
+ err = strtouint32_t(dl->opts.param_value, &val_u32);
+ if (err)
+ goto err_param_value_parse;
+ if (val_u32 == ctx.value.vu32)
+ return 0;
+ mnl_attr_put_u32(nlh, DEVLINK_ATTR_PARAM_VALUE_DATA, val_u32);
+ break;
+ case MNL_TYPE_FLAG:
+ err = strtobool(dl->opts.param_value, &val_bool);
+ if (err)
+ goto err_param_value_parse;
+ if (val_bool == ctx.value.vbool)
+ return 0;
+ if (val_bool)
+ mnl_attr_put(nlh, DEVLINK_ATTR_PARAM_VALUE_DATA,
+ 0, NULL);
+ break;
+ case MNL_TYPE_STRING:
+ mnl_attr_put_strz(nlh, DEVLINK_ATTR_PARAM_VALUE_DATA,
+ dl->opts.param_value);
+ if (!strcmp(dl->opts.param_value, ctx.value.vstr))
+ return 0;
+ break;
+ default:
+ printf("Value type not supported\n");
+ return -ENOTSUP;
+ }
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+
+err_param_value_parse:
+ pr_err("Value \"%s\" is not a number or not within range\n",
+ dl->opts.param_value);
+ return err;
+}
+
+static int cmd_dev_param_show(struct dl *dl)
+{
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ struct nlmsghdr *nlh;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PARAM_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE |
+ DL_OPT_PARAM_NAME, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "param");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dev_param_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_dev_param(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_dev_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_dev_param_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_dev_param_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+static int cmd_dev_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ uint8_t reload_failed = 0;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+
+ if (tb[DEVLINK_ATTR_RELOAD_FAILED])
+ reload_failed = mnl_attr_get_u8(tb[DEVLINK_ATTR_RELOAD_FAILED]);
+
+ if (reload_failed) {
+ __pr_out_handle_start(dl, tb, true, false);
+ pr_out_bool(dl, "reload_failed", true);
+ pr_out_handle_end(dl);
+ } else {
+ pr_out_handle(dl, tb);
+ }
+
+ return MNL_CB_OK;
+}
+
+static int cmd_dev_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "dev");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dev_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static void cmd_dev_reload_help(void)
+{
+ pr_err("Usage: devlink dev reload [ DEV ]\n");
+}
+
+static int cmd_dev_reload(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dev_reload_help();
+ return 0;
+ }
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_RELOAD,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static void pr_out_versions_single(struct dl *dl, const struct nlmsghdr *nlh,
+ const char *name, int type)
+{
+ struct nlattr *version;
+
+ mnl_attr_for_each(version, nlh, sizeof(struct genlmsghdr)) {
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ const char *ver_value;
+ const char *ver_name;
+ int err;
+
+ if (mnl_attr_get_type(version) != type)
+ continue;
+
+ err = mnl_attr_parse_nested(version, attr_cb, tb);
+ if (err != MNL_CB_OK)
+ continue;
+
+ if (!tb[DEVLINK_ATTR_INFO_VERSION_NAME] ||
+ !tb[DEVLINK_ATTR_INFO_VERSION_VALUE])
+ continue;
+
+ if (name) {
+ pr_out_object_start(dl, name);
+ name = NULL;
+ }
+
+ ver_name = mnl_attr_get_str(tb[DEVLINK_ATTR_INFO_VERSION_NAME]);
+ ver_value = mnl_attr_get_str(tb[DEVLINK_ATTR_INFO_VERSION_VALUE]);
+
+ pr_out_str(dl, ver_name, ver_value);
+ if (!dl->json_output)
+ __pr_out_newline();
+ }
+
+ if (!name)
+ pr_out_object_end(dl);
+}
+
+static void pr_out_info(struct dl *dl, const struct nlmsghdr *nlh,
+ struct nlattr **tb, bool has_versions)
+{
+ __pr_out_handle_start(dl, tb, true, false);
+
+ __pr_out_indent_inc();
+ if (tb[DEVLINK_ATTR_INFO_DRIVER_NAME]) {
+ struct nlattr *nla_drv = tb[DEVLINK_ATTR_INFO_DRIVER_NAME];
+
+ if (!dl->json_output)
+ __pr_out_newline();
+ pr_out_str(dl, "driver", mnl_attr_get_str(nla_drv));
+ }
+
+ if (tb[DEVLINK_ATTR_INFO_SERIAL_NUMBER]) {
+ struct nlattr *nla_sn = tb[DEVLINK_ATTR_INFO_SERIAL_NUMBER];
+
+ if (!dl->json_output)
+ __pr_out_newline();
+ pr_out_str(dl, "serial_number", mnl_attr_get_str(nla_sn));
+ }
+ __pr_out_indent_dec();
+
+ if (has_versions) {
+ pr_out_object_start(dl, "versions");
+
+ pr_out_versions_single(dl, nlh, "fixed",
+ DEVLINK_ATTR_INFO_VERSION_FIXED);
+ pr_out_versions_single(dl, nlh, "running",
+ DEVLINK_ATTR_INFO_VERSION_RUNNING);
+ pr_out_versions_single(dl, nlh, "stored",
+ DEVLINK_ATTR_INFO_VERSION_STORED);
+
+ pr_out_object_end(dl);
+ }
+
+ pr_out_handle_end(dl);
+}
+
+static int cmd_versions_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ bool has_versions, has_info;
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+
+ has_versions = tb[DEVLINK_ATTR_INFO_VERSION_FIXED] ||
+ tb[DEVLINK_ATTR_INFO_VERSION_RUNNING] ||
+ tb[DEVLINK_ATTR_INFO_VERSION_STORED];
+ has_info = tb[DEVLINK_ATTR_INFO_DRIVER_NAME] ||
+ tb[DEVLINK_ATTR_INFO_SERIAL_NUMBER] ||
+ has_versions;
+
+ if (has_info)
+ pr_out_info(dl, nlh, tb, has_versions);
+
+ return MNL_CB_OK;
+}
+
+static void cmd_dev_info_help(void)
+{
+ pr_err("Usage: devlink dev info [ DEV ]\n");
+}
+
+static int cmd_dev_info(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argv_match(dl, "help")) {
+ cmd_dev_info_help();
+ return 0;
+ }
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_INFO_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "info");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_versions_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static void cmd_dev_flash_help(void)
+{
+ pr_err("Usage: devlink dev flash DEV file PATH [ component NAME ]\n");
+}
+
+
+struct cmd_dev_flash_status_ctx {
+ struct dl *dl;
+ char *last_msg;
+ char *last_component;
+ uint8_t not_first:1,
+ last_pc:1,
+ received_end:1,
+ flash_done:1;
+};
+
+static int nullstrcmp(const char *str1, const char *str2)
+{
+ if (str1 && str2)
+ return strcmp(str1, str2);
+ if (!str1 && !str2)
+ return 0;
+ return str1 ? 1 : -1;
+}
+
+static int cmd_dev_flash_status_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct cmd_dev_flash_status_ctx *ctx = data;
+ struct dl_opts *opts = &ctx->dl->opts;
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ const char *component = NULL;
+ uint64_t done = 0, total = 0;
+ const char *msg = NULL;
+ const char *bus_name;
+ const char *dev_name;
+
+ if (genl->cmd != DEVLINK_CMD_FLASH_UPDATE_STATUS &&
+ genl->cmd != DEVLINK_CMD_FLASH_UPDATE_END)
+ return MNL_CB_STOP;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+ bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ if (strcmp(bus_name, opts->bus_name) ||
+ strcmp(dev_name, opts->dev_name))
+ return MNL_CB_ERROR;
+
+ if (genl->cmd == DEVLINK_CMD_FLASH_UPDATE_END && ctx->not_first) {
+ pr_out("\n");
+ free(ctx->last_msg);
+ free(ctx->last_component);
+ ctx->received_end = 1;
+ return MNL_CB_STOP;
+ }
+
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG])
+ msg = mnl_attr_get_str(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG]);
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_COMPONENT])
+ component = mnl_attr_get_str(tb[DEVLINK_ATTR_FLASH_UPDATE_COMPONENT]);
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE])
+ done = mnl_attr_get_u64(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE]);
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL])
+ total = mnl_attr_get_u64(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL]);
+
+ if (!nullstrcmp(msg, ctx->last_msg) &&
+ !nullstrcmp(component, ctx->last_component) &&
+ ctx->last_pc && ctx->not_first) {
+ pr_out_tty("\b\b\b\b\b"); /* clean percentage */
+ } else {
+ if (ctx->not_first)
+ pr_out("\n");
+ if (component) {
+ pr_out("[%s] ", component);
+ free(ctx->last_component);
+ ctx->last_component = strdup(component);
+ }
+ if (msg) {
+ pr_out("%s", msg);
+ free(ctx->last_msg);
+ ctx->last_msg = strdup(msg);
+ }
+ }
+ if (total) {
+ pr_out_tty(" %3lu%%", (done * 100) / total);
+ ctx->last_pc = 1;
+ } else {
+ ctx->last_pc = 0;
+ }
+ fflush(stdout);
+ ctx->not_first = 1;
+
+ return MNL_CB_STOP;
+}
+
+static int cmd_dev_flash_fds_process(struct cmd_dev_flash_status_ctx *ctx,
+ struct mnlg_socket *nlg_ntf,
+ int pipe_r)
+{
+ int nlfd = mnlg_socket_get_fd(nlg_ntf);
+ fd_set fds[3];
+ int fdmax;
+ int i;
+ int err;
+ int err2;
+
+ for (i = 0; i < 3; i++)
+ FD_ZERO(&fds[i]);
+ FD_SET(pipe_r, &fds[0]);
+ fdmax = pipe_r + 1;
+ FD_SET(nlfd, &fds[0]);
+ if (nlfd >= fdmax)
+ fdmax = nlfd + 1;
+
+ while (select(fdmax, &fds[0], &fds[1], &fds[2], NULL) < 0) {
+ if (errno == EINTR)
+ continue;
+ pr_err("select() failed\n");
+ return -errno;
+ }
+ if (FD_ISSET(nlfd, &fds[0])) {
+ err = _mnlg_socket_recv_run(nlg_ntf,
+ cmd_dev_flash_status_cb, ctx);
+ if (err)
+ return err;
+ }
+ if (FD_ISSET(pipe_r, &fds[0])) {
+ err = read(pipe_r, &err2, sizeof(err2));
+ if (err == -1) {
+ pr_err("Failed to read pipe\n");
+ return -errno;
+ }
+ if (err2)
+ return err2;
+ ctx->flash_done = 1;
+ }
+ return 0;
+}
+
+
+static int cmd_dev_flash(struct dl *dl)
+{
+ struct cmd_dev_flash_status_ctx ctx = {.dl = dl,};
+ struct mnlg_socket *nlg_ntf;
+ struct nlmsghdr *nlh;
+ int pipe_r, pipe_w;
+ int pipe_fds[2];
+ pid_t pid;
+ int err;
+
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dev_flash_help();
+ return 0;
+ }
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_FLASH_UPDATE,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE | DL_OPT_FLASH_FILE_NAME,
+ DL_OPT_FLASH_COMPONENT);
+ if (err)
+ return err;
+
+ nlg_ntf = mnlg_socket_open(DEVLINK_GENL_NAME, DEVLINK_GENL_VERSION);
+ if (!nlg_ntf)
+ return err;
+
+ err = _mnlg_socket_group_add(nlg_ntf, DEVLINK_GENL_MCGRP_CONFIG_NAME);
+ if (err)
+ return err;
+
+ err = pipe(pipe_fds);
+ if (err == -1)
+ return -errno;
+ pipe_r = pipe_fds[0];
+ pipe_w = pipe_fds[1];
+
+ pid = fork();
+ if (pid == -1) {
+ close(pipe_r);
+ close(pipe_w);
+ return -errno;
+ } else if (!pid) {
+ /* In child, just execute the flash and pass returned
+ * value through pipe once it is done.
+ */
+ close(pipe_r);
+ err = _mnlg_socket_send(dl->nlg, nlh);
+ write(pipe_w, &err, sizeof(err));
+ close(pipe_w);
+ exit(0);
+ }
+ close(pipe_w);
+
+ do {
+ err = cmd_dev_flash_fds_process(&ctx, nlg_ntf, pipe_r);
+ if (err)
+ goto out;
+ } while (!ctx.flash_done || (ctx.not_first && !ctx.received_end));
+
+ err = _mnlg_socket_recv_run(dl->nlg, NULL, NULL);
+out:
+ close(pipe_r);
+ mnlg_socket_close(nlg_ntf);
+ return err;
+}
+
+static int cmd_dev(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_dev_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_dev_show(dl);
+ } else if (dl_argv_match(dl, "eswitch")) {
+ dl_arg_inc(dl);
+ return cmd_dev_eswitch(dl);
+ } else if (dl_argv_match(dl, "reload")) {
+ dl_arg_inc(dl);
+ return cmd_dev_reload(dl);
+ } else if (dl_argv_match(dl, "param")) {
+ dl_arg_inc(dl);
+ return cmd_dev_param(dl);
+ } else if (dl_argv_match(dl, "info")) {
+ dl_arg_inc(dl);
+ return cmd_dev_info(dl);
+ } else if (dl_argv_match(dl, "flash")) {
+ dl_arg_inc(dl);
+ return cmd_dev_flash(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void cmd_port_help(void)
+{
+ pr_err("Usage: devlink port show [ DEV/PORT_INDEX ]\n");
+ pr_err(" devlink port set DEV/PORT_INDEX [ type { eth | ib | auto} ]\n");
+ pr_err(" devlink port split DEV/PORT_INDEX count COUNT\n");
+ pr_err(" devlink port unsplit DEV/PORT_INDEX\n");
+}
+
+static const char *port_type_name(uint32_t type)
+{
+ switch (type) {
+ case DEVLINK_PORT_TYPE_NOTSET: return "notset";
+ case DEVLINK_PORT_TYPE_AUTO: return "auto";
+ case DEVLINK_PORT_TYPE_ETH: return "eth";
+ case DEVLINK_PORT_TYPE_IB: return "ib";
+ default: return "<unknown type>";
+ }
+}
+
+static const char *port_flavour_name(uint16_t flavour)
+{
+ switch (flavour) {
+ case DEVLINK_PORT_FLAVOUR_PHYSICAL:
+ return "physical";
+ case DEVLINK_PORT_FLAVOUR_CPU:
+ return "cpu";
+ case DEVLINK_PORT_FLAVOUR_DSA:
+ return "dsa";
+ case DEVLINK_PORT_FLAVOUR_PCI_PF:
+ return "pcipf";
+ case DEVLINK_PORT_FLAVOUR_PCI_VF:
+ return "pcivf";
+ default:
+ return "<unknown flavour>";
+ }
+}
+
+static void pr_out_port_pfvf_num(struct dl *dl, struct nlattr **tb)
+{
+ uint16_t fn_num;
+
+ if (tb[DEVLINK_ATTR_PORT_PCI_PF_NUMBER]) {
+ fn_num = mnl_attr_get_u16(tb[DEVLINK_ATTR_PORT_PCI_PF_NUMBER]);
+ pr_out_uint(dl, "pfnum", fn_num);
+ }
+ if (tb[DEVLINK_ATTR_PORT_PCI_VF_NUMBER]) {
+ fn_num = mnl_attr_get_u16(tb[DEVLINK_ATTR_PORT_PCI_VF_NUMBER]);
+ pr_out_uint(dl, "vfnum", fn_num);
+ }
+}
+
+static void pr_out_port(struct dl *dl, struct nlattr **tb)
+{
+ struct nlattr *pt_attr = tb[DEVLINK_ATTR_PORT_TYPE];
+ struct nlattr *dpt_attr = tb[DEVLINK_ATTR_PORT_DESIRED_TYPE];
+
+ pr_out_port_handle_start(dl, tb, false);
+ if (pt_attr) {
+ uint16_t port_type = mnl_attr_get_u16(pt_attr);
+
+ pr_out_str(dl, "type", port_type_name(port_type));
+ if (dpt_attr) {
+ uint16_t des_port_type = mnl_attr_get_u16(dpt_attr);
+
+ if (port_type != des_port_type)
+ pr_out_str(dl, "des_type",
+ port_type_name(des_port_type));
+ }
+ }
+ if (tb[DEVLINK_ATTR_PORT_NETDEV_NAME])
+ pr_out_str(dl, "netdev",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_PORT_NETDEV_NAME]));
+ if (tb[DEVLINK_ATTR_PORT_IBDEV_NAME])
+ pr_out_str(dl, "ibdev",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_PORT_IBDEV_NAME]));
+ if (tb[DEVLINK_ATTR_PORT_FLAVOUR]) {
+ uint16_t port_flavour =
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_PORT_FLAVOUR]);
+
+ pr_out_str(dl, "flavour", port_flavour_name(port_flavour));
+
+ switch (port_flavour) {
+ case DEVLINK_PORT_FLAVOUR_PCI_PF:
+ case DEVLINK_PORT_FLAVOUR_PCI_VF:
+ pr_out_port_pfvf_num(dl, tb);
+ break;
+ default:
+ break;
+ }
+ }
+ if (tb[DEVLINK_ATTR_PORT_NUMBER]) {
+ uint32_t port_number;
+
+ port_number = mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_NUMBER]);
+ pr_out_uint(dl, "port", port_number);
+ }
+ if (tb[DEVLINK_ATTR_PORT_SPLIT_GROUP])
+ pr_out_uint(dl, "split_group",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_SPLIT_GROUP]));
+ pr_out_port_handle_end(dl);
+}
+
+static int cmd_port_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX])
+ return MNL_CB_ERROR;
+ pr_out_port(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_port_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PORT_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "port");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_port_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_port_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PORT_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP | DL_OPT_PORT_TYPE, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_port_split(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PORT_SPLIT,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP | DL_OPT_PORT_COUNT, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_port_unsplit(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_PORT_UNSPLIT,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_port(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_port_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_port_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_port_set(dl);
+ } else if (dl_argv_match(dl, "split")) {
+ dl_arg_inc(dl);
+ return cmd_port_split(dl);
+ } else if (dl_argv_match(dl, "unsplit")) {
+ dl_arg_inc(dl);
+ return cmd_port_unsplit(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void cmd_sb_help(void)
+{
+ pr_err("Usage: devlink sb show [ DEV [ sb SB_INDEX ] ]\n");
+ pr_err(" devlink sb pool show [ DEV [ sb SB_INDEX ] pool POOL_INDEX ]\n");
+ pr_err(" devlink sb pool set DEV [ sb SB_INDEX ] pool POOL_INDEX\n");
+ pr_err(" size POOL_SIZE thtype { static | dynamic }\n");
+ pr_err(" devlink sb port pool show [ DEV/PORT_INDEX [ sb SB_INDEX ]\n");
+ pr_err(" pool POOL_INDEX ]\n");
+ pr_err(" devlink sb port pool set DEV/PORT_INDEX [ sb SB_INDEX ]\n");
+ pr_err(" pool POOL_INDEX th THRESHOLD\n");
+ pr_err(" devlink sb tc bind show [ DEV/PORT_INDEX [ sb SB_INDEX ] tc TC_INDEX\n");
+ pr_err(" type { ingress | egress } ]\n");
+ pr_err(" devlink sb tc bind set DEV/PORT_INDEX [ sb SB_INDEX ] tc TC_INDEX\n");
+ pr_err(" type { ingress | egress } pool POOL_INDEX\n");
+ pr_err(" th THRESHOLD\n");
+ pr_err(" devlink sb occupancy show { DEV | DEV/PORT_INDEX } [ sb SB_INDEX ]\n");
+ pr_err(" devlink sb occupancy snapshot DEV [ sb SB_INDEX ]\n");
+ pr_err(" devlink sb occupancy clearmax DEV [ sb SB_INDEX ]\n");
+}
+
+static void pr_out_sb(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_handle_start_arr(dl, tb);
+ pr_out_uint(dl, "sb",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_INDEX]));
+ pr_out_uint(dl, "size",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_SIZE]));
+ pr_out_uint(dl, "ing_pools",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_INGRESS_POOL_COUNT]));
+ pr_out_uint(dl, "eg_pools",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_EGRESS_POOL_COUNT]));
+ pr_out_uint(dl, "ing_tcs",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_INGRESS_TC_COUNT]));
+ pr_out_uint(dl, "eg_tcs",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_EGRESS_TC_COUNT]));
+ pr_out_handle_end(dl);
+}
+
+static int cmd_sb_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_SB_INDEX] || !tb[DEVLINK_ATTR_SB_SIZE] ||
+ !tb[DEVLINK_ATTR_SB_INGRESS_POOL_COUNT] ||
+ !tb[DEVLINK_ATTR_SB_EGRESS_POOL_COUNT] ||
+ !tb[DEVLINK_ATTR_SB_INGRESS_TC_COUNT] ||
+ !tb[DEVLINK_ATTR_SB_EGRESS_TC_COUNT])
+ return MNL_CB_ERROR;
+ pr_out_sb(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_sb_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, DL_OPT_SB);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "sb");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_sb_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static const char *pool_type_name(uint8_t type)
+{
+ switch (type) {
+ case DEVLINK_SB_POOL_TYPE_INGRESS: return "ingress";
+ case DEVLINK_SB_POOL_TYPE_EGRESS: return "egress";
+ default: return "<unknown type>";
+ }
+}
+
+static const char *threshold_type_name(uint8_t type)
+{
+ switch (type) {
+ case DEVLINK_SB_THRESHOLD_TYPE_STATIC: return "static";
+ case DEVLINK_SB_THRESHOLD_TYPE_DYNAMIC: return "dynamic";
+ default: return "<unknown type>";
+ }
+}
+
+static void pr_out_sb_pool(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_handle_start_arr(dl, tb);
+ pr_out_uint(dl, "sb",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_INDEX]));
+ pr_out_uint(dl, "pool",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_POOL_INDEX]));
+ pr_out_str(dl, "type",
+ pool_type_name(mnl_attr_get_u8(tb[DEVLINK_ATTR_SB_POOL_TYPE])));
+ pr_out_uint(dl, "size",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_POOL_SIZE]));
+ pr_out_str(dl, "thtype",
+ threshold_type_name(mnl_attr_get_u8(tb[DEVLINK_ATTR_SB_POOL_THRESHOLD_TYPE])));
+ if (tb[DEVLINK_ATTR_SB_POOL_CELL_SIZE])
+ pr_out_uint(dl, "cell_size",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_POOL_CELL_SIZE]));
+ pr_out_handle_end(dl);
+}
+
+static int cmd_sb_pool_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_SB_INDEX] || !tb[DEVLINK_ATTR_SB_POOL_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_POOL_TYPE] || !tb[DEVLINK_ATTR_SB_POOL_SIZE] ||
+ !tb[DEVLINK_ATTR_SB_POOL_THRESHOLD_TYPE])
+ return MNL_CB_ERROR;
+ pr_out_sb_pool(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_sb_pool_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_POOL_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE | DL_OPT_SB_POOL,
+ DL_OPT_SB);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "pool");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_sb_pool_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_sb_pool_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_POOL_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE | DL_OPT_SB_POOL |
+ DL_OPT_SB_SIZE | DL_OPT_SB_THTYPE, DL_OPT_SB);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_sb_pool(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_sb_pool_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_sb_pool_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void pr_out_sb_port_pool(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_port_handle_start_arr(dl, tb, true);
+ pr_out_uint(dl, "sb",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_INDEX]));
+ pr_out_uint(dl, "pool",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_POOL_INDEX]));
+ pr_out_uint(dl, "threshold",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_THRESHOLD]));
+ pr_out_port_handle_end(dl);
+}
+
+static int cmd_sb_port_pool_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX] || !tb[DEVLINK_ATTR_SB_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_POOL_INDEX] || !tb[DEVLINK_ATTR_SB_THRESHOLD])
+ return MNL_CB_ERROR;
+ pr_out_sb_port_pool(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_sb_port_pool_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_PORT_POOL_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLEP | DL_OPT_SB_POOL,
+ DL_OPT_SB);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "port_pool");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_sb_port_pool_show_cb, dl);
+ pr_out_section_end(dl);
+ return 0;
+}
+
+static int cmd_sb_port_pool_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_PORT_POOL_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP | DL_OPT_SB_POOL |
+ DL_OPT_SB_TH, DL_OPT_SB);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_sb_port_pool(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_sb_port_pool_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_sb_port_pool_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int cmd_sb_port(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "pool")) {
+ dl_arg_inc(dl);
+ return cmd_sb_port_pool(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void pr_out_sb_tc_bind(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_port_handle_start_arr(dl, tb, true);
+ pr_out_uint(dl, "sb",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_INDEX]));
+ pr_out_uint(dl, "tc",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_TC_INDEX]));
+ pr_out_str(dl, "type",
+ pool_type_name(mnl_attr_get_u8(tb[DEVLINK_ATTR_SB_POOL_TYPE])));
+ pr_out_uint(dl, "pool",
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_POOL_INDEX]));
+ pr_out_uint(dl, "threshold",
+ mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_THRESHOLD]));
+ pr_out_port_handle_end(dl);
+}
+
+static int cmd_sb_tc_bind_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX] || !tb[DEVLINK_ATTR_SB_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_TC_INDEX] || !tb[DEVLINK_ATTR_SB_POOL_TYPE] ||
+ !tb[DEVLINK_ATTR_SB_POOL_INDEX] || !tb[DEVLINK_ATTR_SB_THRESHOLD])
+ return MNL_CB_ERROR;
+ pr_out_sb_tc_bind(dl, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_sb_tc_bind_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_TC_POOL_BIND_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP | DL_OPT_SB_TC |
+ DL_OPT_SB_TYPE, DL_OPT_SB);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "tc_bind");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_sb_tc_bind_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_sb_tc_bind_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_TC_POOL_BIND_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLEP | DL_OPT_SB_TC |
+ DL_OPT_SB_TYPE | DL_OPT_SB_POOL | DL_OPT_SB_TH,
+ DL_OPT_SB);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_sb_tc_bind(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_sb_tc_bind_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_sb_tc_bind_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int cmd_sb_tc(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "bind")) {
+ dl_arg_inc(dl);
+ return cmd_sb_tc_bind(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+struct occ_item {
+ struct list_head list;
+ uint32_t index;
+ uint32_t cur;
+ uint32_t max;
+ uint32_t bound_pool_index;
+};
+
+struct occ_port {
+ struct list_head list;
+ char *bus_name;
+ char *dev_name;
+ uint32_t port_index;
+ uint32_t sb_index;
+ struct list_head pool_list;
+ struct list_head ing_tc_list;
+ struct list_head eg_tc_list;
+};
+
+struct occ_show {
+ struct dl *dl;
+ int err;
+ struct list_head port_list;
+};
+
+static struct occ_item *occ_item_alloc(void)
+{
+ return calloc(1, sizeof(struct occ_item));
+}
+
+static void occ_item_free(struct occ_item *occ_item)
+{
+ free(occ_item);
+}
+
+static struct occ_port *occ_port_alloc(uint32_t port_index)
+{
+ struct occ_port *occ_port;
+
+ occ_port = calloc(1, sizeof(*occ_port));
+ if (!occ_port)
+ return NULL;
+ occ_port->port_index = port_index;
+ INIT_LIST_HEAD(&occ_port->pool_list);
+ INIT_LIST_HEAD(&occ_port->ing_tc_list);
+ INIT_LIST_HEAD(&occ_port->eg_tc_list);
+ return occ_port;
+}
+
+static void occ_port_free(struct occ_port *occ_port)
+{
+ struct occ_item *occ_item, *tmp;
+
+ list_for_each_entry_safe(occ_item, tmp, &occ_port->pool_list, list)
+ occ_item_free(occ_item);
+ list_for_each_entry_safe(occ_item, tmp, &occ_port->ing_tc_list, list)
+ occ_item_free(occ_item);
+ list_for_each_entry_safe(occ_item, tmp, &occ_port->eg_tc_list, list)
+ occ_item_free(occ_item);
+}
+
+static struct occ_show *occ_show_alloc(struct dl *dl)
+{
+ struct occ_show *occ_show;
+
+ occ_show = calloc(1, sizeof(*occ_show));
+ if (!occ_show)
+ return NULL;
+ occ_show->dl = dl;
+ INIT_LIST_HEAD(&occ_show->port_list);
+ return occ_show;
+}
+
+static void occ_show_free(struct occ_show *occ_show)
+{
+ struct occ_port *occ_port, *tmp;
+
+ list_for_each_entry_safe(occ_port, tmp, &occ_show->port_list, list)
+ occ_port_free(occ_port);
+}
+
+static struct occ_port *occ_port_get(struct occ_show *occ_show,
+ struct nlattr **tb)
+{
+ struct occ_port *occ_port;
+ uint32_t port_index;
+
+ port_index = mnl_attr_get_u32(tb[DEVLINK_ATTR_PORT_INDEX]);
+
+ list_for_each_entry_reverse(occ_port, &occ_show->port_list, list) {
+ if (occ_port->port_index == port_index)
+ return occ_port;
+ }
+ occ_port = occ_port_alloc(port_index);
+ if (!occ_port)
+ return NULL;
+ list_add_tail(&occ_port->list, &occ_show->port_list);
+ return occ_port;
+}
+
+static void pr_out_occ_show_item_list(const char *label, struct list_head *list,
+ bool bound_pool)
+{
+ struct occ_item *occ_item;
+ int i = 1;
+
+ pr_out_sp(7, " %s:", label);
+ list_for_each_entry(occ_item, list, list) {
+ if ((i - 1) % 4 == 0 && i != 1)
+ pr_out_sp(7, " ");
+ if (bound_pool)
+ pr_out_sp(7, "%2u(%u):", occ_item->index,
+ occ_item->bound_pool_index);
+ else
+ pr_out_sp(7, "%2u:", occ_item->index);
+ pr_out_sp(21, "%10u/%u", occ_item->cur, occ_item->max);
+ if (i++ % 4 == 0)
+ pr_out("\n");
+ }
+ if ((i - 1) % 4 != 0)
+ pr_out("\n");
+}
+
+static void pr_out_json_occ_show_item_list(struct dl *dl, const char *label,
+ struct list_head *list,
+ bool bound_pool)
+{
+ struct occ_item *occ_item;
+ char buf[32];
+
+ jsonw_name(dl->jw, label);
+ jsonw_start_object(dl->jw);
+ list_for_each_entry(occ_item, list, list) {
+ sprintf(buf, "%u", occ_item->index);
+ jsonw_name(dl->jw, buf);
+ jsonw_start_object(dl->jw);
+ if (bound_pool)
+ jsonw_uint_field(dl->jw, "bound_pool",
+ occ_item->bound_pool_index);
+ jsonw_uint_field(dl->jw, "current", occ_item->cur);
+ jsonw_uint_field(dl->jw, "max", occ_item->max);
+ jsonw_end_object(dl->jw);
+ }
+ jsonw_end_object(dl->jw);
+}
+
+static void pr_out_occ_show_port(struct dl *dl, struct occ_port *occ_port)
+{
+ if (dl->json_output) {
+ pr_out_json_occ_show_item_list(dl, "pool",
+ &occ_port->pool_list, false);
+ pr_out_json_occ_show_item_list(dl, "itc",
+ &occ_port->ing_tc_list, true);
+ pr_out_json_occ_show_item_list(dl, "etc",
+ &occ_port->eg_tc_list, true);
+ } else {
+ pr_out("\n");
+ pr_out_occ_show_item_list("pool", &occ_port->pool_list, false);
+ pr_out_occ_show_item_list("itc", &occ_port->ing_tc_list, true);
+ pr_out_occ_show_item_list("etc", &occ_port->eg_tc_list, true);
+ }
+}
+
+static void pr_out_occ_show(struct occ_show *occ_show)
+{
+ struct dl *dl = occ_show->dl;
+ struct dl_opts *opts = &dl->opts;
+ struct occ_port *occ_port;
+
+ list_for_each_entry(occ_port, &occ_show->port_list, list) {
+ __pr_out_port_handle_start(dl, opts->bus_name, opts->dev_name,
+ occ_port->port_index, true, false);
+ pr_out_occ_show_port(dl, occ_port);
+ pr_out_port_handle_end(dl);
+ }
+}
+
+static void cmd_sb_occ_port_pool_process(struct occ_show *occ_show,
+ struct nlattr **tb)
+{
+ struct occ_port *occ_port;
+ struct occ_item *occ_item;
+
+ if (occ_show->err || !dl_dump_filter(occ_show->dl, tb))
+ return;
+
+ occ_port = occ_port_get(occ_show, tb);
+ if (!occ_port) {
+ occ_show->err = -ENOMEM;
+ return;
+ }
+
+ occ_item = occ_item_alloc();
+ if (!occ_item) {
+ occ_show->err = -ENOMEM;
+ return;
+ }
+ occ_item->index = mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_POOL_INDEX]);
+ occ_item->cur = mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_OCC_CUR]);
+ occ_item->max = mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_OCC_MAX]);
+ list_add_tail(&occ_item->list, &occ_port->pool_list);
+}
+
+static int cmd_sb_occ_port_pool_process_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct occ_show *occ_show = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX] || !tb[DEVLINK_ATTR_SB_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_POOL_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_OCC_CUR] || !tb[DEVLINK_ATTR_SB_OCC_MAX])
+ return MNL_CB_ERROR;
+ cmd_sb_occ_port_pool_process(occ_show, tb);
+ return MNL_CB_OK;
+}
+
+static void cmd_sb_occ_tc_pool_process(struct occ_show *occ_show,
+ struct nlattr **tb)
+{
+ struct occ_port *occ_port;
+ struct occ_item *occ_item;
+ uint8_t pool_type;
+
+ if (occ_show->err || !dl_dump_filter(occ_show->dl, tb))
+ return;
+
+ occ_port = occ_port_get(occ_show, tb);
+ if (!occ_port) {
+ occ_show->err = -ENOMEM;
+ return;
+ }
+
+ occ_item = occ_item_alloc();
+ if (!occ_item) {
+ occ_show->err = -ENOMEM;
+ return;
+ }
+ occ_item->index = mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_TC_INDEX]);
+ occ_item->cur = mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_OCC_CUR]);
+ occ_item->max = mnl_attr_get_u32(tb[DEVLINK_ATTR_SB_OCC_MAX]);
+ occ_item->bound_pool_index =
+ mnl_attr_get_u16(tb[DEVLINK_ATTR_SB_POOL_INDEX]);
+ pool_type = mnl_attr_get_u8(tb[DEVLINK_ATTR_SB_POOL_TYPE]);
+ if (pool_type == DEVLINK_SB_POOL_TYPE_INGRESS)
+ list_add_tail(&occ_item->list, &occ_port->ing_tc_list);
+ else if (pool_type == DEVLINK_SB_POOL_TYPE_EGRESS)
+ list_add_tail(&occ_item->list, &occ_port->eg_tc_list);
+ else
+ occ_item_free(occ_item);
+}
+
+static int cmd_sb_occ_tc_pool_process_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct occ_show *occ_show = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX] || !tb[DEVLINK_ATTR_SB_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_TC_INDEX] || !tb[DEVLINK_ATTR_SB_POOL_TYPE] ||
+ !tb[DEVLINK_ATTR_SB_POOL_INDEX] ||
+ !tb[DEVLINK_ATTR_SB_OCC_CUR] || !tb[DEVLINK_ATTR_SB_OCC_MAX])
+ return MNL_CB_ERROR;
+ cmd_sb_occ_tc_pool_process(occ_show, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_sb_occ_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct occ_show *occ_show;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP;
+ int err;
+
+ err = dl_argv_parse(dl, DL_OPT_HANDLE | DL_OPT_HANDLEP, DL_OPT_SB);
+ if (err)
+ return err;
+
+ occ_show = occ_show_alloc(dl);
+ if (!occ_show)
+ return -ENOMEM;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_PORT_POOL_GET, flags);
+
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh,
+ cmd_sb_occ_port_pool_process_cb, occ_show);
+ if (err)
+ goto out;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_TC_POOL_BIND_GET, flags);
+
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh,
+ cmd_sb_occ_tc_pool_process_cb, occ_show);
+ if (err)
+ goto out;
+
+ pr_out_section_start(dl, "occupancy");
+ pr_out_occ_show(occ_show);
+ pr_out_section_end(dl);
+
+out:
+ occ_show_free(occ_show);
+ return err;
+}
+
+static int cmd_sb_occ_snapshot(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_OCC_SNAPSHOT,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, DL_OPT_SB);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_sb_occ_clearmax(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_SB_OCC_MAX_CLEAR,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, DL_OPT_SB);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_sb_occ(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list")) {
+ dl_arg_inc(dl);
+ return cmd_sb_occ_show(dl);
+ } else if (dl_argv_match(dl, "snapshot")) {
+ dl_arg_inc(dl);
+ return cmd_sb_occ_snapshot(dl);
+ } else if (dl_argv_match(dl, "clearmax")) {
+ dl_arg_inc(dl);
+ return cmd_sb_occ_clearmax(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int cmd_sb(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_sb_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_sb_show(dl);
+ } else if (dl_argv_match(dl, "pool")) {
+ dl_arg_inc(dl);
+ return cmd_sb_pool(dl);
+ } else if (dl_argv_match(dl, "port")) {
+ dl_arg_inc(dl);
+ return cmd_sb_port(dl);
+ } else if (dl_argv_match(dl, "tc")) {
+ dl_arg_inc(dl);
+ return cmd_sb_tc(dl);
+ } else if (dl_argv_match(dl, "occupancy")) {
+ dl_arg_inc(dl);
+ return cmd_sb_occ(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static const char *cmd_name(uint8_t cmd)
+{
+ switch (cmd) {
+ case DEVLINK_CMD_UNSPEC: return "unspec";
+ case DEVLINK_CMD_GET: return "get";
+ case DEVLINK_CMD_SET: return "set";
+ case DEVLINK_CMD_NEW: return "new";
+ case DEVLINK_CMD_DEL: return "del";
+ case DEVLINK_CMD_PORT_GET: return "get";
+ case DEVLINK_CMD_PORT_SET: return "set";
+ case DEVLINK_CMD_PORT_NEW: return "new";
+ case DEVLINK_CMD_PORT_DEL: return "del";
+ case DEVLINK_CMD_PARAM_GET: return "get";
+ case DEVLINK_CMD_PARAM_SET: return "set";
+ case DEVLINK_CMD_PARAM_NEW: return "new";
+ case DEVLINK_CMD_PARAM_DEL: return "del";
+ case DEVLINK_CMD_REGION_GET: return "get";
+ case DEVLINK_CMD_REGION_SET: return "set";
+ case DEVLINK_CMD_REGION_NEW: return "new";
+ case DEVLINK_CMD_REGION_DEL: return "del";
+ case DEVLINK_CMD_FLASH_UPDATE: return "begin";
+ case DEVLINK_CMD_FLASH_UPDATE_END: return "end";
+ case DEVLINK_CMD_FLASH_UPDATE_STATUS: return "status";
+ case DEVLINK_CMD_TRAP_GET: return "get";
+ case DEVLINK_CMD_TRAP_SET: return "set";
+ case DEVLINK_CMD_TRAP_NEW: return "new";
+ case DEVLINK_CMD_TRAP_DEL: return "del";
+ case DEVLINK_CMD_TRAP_GROUP_GET: return "get";
+ case DEVLINK_CMD_TRAP_GROUP_SET: return "set";
+ case DEVLINK_CMD_TRAP_GROUP_NEW: return "new";
+ case DEVLINK_CMD_TRAP_GROUP_DEL: return "del";
+ default: return "<unknown cmd>";
+ }
+}
+
+static const char *cmd_obj(uint8_t cmd)
+{
+ switch (cmd) {
+ case DEVLINK_CMD_UNSPEC: return "unspec";
+ case DEVLINK_CMD_GET:
+ case DEVLINK_CMD_SET:
+ case DEVLINK_CMD_NEW:
+ case DEVLINK_CMD_DEL:
+ return "dev";
+ case DEVLINK_CMD_PORT_GET:
+ case DEVLINK_CMD_PORT_SET:
+ case DEVLINK_CMD_PORT_NEW:
+ case DEVLINK_CMD_PORT_DEL:
+ return "port";
+ case DEVLINK_CMD_PARAM_GET:
+ case DEVLINK_CMD_PARAM_SET:
+ case DEVLINK_CMD_PARAM_NEW:
+ case DEVLINK_CMD_PARAM_DEL:
+ return "param";
+ case DEVLINK_CMD_REGION_GET:
+ case DEVLINK_CMD_REGION_SET:
+ case DEVLINK_CMD_REGION_NEW:
+ case DEVLINK_CMD_REGION_DEL:
+ return "region";
+ case DEVLINK_CMD_FLASH_UPDATE:
+ case DEVLINK_CMD_FLASH_UPDATE_END:
+ case DEVLINK_CMD_FLASH_UPDATE_STATUS:
+ return "flash";
+ case DEVLINK_CMD_TRAP_GET:
+ case DEVLINK_CMD_TRAP_SET:
+ case DEVLINK_CMD_TRAP_NEW:
+ case DEVLINK_CMD_TRAP_DEL:
+ return "trap";
+ case DEVLINK_CMD_TRAP_GROUP_GET:
+ case DEVLINK_CMD_TRAP_GROUP_SET:
+ case DEVLINK_CMD_TRAP_GROUP_NEW:
+ case DEVLINK_CMD_TRAP_GROUP_DEL:
+ return "trap-group";
+ default: return "<unknown obj>";
+ }
+}
+
+static void pr_out_mon_header(uint8_t cmd)
+{
+ pr_out("[%s,%s] ", cmd_obj(cmd), cmd_name(cmd));
+}
+
+static bool cmd_filter_check(struct dl *dl, uint8_t cmd)
+{
+ const char *obj = cmd_obj(cmd);
+ unsigned int index = 0;
+ const char *cur_obj;
+
+ if (dl_no_arg(dl))
+ return true;
+ while ((cur_obj = dl_argv_index(dl, index++))) {
+ if (strcmp(cur_obj, obj) == 0 || strcmp(cur_obj, "all") == 0)
+ return true;
+ }
+ return false;
+}
+
+static void pr_out_flash_update(struct dl *dl, struct nlattr **tb)
+{
+ __pr_out_handle_start(dl, tb, true, false);
+
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG])
+ pr_out_str(dl, "msg",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG]));
+
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_COMPONENT])
+ pr_out_str(dl, "component",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_FLASH_UPDATE_COMPONENT]));
+
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE])
+ pr_out_u64(dl, "done",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE]));
+
+ if (tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL])
+ pr_out_u64(dl, "total",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL]));
+
+ pr_out_handle_end(dl);
+}
+
+static void pr_out_region(struct dl *dl, struct nlattr **tb);
+static void pr_out_trap(struct dl *dl, struct nlattr **tb, bool array);
+static void pr_out_trap_group(struct dl *dl, struct nlattr **tb, bool array);
+
+static int cmd_mon_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dl *dl = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ uint8_t cmd = genl->cmd;
+
+ if (!cmd_filter_check(dl, cmd))
+ return MNL_CB_OK;
+
+ switch (cmd) {
+ case DEVLINK_CMD_GET: /* fall through */
+ case DEVLINK_CMD_SET: /* fall through */
+ case DEVLINK_CMD_NEW: /* fall through */
+ case DEVLINK_CMD_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_handle(dl, tb);
+ break;
+ case DEVLINK_CMD_PORT_GET: /* fall through */
+ case DEVLINK_CMD_PORT_SET: /* fall through */
+ case DEVLINK_CMD_PORT_NEW: /* fall through */
+ case DEVLINK_CMD_PORT_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PORT_INDEX])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_port(dl, tb);
+ break;
+ case DEVLINK_CMD_PARAM_GET: /* fall through */
+ case DEVLINK_CMD_PARAM_SET: /* fall through */
+ case DEVLINK_CMD_PARAM_NEW: /* fall through */
+ case DEVLINK_CMD_PARAM_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_PARAM])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_param(dl, tb, false);
+ break;
+ case DEVLINK_CMD_REGION_GET: /* fall through */
+ case DEVLINK_CMD_REGION_SET: /* fall through */
+ case DEVLINK_CMD_REGION_NEW: /* fall through */
+ case DEVLINK_CMD_REGION_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_REGION_NAME])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_region(dl, tb);
+ break;
+ case DEVLINK_CMD_FLASH_UPDATE: /* fall through */
+ case DEVLINK_CMD_FLASH_UPDATE_END: /* fall through */
+ case DEVLINK_CMD_FLASH_UPDATE_STATUS:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_flash_update(dl, tb);
+ break;
+ case DEVLINK_CMD_TRAP_GET: /* fall through */
+ case DEVLINK_CMD_TRAP_SET: /* fall through */
+ case DEVLINK_CMD_TRAP_NEW: /* fall through */
+ case DEVLINK_CMD_TRAP_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_TYPE] ||
+ !tb[DEVLINK_ATTR_TRAP_ACTION] ||
+ !tb[DEVLINK_ATTR_TRAP_GROUP_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_METADATA] ||
+ !tb[DEVLINK_ATTR_STATS])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_trap(dl, tb, false);
+ break;
+ case DEVLINK_CMD_TRAP_GROUP_GET: /* fall through */
+ case DEVLINK_CMD_TRAP_GROUP_SET: /* fall through */
+ case DEVLINK_CMD_TRAP_GROUP_NEW: /* fall through */
+ case DEVLINK_CMD_TRAP_GROUP_DEL:
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_GROUP_NAME] ||
+ !tb[DEVLINK_ATTR_STATS])
+ return MNL_CB_ERROR;
+ pr_out_mon_header(genl->cmd);
+ pr_out_trap_group(dl, tb, false);
+ break;
+ }
+ return MNL_CB_OK;
+}
+
+static int cmd_mon_show(struct dl *dl)
+{
+ int err;
+ unsigned int index = 0;
+ const char *cur_obj;
+
+ while ((cur_obj = dl_argv_index(dl, index++))) {
+ if (strcmp(cur_obj, "all") != 0 &&
+ strcmp(cur_obj, "dev") != 0 &&
+ strcmp(cur_obj, "port") != 0 &&
+ strcmp(cur_obj, "trap") != 0 &&
+ strcmp(cur_obj, "trap-group") != 0) {
+ pr_err("Unknown object \"%s\"\n", cur_obj);
+ return -EINVAL;
+ }
+ }
+ err = _mnlg_socket_group_add(dl->nlg, DEVLINK_GENL_MCGRP_CONFIG_NAME);
+ if (err)
+ return err;
+ err = _mnlg_socket_recv_run(dl->nlg, cmd_mon_show_cb, dl);
+ if (err)
+ return err;
+ return 0;
+}
+
+static void cmd_mon_help(void)
+{
+ pr_err("Usage: devlink monitor [ all | OBJECT-LIST ]\n"
+ "where OBJECT-LIST := { dev | port | trap | trap-group }\n");
+}
+
+static int cmd_mon(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_mon_help();
+ return 0;
+ }
+ return cmd_mon_show(dl);
+}
+
+struct dpipe_field {
+ char *name;
+ unsigned int id;
+ unsigned int bitwidth;
+ enum devlink_dpipe_field_mapping_type mapping_type;
+};
+
+struct dpipe_header {
+ struct list_head list;
+ char *name;
+ unsigned int id;
+ struct dpipe_field *fields;
+ unsigned int fields_count;
+};
+
+struct dpipe_table {
+ struct list_head list;
+ char *name;
+ unsigned int resource_id;
+ bool resource_valid;
+};
+
+struct dpipe_tables {
+ struct list_head table_list;
+};
+
+struct resource {
+ char *name;
+ uint64_t size;
+ uint64_t size_new;
+ uint64_t size_min;
+ uint64_t size_max;
+ uint64_t size_gran;
+ enum devlink_resource_unit unit;
+ bool size_valid;
+ uint64_t size_occ;
+ bool occ_valid;
+ uint64_t id;
+ struct list_head list;
+ struct list_head resource_list;
+ struct resource *parent;
+};
+
+struct resources {
+ struct list_head resource_list;
+};
+
+struct resource_ctx {
+ struct dl *dl;
+ int err;
+ struct resources *resources;
+ struct dpipe_tables *tables;
+ bool print_resources;
+ bool pending_change;
+};
+
+static struct resource *resource_alloc(void)
+{
+ struct resource *resource;
+
+ resource = calloc(1, sizeof(struct resource));
+ if (!resource)
+ return NULL;
+ INIT_LIST_HEAD(&resource->resource_list);
+ return resource;
+}
+
+static void resource_free(struct resource *resource)
+{
+ struct resource *child_resource, *tmp;
+
+ list_for_each_entry_safe(child_resource, tmp, &resource->resource_list,
+ list) {
+ free(child_resource->name);
+ resource_free(child_resource);
+ }
+ free(resource);
+}
+
+static struct resources *resources_alloc(void)
+{
+ struct resources *resources;
+
+ resources = calloc(1, sizeof(struct resources));
+ if (!resources)
+ return NULL;
+ INIT_LIST_HEAD(&resources->resource_list);
+ return resources;
+}
+
+static void resources_free(struct resources *resources)
+{
+ struct resource *resource, *tmp;
+
+ list_for_each_entry_safe(resource, tmp, &resources->resource_list, list)
+ resource_free(resource);
+}
+
+static int resource_ctx_init(struct resource_ctx *ctx, struct dl *dl)
+{
+ ctx->resources = resources_alloc();
+ if (!ctx->resources)
+ return -ENOMEM;
+ ctx->dl = dl;
+ return 0;
+}
+
+static void resource_ctx_fini(struct resource_ctx *ctx)
+{
+ resources_free(ctx->resources);
+}
+
+struct dpipe_ctx {
+ struct dl *dl;
+ int err;
+ struct list_head global_headers;
+ struct list_head local_headers;
+ struct dpipe_tables *tables;
+ struct resources *resources;
+ bool print_headers;
+ bool print_tables;
+};
+
+static struct dpipe_header *dpipe_header_alloc(unsigned int fields_count)
+{
+ struct dpipe_header *header;
+
+ header = calloc(1, sizeof(struct dpipe_header));
+ if (!header)
+ return NULL;
+ header->fields = calloc(fields_count, sizeof(struct dpipe_field));
+ if (!header->fields)
+ goto err_fields_alloc;
+ header->fields_count = fields_count;
+ return header;
+
+err_fields_alloc:
+ free(header);
+ return NULL;
+}
+
+static void dpipe_header_free(struct dpipe_header *header)
+{
+ free(header->fields);
+ free(header);
+}
+
+static void dpipe_header_clear(struct dpipe_header *header)
+{
+ struct dpipe_field *field;
+ int i;
+
+ for (i = 0; i < header->fields_count; i++) {
+ field = &header->fields[i];
+ free(field->name);
+ }
+ free(header->name);
+}
+
+static void dpipe_header_add(struct dpipe_ctx *ctx,
+ struct dpipe_header *header, bool global)
+{
+ if (global)
+ list_add(&header->list, &ctx->global_headers);
+ else
+ list_add(&header->list, &ctx->local_headers);
+}
+
+static void dpipe_header_del(struct dpipe_header *header)
+{
+ list_del(&header->list);
+}
+
+static struct dpipe_table *dpipe_table_alloc(void)
+{
+ return calloc(1, sizeof(struct dpipe_table));
+}
+
+static void dpipe_table_free(struct dpipe_table *table)
+{
+ free(table);
+}
+
+static struct dpipe_tables *dpipe_tables_alloc(void)
+{
+ struct dpipe_tables *tables;
+
+ tables = calloc(1, sizeof(struct dpipe_tables));
+ if (!tables)
+ return NULL;
+ INIT_LIST_HEAD(&tables->table_list);
+ return tables;
+}
+
+static void dpipe_tables_free(struct dpipe_tables *tables)
+{
+ struct dpipe_table *table, *tmp;
+
+ list_for_each_entry_safe(table, tmp, &tables->table_list, list)
+ dpipe_table_free(table);
+ free(tables);
+}
+
+static int dpipe_ctx_init(struct dpipe_ctx *ctx, struct dl *dl)
+{
+ ctx->tables = dpipe_tables_alloc();
+ if (!ctx->tables)
+ return -ENOMEM;
+
+ ctx->dl = dl;
+ INIT_LIST_HEAD(&ctx->global_headers);
+ INIT_LIST_HEAD(&ctx->local_headers);
+ return 0;
+}
+
+static void dpipe_ctx_fini(struct dpipe_ctx *ctx)
+{
+ struct dpipe_header *header, *tmp;
+
+ list_for_each_entry_safe(header, tmp, &ctx->global_headers,
+ list) {
+ dpipe_header_del(header);
+ dpipe_header_clear(header);
+ dpipe_header_free(header);
+ }
+ list_for_each_entry_safe(header, tmp, &ctx->local_headers,
+ list) {
+ dpipe_header_del(header);
+ dpipe_header_clear(header);
+ dpipe_header_free(header);
+ }
+ dpipe_tables_free(ctx->tables);
+}
+
+static const char *dpipe_header_id2s(struct dpipe_ctx *ctx,
+ uint32_t header_id, bool global)
+{
+ struct list_head *header_list;
+ struct dpipe_header *header;
+
+ if (global)
+ header_list = &ctx->global_headers;
+ else
+ header_list = &ctx->local_headers;
+ list_for_each_entry(header, header_list, list) {
+ if (header->id != header_id)
+ continue;
+ return header->name;
+ }
+ return NULL;
+}
+
+static const char *dpipe_field_id2s(struct dpipe_ctx *ctx,
+ uint32_t header_id,
+ uint32_t field_id, bool global)
+{
+ struct list_head *header_list;
+ struct dpipe_header *header;
+
+ if (global)
+ header_list = &ctx->global_headers;
+ else
+ header_list = &ctx->local_headers;
+ list_for_each_entry(header, header_list, list) {
+ if (header->id != header_id)
+ continue;
+ return header->fields[field_id].name;
+ }
+ return NULL;
+}
+
+static const char *
+dpipe_field_mapping_e2s(enum devlink_dpipe_field_mapping_type mapping_type)
+{
+ switch (mapping_type) {
+ case DEVLINK_DPIPE_FIELD_MAPPING_TYPE_NONE:
+ return NULL;
+ case DEVLINK_DPIPE_FIELD_MAPPING_TYPE_IFINDEX:
+ return "ifindex";
+ default:
+ return "<unknown>";
+ }
+}
+
+static const char *
+dpipe_mapping_get(struct dpipe_ctx *ctx, uint32_t header_id,
+ uint32_t field_id, bool global)
+{
+ enum devlink_dpipe_field_mapping_type mapping_type;
+ struct list_head *header_list;
+ struct dpipe_header *header;
+
+ if (global)
+ header_list = &ctx->global_headers;
+ else
+ header_list = &ctx->local_headers;
+ list_for_each_entry(header, header_list, list) {
+ if (header->id != header_id)
+ continue;
+ mapping_type = header->fields[field_id].mapping_type;
+ return dpipe_field_mapping_e2s(mapping_type);
+ }
+ return NULL;
+}
+
+static void pr_out_dpipe_fields(struct dpipe_ctx *ctx,
+ struct dpipe_field *fields,
+ unsigned int field_count)
+{
+ struct dpipe_field *field;
+ int i;
+
+ for (i = 0; i < field_count; i++) {
+ field = &fields[i];
+ pr_out_entry_start(ctx->dl);
+ pr_out_str(ctx->dl, "name", field->name);
+ if (ctx->dl->verbose)
+ pr_out_uint(ctx->dl, "id", field->id);
+ pr_out_uint(ctx->dl, "bitwidth", field->bitwidth);
+ if (field->mapping_type)
+ pr_out_str(ctx->dl, "mapping_type",
+ dpipe_field_mapping_e2s(field->mapping_type));
+ pr_out_entry_end(ctx->dl);
+ }
+}
+
+static void
+pr_out_dpipe_header(struct dpipe_ctx *ctx, struct nlattr **tb,
+ struct dpipe_header *header, bool global)
+{
+ pr_out_handle_start_arr(ctx->dl, tb);
+ pr_out_str(ctx->dl, "name", header->name);
+ if (ctx->dl->verbose) {
+ pr_out_uint(ctx->dl, "id", header->id);
+ pr_out_str(ctx->dl, "global",
+ global ? "true" : "false");
+ }
+ pr_out_array_start(ctx->dl, "field");
+ pr_out_dpipe_fields(ctx, header->fields,
+ header->fields_count);
+ pr_out_array_end(ctx->dl);
+ pr_out_handle_end(ctx->dl);
+}
+
+static void pr_out_dpipe_headers(struct dpipe_ctx *ctx,
+ struct nlattr **tb)
+{
+ struct dpipe_header *header;
+
+ list_for_each_entry(header, &ctx->local_headers, list)
+ pr_out_dpipe_header(ctx, tb, header, false);
+
+ list_for_each_entry(header, &ctx->global_headers, list)
+ pr_out_dpipe_header(ctx, tb, header, true);
+}
+
+static int dpipe_header_field_get(struct nlattr *nl, struct dpipe_field *field)
+{
+ struct nlattr *nla_field[DEVLINK_ATTR_MAX + 1] = {};
+ const char *name;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_field);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+ if (!nla_field[DEVLINK_ATTR_DPIPE_FIELD_ID] ||
+ !nla_field[DEVLINK_ATTR_DPIPE_FIELD_NAME] ||
+ !nla_field[DEVLINK_ATTR_DPIPE_FIELD_BITWIDTH] ||
+ !nla_field[DEVLINK_ATTR_DPIPE_FIELD_MAPPING_TYPE])
+ return -EINVAL;
+
+ name = mnl_attr_get_str(nla_field[DEVLINK_ATTR_DPIPE_FIELD_NAME]);
+ field->id = mnl_attr_get_u32(nla_field[DEVLINK_ATTR_DPIPE_FIELD_ID]);
+ field->bitwidth = mnl_attr_get_u32(nla_field[DEVLINK_ATTR_DPIPE_FIELD_BITWIDTH]);
+ field->name = strdup(name);
+ if (!field->name)
+ return -ENOMEM;
+ field->mapping_type = mnl_attr_get_u32(nla_field[DEVLINK_ATTR_DPIPE_FIELD_MAPPING_TYPE]);
+ return 0;
+}
+
+static int dpipe_header_fields_get(struct nlattr *nla_fields,
+ struct dpipe_field *fields)
+{
+ struct nlattr *nla_field;
+ int count = 0;
+ int err;
+
+ mnl_attr_for_each_nested(nla_field, nla_fields) {
+ err = dpipe_header_field_get(nla_field, &fields[count]);
+ if (err)
+ return err;
+ count++;
+ }
+ return 0;
+}
+
+static unsigned int dpipe_header_field_count_get(struct nlattr *nla_fields)
+{
+ struct nlattr *nla_field;
+ unsigned int count = 0;
+
+ mnl_attr_for_each_nested(nla_field, nla_fields)
+ count++;
+ return count;
+}
+
+static int dpipe_header_get(struct dpipe_ctx *ctx, struct nlattr *nl)
+{
+ struct nlattr *nla_header[DEVLINK_ATTR_MAX + 1] = {};
+ struct dpipe_header *header;
+ unsigned int fields_count;
+ const char *header_name;
+ bool global;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_header);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_header[DEVLINK_ATTR_DPIPE_HEADER_NAME] ||
+ !nla_header[DEVLINK_ATTR_DPIPE_HEADER_ID] ||
+ !nla_header[DEVLINK_ATTR_DPIPE_HEADER_FIELDS])
+ return -EINVAL;
+
+ fields_count = dpipe_header_field_count_get(nla_header[DEVLINK_ATTR_DPIPE_HEADER_FIELDS]);
+ header = dpipe_header_alloc(fields_count);
+ if (!header)
+ return -ENOMEM;
+
+ header_name = mnl_attr_get_str(nla_header[DEVLINK_ATTR_DPIPE_HEADER_NAME]);
+ header->name = strdup(header_name);
+ header->id = mnl_attr_get_u32(nla_header[DEVLINK_ATTR_DPIPE_HEADER_ID]);
+ header->fields_count = fields_count;
+ global = !!mnl_attr_get_u8(nla_header[DEVLINK_ATTR_DPIPE_HEADER_GLOBAL]);
+
+ err = dpipe_header_fields_get(nla_header[DEVLINK_ATTR_DPIPE_HEADER_FIELDS],
+ header->fields);
+ if (err)
+ goto err_field_get;
+ dpipe_header_add(ctx, header, global);
+ return 0;
+
+err_field_get:
+ dpipe_header_free(header);
+ return err;
+}
+
+static int dpipe_headers_get(struct dpipe_ctx *ctx, struct nlattr **tb)
+{
+ struct nlattr *nla_headers = tb[DEVLINK_ATTR_DPIPE_HEADERS];
+ struct nlattr *nla_header;
+ int err;
+
+ mnl_attr_for_each_nested(nla_header, nla_headers) {
+ err = dpipe_header_get(ctx, nla_header);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
+static int cmd_dpipe_header_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dpipe_ctx *ctx = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ int err;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_DPIPE_HEADERS])
+ return MNL_CB_ERROR;
+ err = dpipe_headers_get(ctx, tb);
+ if (err) {
+ ctx->err = err;
+ return MNL_CB_ERROR;
+ }
+
+ if (ctx->print_headers)
+ pr_out_dpipe_headers(ctx, tb);
+ return MNL_CB_OK;
+}
+
+static int cmd_dpipe_headers_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct dpipe_ctx ctx = {};
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_HEADERS_GET, flags);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+
+ err = dpipe_ctx_init(&ctx, dl);
+ if (err)
+ return err;
+
+ ctx.print_headers = true;
+
+ pr_out_section_start(dl, "header");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_header_cb, &ctx);
+ if (err)
+ pr_err("error get headers %s\n", strerror(ctx.err));
+ pr_out_section_end(dl);
+
+ dpipe_ctx_fini(&ctx);
+ return err;
+}
+
+static void cmd_dpipe_header_help(void)
+{
+ pr_err("Usage: devlink dpipe headers show DEV\n");
+}
+
+static int cmd_dpipe_header(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dpipe_header_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_headers_show(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static const char
+*dpipe_action_type_e2s(enum devlink_dpipe_action_type action_type)
+{
+ switch (action_type) {
+ case DEVLINK_DPIPE_ACTION_TYPE_FIELD_MODIFY:
+ return "field_modify";
+ default:
+ return "<unknown>";
+ }
+}
+
+struct dpipe_op_info {
+ uint32_t header_id;
+ uint32_t field_id;
+ bool header_global;
+};
+
+struct dpipe_action {
+ struct dpipe_op_info info;
+ uint32_t type;
+};
+
+static void pr_out_dpipe_action(struct dpipe_action *action,
+ struct dpipe_ctx *ctx)
+{
+ struct dpipe_op_info *op_info = &action->info;
+ const char *mapping;
+
+ pr_out_str(ctx->dl, "type",
+ dpipe_action_type_e2s(action->type));
+ pr_out_str(ctx->dl, "header",
+ dpipe_header_id2s(ctx, op_info->header_id,
+ op_info->header_global));
+ pr_out_str(ctx->dl, "field",
+ dpipe_field_id2s(ctx, op_info->header_id,
+ op_info->field_id,
+ op_info->header_global));
+ mapping = dpipe_mapping_get(ctx, op_info->header_id,
+ op_info->field_id,
+ op_info->header_global);
+ if (mapping)
+ pr_out_str(ctx->dl, "mapping", mapping);
+}
+
+static int dpipe_action_parse(struct dpipe_action *action, struct nlattr *nl)
+{
+ struct nlattr *nla_action[DEVLINK_ATTR_MAX + 1] = {};
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_action);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_action[DEVLINK_ATTR_DPIPE_ACTION_TYPE] ||
+ !nla_action[DEVLINK_ATTR_DPIPE_HEADER_INDEX] ||
+ !nla_action[DEVLINK_ATTR_DPIPE_HEADER_ID] ||
+ !nla_action[DEVLINK_ATTR_DPIPE_FIELD_ID]) {
+ return -EINVAL;
+ }
+
+ action->type = mnl_attr_get_u32(nla_action[DEVLINK_ATTR_DPIPE_ACTION_TYPE]);
+ action->info.header_id = mnl_attr_get_u32(nla_action[DEVLINK_ATTR_DPIPE_HEADER_ID]);
+ action->info.field_id = mnl_attr_get_u32(nla_action[DEVLINK_ATTR_DPIPE_FIELD_ID]);
+ action->info.header_global = !!mnl_attr_get_u8(nla_action[DEVLINK_ATTR_DPIPE_HEADER_GLOBAL]);
+
+ return 0;
+}
+
+static int dpipe_table_actions_show(struct dpipe_ctx *ctx,
+ struct nlattr *nla_actions)
+{
+ struct nlattr *nla_action;
+ struct dpipe_action action;
+
+ mnl_attr_for_each_nested(nla_action, nla_actions) {
+ pr_out_entry_start(ctx->dl);
+ if (dpipe_action_parse(&action, nla_action))
+ goto err_action_parse;
+ pr_out_dpipe_action(&action, ctx);
+ pr_out_entry_end(ctx->dl);
+ }
+ return 0;
+
+err_action_parse:
+ pr_out_entry_end(ctx->dl);
+ return -EINVAL;
+}
+
+static const char *
+dpipe_match_type_e2s(enum devlink_dpipe_match_type match_type)
+{
+ switch (match_type) {
+ case DEVLINK_DPIPE_MATCH_TYPE_FIELD_EXACT:
+ return "field_exact";
+ default:
+ return "<unknown>";
+ }
+}
+
+struct dpipe_match {
+ struct dpipe_op_info info;
+ uint32_t type;
+};
+
+static void pr_out_dpipe_match(struct dpipe_match *match,
+ struct dpipe_ctx *ctx)
+{
+ struct dpipe_op_info *op_info = &match->info;
+ const char *mapping;
+
+ pr_out_str(ctx->dl, "type",
+ dpipe_match_type_e2s(match->type));
+ pr_out_str(ctx->dl, "header",
+ dpipe_header_id2s(ctx, op_info->header_id,
+ op_info->header_global));
+ pr_out_str(ctx->dl, "field",
+ dpipe_field_id2s(ctx, op_info->header_id,
+ op_info->field_id,
+ op_info->header_global));
+ mapping = dpipe_mapping_get(ctx, op_info->header_id,
+ op_info->field_id,
+ op_info->header_global);
+ if (mapping)
+ pr_out_str(ctx->dl, "mapping", mapping);
+}
+
+static int dpipe_match_parse(struct dpipe_match *match,
+ struct nlattr *nl)
+
+{
+ struct nlattr *nla_match[DEVLINK_ATTR_MAX + 1] = {};
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_match);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_match[DEVLINK_ATTR_DPIPE_MATCH_TYPE] ||
+ !nla_match[DEVLINK_ATTR_DPIPE_HEADER_INDEX] ||
+ !nla_match[DEVLINK_ATTR_DPIPE_HEADER_ID] ||
+ !nla_match[DEVLINK_ATTR_DPIPE_FIELD_ID]) {
+ return -EINVAL;
+ }
+
+ match->type = mnl_attr_get_u32(nla_match[DEVLINK_ATTR_DPIPE_MATCH_TYPE]);
+ match->info.header_id = mnl_attr_get_u32(nla_match[DEVLINK_ATTR_DPIPE_HEADER_ID]);
+ match->info.field_id = mnl_attr_get_u32(nla_match[DEVLINK_ATTR_DPIPE_FIELD_ID]);
+ match->info.header_global = !!mnl_attr_get_u8(nla_match[DEVLINK_ATTR_DPIPE_HEADER_GLOBAL]);
+
+ return 0;
+}
+
+static int dpipe_table_matches_show(struct dpipe_ctx *ctx,
+ struct nlattr *nla_matches)
+{
+ struct nlattr *nla_match;
+ struct dpipe_match match;
+
+ mnl_attr_for_each_nested(nla_match, nla_matches) {
+ pr_out_entry_start(ctx->dl);
+ if (dpipe_match_parse(&match, nla_match))
+ goto err_match_parse;
+ pr_out_dpipe_match(&match, ctx);
+ pr_out_entry_end(ctx->dl);
+ }
+ return 0;
+
+err_match_parse:
+ pr_out_entry_end(ctx->dl);
+ return -EINVAL;
+}
+
+static struct resource *
+resource_find(struct resources *resources, struct resource *resource,
+ uint64_t resource_id)
+{
+ struct list_head *list_head;
+
+ if (!resource)
+ list_head = &resources->resource_list;
+ else
+ list_head = &resource->resource_list;
+
+ list_for_each_entry(resource, list_head, list) {
+ struct resource *child_resource;
+
+ if (resource->id == resource_id)
+ return resource;
+
+ child_resource = resource_find(resources, resource,
+ resource_id);
+ if (child_resource)
+ return child_resource;
+ }
+ return NULL;
+}
+
+static void
+resource_path_print(struct dl *dl, struct resources *resources,
+ uint64_t resource_id)
+{
+ struct resource *resource, *parent_resource;
+ const char del[] = "/";
+ int path_len = 0;
+ char *path;
+
+ resource = resource_find(resources, NULL, resource_id);
+ if (!resource)
+ return;
+
+ for (parent_resource = resource; parent_resource;
+ parent_resource = parent_resource->parent)
+ path_len += strlen(parent_resource->name) + 1;
+
+ path_len++;
+ path = calloc(1, path_len);
+ if (!path)
+ return;
+
+ path += path_len - 1;
+ for (parent_resource = resource; parent_resource;
+ parent_resource = parent_resource->parent) {
+ path -= strlen(parent_resource->name);
+ memcpy(path, parent_resource->name,
+ strlen(parent_resource->name));
+ path -= strlen(del);
+ memcpy(path, del, strlen(del));
+ }
+ pr_out_str(dl, "resource_path", path);
+ free(path);
+}
+
+static int dpipe_table_show(struct dpipe_ctx *ctx, struct nlattr *nl)
+{
+ struct nlattr *nla_table[DEVLINK_ATTR_MAX + 1] = {};
+ struct dpipe_table *table;
+ uint32_t resource_units;
+ bool counters_enabled;
+ bool resource_valid;
+ uint32_t size;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_table);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_table[DEVLINK_ATTR_DPIPE_TABLE_NAME] ||
+ !nla_table[DEVLINK_ATTR_DPIPE_TABLE_SIZE] ||
+ !nla_table[DEVLINK_ATTR_DPIPE_TABLE_ACTIONS] ||
+ !nla_table[DEVLINK_ATTR_DPIPE_TABLE_MATCHES] ||
+ !nla_table[DEVLINK_ATTR_DPIPE_TABLE_COUNTERS_ENABLED]) {
+ return -EINVAL;
+ }
+
+ table = dpipe_table_alloc();
+ if (!table)
+ return -ENOMEM;
+
+ table->name = strdup(mnl_attr_get_str(nla_table[DEVLINK_ATTR_DPIPE_TABLE_NAME]));
+ size = mnl_attr_get_u32(nla_table[DEVLINK_ATTR_DPIPE_TABLE_SIZE]);
+ counters_enabled = !!mnl_attr_get_u8(nla_table[DEVLINK_ATTR_DPIPE_TABLE_COUNTERS_ENABLED]);
+
+ resource_valid = nla_table[DEVLINK_ATTR_DPIPE_TABLE_RESOURCE_ID] &&
+ ctx->resources;
+ if (resource_valid) {
+ table->resource_id = mnl_attr_get_u64(nla_table[DEVLINK_ATTR_DPIPE_TABLE_RESOURCE_ID]);
+ table->resource_valid = true;
+ }
+
+ list_add_tail(&table->list, &ctx->tables->table_list);
+ if (!ctx->print_tables)
+ return 0;
+
+ pr_out_str(ctx->dl, "name", table->name);
+ pr_out_uint(ctx->dl, "size", size);
+ pr_out_str(ctx->dl, "counters_enabled",
+ counters_enabled ? "true" : "false");
+
+ if (resource_valid) {
+ resource_units = mnl_attr_get_u32(nla_table[DEVLINK_ATTR_DPIPE_TABLE_RESOURCE_UNITS]);
+ resource_path_print(ctx->dl, ctx->resources,
+ table->resource_id);
+ pr_out_uint(ctx->dl, "resource_units", resource_units);
+ }
+
+ pr_out_array_start(ctx->dl, "match");
+ if (dpipe_table_matches_show(ctx, nla_table[DEVLINK_ATTR_DPIPE_TABLE_MATCHES]))
+ goto err_matches_show;
+ pr_out_array_end(ctx->dl);
+
+ pr_out_array_start(ctx->dl, "action");
+ if (dpipe_table_actions_show(ctx, nla_table[DEVLINK_ATTR_DPIPE_TABLE_ACTIONS]))
+ goto err_actions_show;
+ pr_out_array_end(ctx->dl);
+
+ return 0;
+
+err_actions_show:
+err_matches_show:
+ pr_out_array_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int dpipe_tables_show(struct dpipe_ctx *ctx, struct nlattr **tb)
+{
+ struct nlattr *nla_tables = tb[DEVLINK_ATTR_DPIPE_TABLES];
+ struct nlattr *nla_table;
+
+ mnl_attr_for_each_nested(nla_table, nla_tables) {
+ if (ctx->print_tables)
+ pr_out_handle_start_arr(ctx->dl, tb);
+ if (dpipe_table_show(ctx, nla_table))
+ goto err_table_show;
+ if (ctx->print_tables)
+ pr_out_handle_end(ctx->dl);
+ }
+ return 0;
+
+err_table_show:
+ if (ctx->print_tables)
+ pr_out_handle_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int cmd_dpipe_table_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dpipe_ctx *ctx = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_DPIPE_TABLES])
+ return MNL_CB_ERROR;
+
+ if (dpipe_tables_show(ctx, tb))
+ return MNL_CB_ERROR;
+ return MNL_CB_OK;
+}
+
+static int cmd_resource_dump_cb(const struct nlmsghdr *nlh, void *data);
+
+static int cmd_dpipe_table_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct dpipe_ctx dpipe_ctx = {};
+ struct resource_ctx resource_ctx = {};
+ uint16_t flags = NLM_F_REQUEST;
+ int err;
+
+ err = dl_argv_parse(dl, DL_OPT_HANDLE, DL_OPT_DPIPE_TABLE_NAME);
+ if (err)
+ return err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_HEADERS_GET, flags);
+
+ err = dpipe_ctx_init(&dpipe_ctx, dl);
+ if (err)
+ return err;
+
+ dpipe_ctx.print_tables = true;
+
+ dl_opts_put(nlh, dl);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_header_cb,
+ &dpipe_ctx);
+ if (err) {
+ pr_err("error get headers %s\n", strerror(dpipe_ctx.err));
+ goto err_headers_get;
+ }
+
+ err = resource_ctx_init(&resource_ctx, dl);
+ if (err)
+ goto err_resource_ctx_init;
+
+ resource_ctx.print_resources = false;
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_RESOURCE_DUMP, flags);
+ dl_opts_put(nlh, dl);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_resource_dump_cb,
+ &resource_ctx);
+ if (!err)
+ dpipe_ctx.resources = resource_ctx.resources;
+
+ flags = NLM_F_REQUEST | NLM_F_ACK;
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_TABLE_GET, flags);
+ dl_opts_put(nlh, dl);
+
+ pr_out_section_start(dl, "table");
+ _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_table_show_cb, &dpipe_ctx);
+ pr_out_section_end(dl);
+
+ resource_ctx_fini(&resource_ctx);
+ dpipe_ctx_fini(&dpipe_ctx);
+ return 0;
+
+err_resource_ctx_init:
+err_headers_get:
+ dpipe_ctx_fini(&dpipe_ctx);
+ return err;
+}
+
+static int cmd_dpipe_table_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_TABLE_COUNTERS_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_DPIPE_TABLE_NAME |
+ DL_OPT_DPIPE_TABLE_COUNTERS, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+enum dpipe_value_type {
+ DPIPE_VALUE_TYPE_VALUE,
+ DPIPE_VALUE_TYPE_MASK,
+};
+
+static const char *
+dpipe_value_type_e2s(enum dpipe_value_type type)
+{
+ switch (type) {
+ case DPIPE_VALUE_TYPE_VALUE:
+ return "value";
+ case DPIPE_VALUE_TYPE_MASK:
+ return "value_mask";
+ default:
+ return "<unknown>";
+ }
+}
+
+struct dpipe_field_printer {
+ unsigned int field_id;
+ void (*printer)(struct dpipe_ctx *, enum dpipe_value_type, void *);
+};
+
+struct dpipe_header_printer {
+ struct dpipe_field_printer *printers;
+ unsigned int printers_count;
+ unsigned int header_id;
+};
+
+static void dpipe_field_printer_ipv4_addr(struct dpipe_ctx *ctx,
+ enum dpipe_value_type type,
+ void *value)
+{
+ struct in_addr ip_addr;
+
+ ip_addr.s_addr = htonl(*(uint32_t *)value);
+ pr_out_str(ctx->dl, dpipe_value_type_e2s(type), inet_ntoa(ip_addr));
+}
+
+static void
+dpipe_field_printer_ethernet_addr(struct dpipe_ctx *ctx,
+ enum dpipe_value_type type,
+ void *value)
+{
+ pr_out_str(ctx->dl, dpipe_value_type_e2s(type),
+ ether_ntoa((struct ether_addr *)value));
+}
+
+static void dpipe_field_printer_ipv6_addr(struct dpipe_ctx *ctx,
+ enum dpipe_value_type type,
+ void *value)
+{
+ char str[INET6_ADDRSTRLEN];
+
+ inet_ntop(AF_INET6, value, str, INET6_ADDRSTRLEN);
+ pr_out_str(ctx->dl, dpipe_value_type_e2s(type), str);
+}
+
+static struct dpipe_field_printer dpipe_field_printers_ipv4[] = {
+ {
+ .printer = dpipe_field_printer_ipv4_addr,
+ .field_id = DEVLINK_DPIPE_FIELD_IPV4_DST_IP,
+ }
+};
+
+static struct dpipe_header_printer dpipe_header_printer_ipv4 = {
+ .printers = dpipe_field_printers_ipv4,
+ .printers_count = ARRAY_SIZE(dpipe_field_printers_ipv4),
+ .header_id = DEVLINK_DPIPE_HEADER_IPV4,
+};
+
+static struct dpipe_field_printer dpipe_field_printers_ethernet[] = {
+ {
+ .printer = dpipe_field_printer_ethernet_addr,
+ .field_id = DEVLINK_DPIPE_FIELD_ETHERNET_DST_MAC,
+ },
+};
+
+static struct dpipe_header_printer dpipe_header_printer_ethernet = {
+ .printers = dpipe_field_printers_ethernet,
+ .printers_count = ARRAY_SIZE(dpipe_field_printers_ethernet),
+ .header_id = DEVLINK_DPIPE_HEADER_ETHERNET,
+};
+
+static struct dpipe_field_printer dpipe_field_printers_ipv6[] = {
+ {
+ .printer = dpipe_field_printer_ipv6_addr,
+ .field_id = DEVLINK_DPIPE_FIELD_IPV6_DST_IP,
+ }
+};
+
+static struct dpipe_header_printer dpipe_header_printer_ipv6 = {
+ .printers = dpipe_field_printers_ipv6,
+ .printers_count = ARRAY_SIZE(dpipe_field_printers_ipv6),
+ .header_id = DEVLINK_DPIPE_HEADER_IPV6,
+};
+
+static struct dpipe_header_printer *dpipe_header_printers[] = {
+ &dpipe_header_printer_ipv4,
+ &dpipe_header_printer_ethernet,
+ &dpipe_header_printer_ipv6,
+};
+
+static int dpipe_print_prot_header(struct dpipe_ctx *ctx,
+ struct dpipe_op_info *info,
+ enum dpipe_value_type type,
+ void *value)
+{
+ unsigned int header_printers_count = ARRAY_SIZE(dpipe_header_printers);
+ struct dpipe_header_printer *header_printer;
+ struct dpipe_field_printer *field_printer;
+ unsigned int field_printers_count;
+ int j;
+ int i;
+
+ for (i = 0; i < header_printers_count; i++) {
+ header_printer = dpipe_header_printers[i];
+ if (header_printer->header_id != info->header_id)
+ continue;
+ field_printers_count = header_printer->printers_count;
+ for (j = 0; j < field_printers_count; j++) {
+ field_printer = &header_printer->printers[j];
+ if (field_printer->field_id != info->field_id)
+ continue;
+ field_printer->printer(ctx, type, value);
+ return 0;
+ }
+ }
+
+ return -EINVAL;
+}
+
+static void __pr_out_entry_value(struct dpipe_ctx *ctx,
+ void *value,
+ unsigned int value_len,
+ struct dpipe_op_info *info,
+ enum dpipe_value_type type)
+{
+ if (info->header_global &&
+ !dpipe_print_prot_header(ctx, info, type, value))
+ return;
+
+ if (value_len == sizeof(uint32_t)) {
+ uint32_t *value_32 = value;
+
+ pr_out_uint(ctx->dl, dpipe_value_type_e2s(type), *value_32);
+ }
+}
+
+static void pr_out_dpipe_entry_value(struct dpipe_ctx *ctx,
+ struct nlattr **nla_match_value,
+ struct dpipe_op_info *info)
+{
+ void *value, *value_mask;
+ uint32_t value_mapping;
+ uint16_t value_len;
+ bool mask, mapping;
+
+ mask = !!nla_match_value[DEVLINK_ATTR_DPIPE_VALUE_MASK];
+ mapping = !!nla_match_value[DEVLINK_ATTR_DPIPE_VALUE_MAPPING];
+
+ value_len = mnl_attr_get_payload_len(nla_match_value[DEVLINK_ATTR_DPIPE_VALUE]);
+ value = mnl_attr_get_payload(nla_match_value[DEVLINK_ATTR_DPIPE_VALUE]);
+
+ if (mapping) {
+ value_mapping = mnl_attr_get_u32(nla_match_value[DEVLINK_ATTR_DPIPE_VALUE_MAPPING]);
+ pr_out_uint(ctx->dl, "mapping_value", value_mapping);
+ }
+
+ if (mask) {
+ value_mask = mnl_attr_get_payload(nla_match_value[DEVLINK_ATTR_DPIPE_VALUE]);
+ __pr_out_entry_value(ctx, value_mask, value_len, info,
+ DPIPE_VALUE_TYPE_MASK);
+ }
+
+ __pr_out_entry_value(ctx, value, value_len, info, DPIPE_VALUE_TYPE_VALUE);
+}
+
+static int dpipe_entry_match_value_show(struct dpipe_ctx *ctx,
+ struct nlattr *nl)
+{
+ struct nlattr *nla_match_value[DEVLINK_ATTR_MAX + 1] = {};
+ struct dpipe_match match;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_match_value);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_match_value[DEVLINK_ATTR_DPIPE_MATCH] ||
+ !nla_match_value[DEVLINK_ATTR_DPIPE_VALUE]) {
+ return -EINVAL;
+ }
+
+ pr_out_entry_start(ctx->dl);
+ if (dpipe_match_parse(&match,
+ nla_match_value[DEVLINK_ATTR_DPIPE_MATCH]))
+ goto err_match_parse;
+ pr_out_dpipe_match(&match, ctx);
+ pr_out_dpipe_entry_value(ctx, nla_match_value, &match.info);
+ pr_out_entry_end(ctx->dl);
+
+ return 0;
+
+err_match_parse:
+ pr_out_entry_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int dpipe_entry_action_value_show(struct dpipe_ctx *ctx,
+ struct nlattr *nl)
+{
+ struct nlattr *nla_action_value[DEVLINK_ATTR_MAX + 1] = {};
+ struct dpipe_action action;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_action_value);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_action_value[DEVLINK_ATTR_DPIPE_ACTION] ||
+ !nla_action_value[DEVLINK_ATTR_DPIPE_VALUE]) {
+ return -EINVAL;
+ }
+
+ pr_out_entry_start(ctx->dl);
+ if (dpipe_action_parse(&action,
+ nla_action_value[DEVLINK_ATTR_DPIPE_ACTION]))
+ goto err_action_parse;
+ pr_out_dpipe_action(&action, ctx);
+ pr_out_dpipe_entry_value(ctx, nla_action_value, &action.info);
+ pr_out_entry_end(ctx->dl);
+
+ return 0;
+
+err_action_parse:
+ pr_out_entry_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int
+dpipe_tables_action_values_show(struct dpipe_ctx *ctx,
+ struct nlattr *nla_action_values)
+{
+ struct nlattr *nla_action_value;
+
+ mnl_attr_for_each_nested(nla_action_value, nla_action_values) {
+ if (dpipe_entry_action_value_show(ctx, nla_action_value))
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int
+dpipe_tables_match_values_show(struct dpipe_ctx *ctx,
+ struct nlattr *nla_match_values)
+{
+ struct nlattr *nla_match_value;
+
+ mnl_attr_for_each_nested(nla_match_value, nla_match_values) {
+ if (dpipe_entry_match_value_show(ctx, nla_match_value))
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static int dpipe_entry_show(struct dpipe_ctx *ctx, struct nlattr *nl)
+{
+ struct nlattr *nla_entry[DEVLINK_ATTR_MAX + 1] = {};
+ uint32_t entry_index;
+ uint64_t counter;
+ int err;
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_entry);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ if (!nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_INDEX] ||
+ !nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_MATCH_VALUES] ||
+ !nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_ACTION_VALUES]) {
+ return -EINVAL;
+ }
+
+ entry_index = mnl_attr_get_u32(nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_INDEX]);
+ pr_out_uint(ctx->dl, "index", entry_index);
+
+ if (nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_COUNTER]) {
+ counter = mnl_attr_get_u64(nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_COUNTER]);
+ pr_out_uint(ctx->dl, "counter", counter);
+ }
+
+ pr_out_array_start(ctx->dl, "match_value");
+ if (dpipe_tables_match_values_show(ctx,
+ nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_MATCH_VALUES]))
+ goto err_match_values_show;
+ pr_out_array_end(ctx->dl);
+
+ pr_out_array_start(ctx->dl, "action_value");
+ if (dpipe_tables_action_values_show(ctx,
+ nla_entry[DEVLINK_ATTR_DPIPE_ENTRY_ACTION_VALUES]))
+ goto err_action_values_show;
+ pr_out_array_end(ctx->dl);
+ return 0;
+
+err_action_values_show:
+err_match_values_show:
+ pr_out_array_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int dpipe_table_entries_show(struct dpipe_ctx *ctx, struct nlattr **tb)
+{
+ struct nlattr *nla_entries = tb[DEVLINK_ATTR_DPIPE_ENTRIES];
+ struct nlattr *nla_entry;
+
+ mnl_attr_for_each_nested(nla_entry, nla_entries) {
+ pr_out_handle_start_arr(ctx->dl, tb);
+ if (dpipe_entry_show(ctx, nla_entry))
+ goto err_entry_show;
+ pr_out_handle_end(ctx->dl);
+ }
+ return 0;
+
+err_entry_show:
+ pr_out_handle_end(ctx->dl);
+ return -EINVAL;
+}
+
+static int cmd_dpipe_table_entry_dump_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct dpipe_ctx *ctx = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_DPIPE_ENTRIES])
+ return MNL_CB_ERROR;
+
+ if (dpipe_table_entries_show(ctx, tb))
+ return MNL_CB_ERROR;
+ return MNL_CB_OK;
+}
+
+static int cmd_dpipe_table_dump(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct dpipe_ctx ctx = {};
+ uint16_t flags = NLM_F_REQUEST;
+ int err;
+
+ err = dpipe_ctx_init(&ctx, dl);
+ if (err)
+ return err;
+
+ err = dl_argv_parse(dl, DL_OPT_HANDLE | DL_OPT_DPIPE_TABLE_NAME, 0);
+ if (err)
+ goto out;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_HEADERS_GET, flags);
+ dl_opts_put(nlh, dl);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_header_cb, &ctx);
+ if (err) {
+ pr_err("error get headers %s\n", strerror(ctx.err));
+ goto out;
+ }
+
+ flags = NLM_F_REQUEST | NLM_F_ACK;
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_ENTRIES_GET, flags);
+ dl_opts_put(nlh, dl);
+
+ pr_out_section_start(dl, "table_entry");
+ _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_table_entry_dump_cb, &ctx);
+ pr_out_section_end(dl);
+out:
+ dpipe_ctx_fini(&ctx);
+ return err;
+}
+
+static void cmd_dpipe_table_help(void)
+{
+ pr_err("Usage: devlink dpipe table [ OBJECT-LIST ]\n"
+ "where OBJECT-LIST := { show | set | dump }\n");
+}
+
+static int cmd_dpipe_table(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dpipe_table_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_table_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_table_set(dl);
+ } else if (dl_argv_match(dl, "dump")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_table_dump(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void cmd_dpipe_help(void)
+{
+ pr_err("Usage: devlink dpipe [ OBJECT-LIST ]\n"
+ "where OBJECT-LIST := { header | table }\n");
+}
+
+static int cmd_dpipe(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_dpipe_help();
+ return 0;
+ } else if (dl_argv_match(dl, "header")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_header(dl);
+ } else if (dl_argv_match(dl, "table")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe_table(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int
+resource_parse(struct resource_ctx *ctx, struct resource *resource,
+ struct nlattr **nla_resource)
+{
+ if (!nla_resource[DEVLINK_ATTR_RESOURCE_NAME] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_SIZE] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_ID] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_UNIT] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_MIN] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_MAX] ||
+ !nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_GRAN]) {
+ return -EINVAL;
+ }
+
+ resource->name = strdup(mnl_attr_get_str(nla_resource[DEVLINK_ATTR_RESOURCE_NAME]));
+ resource->size = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE]);
+ resource->id = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_ID]);
+ resource->unit = mnl_attr_get_u8(nla_resource[DEVLINK_ATTR_RESOURCE_UNIT]);
+ resource->size_min = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_MIN]);
+ resource->size_max = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_MAX]);
+ resource->size_gran = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_GRAN]);
+
+ if (nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_NEW])
+ resource->size_new = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_NEW]);
+ else
+ resource->size_new = resource->size;
+
+ if (nla_resource[DEVLINK_ATTR_RESOURCE_OCC]) {
+ resource->size_occ = mnl_attr_get_u64(nla_resource[DEVLINK_ATTR_RESOURCE_OCC]);
+ resource->occ_valid = true;
+ }
+
+ if (resource->size_new != resource->size)
+ ctx->pending_change = true;
+
+ return 0;
+}
+
+static int
+resource_get(struct resource_ctx *ctx, struct resource *resource,
+ struct resource *parent_resource, struct nlattr *nl)
+{
+ struct nlattr *nla_resource[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *nla_child_resource;
+ struct nlattr *nla_resources;
+ bool top = false;
+ int err;
+
+ if (!resource) {
+ nla_resources = nl;
+ top = true;
+ goto out;
+ }
+
+ err = mnl_attr_parse_nested(nl, attr_cb, nla_resource);
+ if (err != MNL_CB_OK)
+ return -EINVAL;
+
+ err = resource_parse(ctx, resource, nla_resource);
+ if (err)
+ return err;
+
+ resource->parent = parent_resource;
+ if (!nla_resource[DEVLINK_ATTR_RESOURCE_LIST])
+ return 0;
+
+ resource->size_valid = !!mnl_attr_get_u8(nla_resource[DEVLINK_ATTR_RESOURCE_SIZE_VALID]);
+ nla_resources = nla_resource[DEVLINK_ATTR_RESOURCE_LIST];
+out:
+ mnl_attr_for_each_nested(nla_child_resource, nla_resources) {
+ struct resource *child_resource;
+ struct list_head *list;
+
+ child_resource = resource_alloc();
+ if (!child_resource)
+ return -ENOMEM;
+
+ if (top)
+ list = &ctx->resources->resource_list;
+ else
+ list = &resource->resource_list;
+
+ list_add_tail(&child_resource->list, list);
+ err = resource_get(ctx, child_resource, resource,
+ nla_child_resource);
+ if (err)
+ return err;
+ }
+
+ return 0;
+}
+
+static const char *resource_unit_str_get(enum devlink_resource_unit unit)
+{
+ switch (unit) {
+ case DEVLINK_RESOURCE_UNIT_ENTRY: return "entry";
+ default: return "<unknown unit>";
+ }
+}
+
+static void resource_show(struct resource *resource,
+ struct resource_ctx *ctx)
+{
+ struct resource *child_resource;
+ struct dpipe_table *table;
+ struct dl *dl = ctx->dl;
+ bool array = false;
+
+ pr_out_str(dl, "name", resource->name);
+ if (dl->verbose)
+ resource_path_print(dl, ctx->resources, resource->id);
+ pr_out_u64(dl, "size", resource->size);
+ if (resource->size != resource->size_new)
+ pr_out_u64(dl, "size_new", resource->size_new);
+ if (resource->occ_valid)
+ pr_out_uint(dl, "occ", resource->size_occ);
+ pr_out_str(dl, "unit", resource_unit_str_get(resource->unit));
+
+ if (resource->size_min != resource->size_max) {
+ pr_out_uint(dl, "size_min", resource->size_min);
+ pr_out_u64(dl, "size_max", resource->size_max);
+ pr_out_uint(dl, "size_gran", resource->size_gran);
+ }
+
+ list_for_each_entry(table, &ctx->tables->table_list, list)
+ if (table->resource_id == resource->id &&
+ table->resource_valid)
+ array = true;
+
+ if (array)
+ pr_out_array_start(dl, "dpipe_tables");
+ else
+ pr_out_str(dl, "dpipe_tables", "none");
+
+ list_for_each_entry(table, &ctx->tables->table_list, list) {
+ if (table->resource_id != resource->id ||
+ !table->resource_valid)
+ continue;
+ pr_out_entry_start(dl);
+ pr_out_str(dl, "table_name", table->name);
+ pr_out_entry_end(dl);
+ }
+ if (array)
+ pr_out_array_end(dl);
+
+ if (list_empty(&resource->resource_list))
+ return;
+
+ if (ctx->pending_change)
+ pr_out_str(dl, "size_valid", resource->size_valid ?
+ "true" : "false");
+ pr_out_array_start(dl, "resources");
+ list_for_each_entry(child_resource, &resource->resource_list, list) {
+ pr_out_entry_start(dl);
+ resource_show(child_resource, ctx);
+ pr_out_entry_end(dl);
+ }
+ pr_out_array_end(dl);
+}
+
+static void
+resources_show(struct resource_ctx *ctx, struct nlattr **tb)
+{
+ struct resources *resources = ctx->resources;
+ struct resource *resource;
+
+ list_for_each_entry(resource, &resources->resource_list, list) {
+ pr_out_handle_start_arr(ctx->dl, tb);
+ resource_show(resource, ctx);
+ pr_out_handle_end(ctx->dl);
+ }
+}
+
+static int resources_get(struct resource_ctx *ctx, struct nlattr **tb)
+{
+ return resource_get(ctx, NULL, NULL, tb[DEVLINK_ATTR_RESOURCE_LIST]);
+}
+
+static int cmd_resource_dump_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct resource_ctx *ctx = data;
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ int err;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_RESOURCE_LIST])
+ return MNL_CB_ERROR;
+
+ err = resources_get(ctx, tb);
+ if (err) {
+ ctx->err = err;
+ return MNL_CB_ERROR;
+ }
+
+ if (ctx->print_resources)
+ resources_show(ctx, tb);
+
+ return MNL_CB_OK;
+}
+
+static int cmd_resource_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct dpipe_ctx dpipe_ctx = {};
+ struct resource_ctx resource_ctx = {};
+ int err;
+
+ err = dl_argv_parse(dl, DL_OPT_HANDLE, 0);
+ if (err)
+ return err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_DPIPE_TABLE_GET,
+ NLM_F_REQUEST);
+ dl_opts_put(nlh, dl);
+
+ err = dpipe_ctx_init(&dpipe_ctx, dl);
+ if (err)
+ return err;
+
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_dpipe_table_show_cb,
+ &dpipe_ctx);
+ if (err) {
+ pr_err("error get tables %s\n", strerror(dpipe_ctx.err));
+ goto out;
+ }
+
+ err = resource_ctx_init(&resource_ctx, dl);
+ if (err)
+ goto out;
+
+ resource_ctx.print_resources = true;
+ resource_ctx.tables = dpipe_ctx.tables;
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_RESOURCE_DUMP,
+ NLM_F_REQUEST | NLM_F_ACK);
+ dl_opts_put(nlh, dl);
+ pr_out_section_start(dl, "resources");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_resource_dump_cb,
+ &resource_ctx);
+ pr_out_section_end(dl);
+ resource_ctx_fini(&resource_ctx);
+out:
+ dpipe_ctx_fini(&dpipe_ctx);
+ return err;
+}
+
+static void cmd_resource_help(void)
+{
+ pr_err("Usage: devlink resource show DEV\n"
+ " devlink resource set DEV path PATH size SIZE\n");
+}
+
+static struct resource *
+resource_find_by_name(struct list_head *list, char *name)
+{
+ struct resource *resource;
+
+ list_for_each_entry(resource, list, list) {
+ if (!strcmp(resource->name, name))
+ return resource;
+ }
+ return NULL;
+}
+
+static int
+resource_path_parse(struct resource_ctx *ctx, const char *resource_path,
+ uint32_t *p_resource_id, bool *p_resource_valid)
+{
+ struct resource *resource;
+ uint32_t resource_id = 0;
+ char *resource_path_dup;
+ struct list_head *list;
+ const char del[] = "/";
+ char *resource_name;
+
+ resource_path_dup = strdup(resource_path);
+ list = &ctx->resources->resource_list;
+ resource_name = strtok(resource_path_dup, del);
+ while (resource_name != NULL) {
+ resource = resource_find_by_name(list, resource_name);
+ if (!resource)
+ goto err_resource_lookup;
+
+ list = &resource->resource_list;
+ resource_name = strtok(NULL, del);
+ resource_id = resource->id;
+ }
+ free(resource_path_dup);
+ *p_resource_valid = true;
+ *p_resource_id = resource_id;
+ return 0;
+
+err_resource_lookup:
+ free(resource_path_dup);
+ return -EINVAL;
+}
+
+static int cmd_resource_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ struct resource_ctx ctx = {};
+ int err;
+
+ err = resource_ctx_init(&ctx, dl);
+ if (err)
+ return err;
+
+ ctx.print_resources = false;
+ err = dl_argv_parse(dl, DL_OPT_HANDLE | DL_OPT_RESOURCE_PATH |
+ DL_OPT_RESOURCE_SIZE, 0);
+ if (err)
+ goto out;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_RESOURCE_DUMP,
+ NLM_F_REQUEST);
+ dl_opts_put(nlh, dl);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_resource_dump_cb, &ctx);
+ if (err) {
+ pr_err("error getting resources %s\n", strerror(ctx.err));
+ goto out;
+ }
+
+ err = resource_path_parse(&ctx, dl->opts.resource_path,
+ &dl->opts.resource_id,
+ &dl->opts.resource_id_valid);
+ if (err) {
+ pr_err("error parsing resource path %s\n", strerror(-err));
+ goto out;
+ }
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_RESOURCE_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ dl_opts_put(nlh, dl);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+out:
+ resource_ctx_fini(&ctx);
+ return err;
+}
+
+static int cmd_resource(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ cmd_resource_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_resource_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_resource_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void pr_out_region_handle_start(struct dl *dl, struct nlattr **tb)
+{
+ const char *bus_name = mnl_attr_get_str(tb[DEVLINK_ATTR_BUS_NAME]);
+ const char *dev_name = mnl_attr_get_str(tb[DEVLINK_ATTR_DEV_NAME]);
+ const char *region_name = mnl_attr_get_str(tb[DEVLINK_ATTR_REGION_NAME]);
+ char buf[256];
+
+ sprintf(buf, "%s/%s/%s", bus_name, dev_name, region_name);
+ if (dl->json_output) {
+ jsonw_name(dl->jw, buf);
+ jsonw_start_object(dl->jw);
+ } else {
+ pr_out("%s:", buf);
+ }
+}
+
+static void pr_out_region_handle_end(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_end_object(dl->jw);
+ else
+ pr_out("\n");
+}
+
+static void pr_out_region_snapshots_start(struct dl *dl, bool array)
+{
+ __pr_out_indent_newline(dl);
+ if (dl->json_output) {
+ jsonw_name(dl->jw, "snapshot");
+ jsonw_start_array(dl->jw);
+ } else {
+ pr_out("snapshot %s", array ? "[" : "");
+ }
+}
+
+static void pr_out_region_snapshots_end(struct dl *dl, bool array)
+{
+ if (dl->json_output)
+ jsonw_end_array(dl->jw);
+ else if (array)
+ pr_out("]");
+}
+
+static void pr_out_region_snapshots_id(struct dl *dl, struct nlattr **tb, int index)
+{
+ uint32_t snapshot_id;
+
+ if (!tb[DEVLINK_ATTR_REGION_SNAPSHOT_ID])
+ return;
+
+ snapshot_id = mnl_attr_get_u32(tb[DEVLINK_ATTR_REGION_SNAPSHOT_ID]);
+
+ if (dl->json_output)
+ jsonw_uint(dl->jw, snapshot_id);
+ else
+ pr_out("%s%u", index ? " " : "", snapshot_id);
+}
+
+static void pr_out_snapshots(struct dl *dl, struct nlattr **tb)
+{
+ struct nlattr *tb_snapshot[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *nla_sanpshot;
+ int err, index = 0;
+
+ pr_out_region_snapshots_start(dl, true);
+ mnl_attr_for_each_nested(nla_sanpshot, tb[DEVLINK_ATTR_REGION_SNAPSHOTS]) {
+ err = mnl_attr_parse_nested(nla_sanpshot, attr_cb, tb_snapshot);
+ if (err != MNL_CB_OK)
+ return;
+ pr_out_region_snapshots_id(dl, tb_snapshot, index++);
+ }
+ pr_out_region_snapshots_end(dl, true);
+}
+
+static void pr_out_snapshot(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_region_snapshots_start(dl, false);
+ pr_out_region_snapshots_id(dl, tb, 0);
+ pr_out_region_snapshots_end(dl, false);
+}
+
+static void pr_out_region(struct dl *dl, struct nlattr **tb)
+{
+ pr_out_region_handle_start(dl, tb);
+
+ if (tb[DEVLINK_ATTR_REGION_SIZE])
+ pr_out_u64(dl, "size",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_REGION_SIZE]));
+
+ if (tb[DEVLINK_ATTR_REGION_SNAPSHOTS])
+ pr_out_snapshots(dl, tb);
+
+ if (tb[DEVLINK_ATTR_REGION_SNAPSHOT_ID])
+ pr_out_snapshot(dl, tb);
+
+ pr_out_region_handle_end(dl);
+}
+
+static int cmd_region_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_REGION_NAME] || !tb[DEVLINK_ATTR_REGION_SIZE])
+ return MNL_CB_ERROR;
+
+ pr_out_region(dl, tb);
+
+ return MNL_CB_OK;
+}
+
+static int cmd_region_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_REGION_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE_REGION, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "regions");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_region_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static int cmd_region_snapshot_del(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_REGION_DEL,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE_REGION |
+ DL_OPT_REGION_SNAPSHOT_ID, 0);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_region_read_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct nlattr *nla_entry, *nla_chunk_data, *nla_chunk_addr;
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb_field[DEVLINK_ATTR_MAX + 1] = {};
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+ int err;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_REGION_CHUNKS])
+ return MNL_CB_ERROR;
+
+ mnl_attr_for_each_nested(nla_entry, tb[DEVLINK_ATTR_REGION_CHUNKS]) {
+ err = mnl_attr_parse_nested(nla_entry, attr_cb, tb_field);
+ if (err != MNL_CB_OK)
+ return MNL_CB_ERROR;
+
+ nla_chunk_data = tb_field[DEVLINK_ATTR_REGION_CHUNK_DATA];
+ if (!nla_chunk_data)
+ continue;
+
+ nla_chunk_addr = tb_field[DEVLINK_ATTR_REGION_CHUNK_ADDR];
+ if (!nla_chunk_addr)
+ continue;
+
+ pr_out_region_chunk(dl, mnl_attr_get_payload(nla_chunk_data),
+ mnl_attr_get_payload_len(nla_chunk_data),
+ mnl_attr_get_u64(nla_chunk_addr));
+ }
+ return MNL_CB_OK;
+}
+
+static int cmd_region_dump(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_REGION_READ,
+ NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE_REGION |
+ DL_OPT_REGION_SNAPSHOT_ID, 0);
+ if (err)
+ return err;
+
+ pr_out_section_start(dl, "dump");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_region_read_cb, dl);
+ pr_out_section_end(dl);
+ if (!dl->json_output)
+ pr_out("\n");
+ return err;
+}
+
+static int cmd_region_read(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_REGION_READ,
+ NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE_REGION |
+ DL_OPT_REGION_ADDRESS | DL_OPT_REGION_LENGTH |
+ DL_OPT_REGION_SNAPSHOT_ID, 0);
+ if (err)
+ return err;
+
+ pr_out_section_start(dl, "read");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_region_read_cb, dl);
+ pr_out_section_end(dl);
+ if (!dl->json_output)
+ pr_out("\n");
+ return err;
+}
+
+static void cmd_region_help(void)
+{
+ pr_err("Usage: devlink region show [ DEV/REGION ]\n");
+ pr_err(" devlink region del DEV/REGION snapshot SNAPSHOT_ID\n");
+ pr_err(" devlink region dump DEV/REGION [ snapshot SNAPSHOT_ID ]\n");
+ pr_err(" devlink region read DEV/REGION [ snapshot SNAPSHOT_ID ] address ADDRESS length LENGTH\n");
+}
+
+static int cmd_region(struct dl *dl)
+{
+ if (dl_no_arg(dl)) {
+ return cmd_region_show(dl);
+ } else if (dl_argv_match(dl, "help")) {
+ cmd_region_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_region_show(dl);
+ } else if (dl_argv_match(dl, "del")) {
+ dl_arg_inc(dl);
+ return cmd_region_snapshot_del(dl);
+ } else if (dl_argv_match(dl, "dump")) {
+ dl_arg_inc(dl);
+ return cmd_region_dump(dl);
+ } else if (dl_argv_match(dl, "read")) {
+ dl_arg_inc(dl);
+ return cmd_region_read(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int cmd_health_set_params(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_HEALTH_REPORTER_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+ err = dl_argv_parse(dl, DL_OPT_HANDLE | DL_OPT_HEALTH_REPORTER_NAME,
+ DL_OPT_HEALTH_REPORTER_GRACEFUL_PERIOD |
+ DL_OPT_HEALTH_REPORTER_AUTO_RECOVER);
+ if (err)
+ return err;
+
+ dl_opts_put(nlh, dl);
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_health_dump_clear(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_HEALTH_REPORTER_DUMP_CLEAR,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_HEALTH_REPORTER_NAME, 0);
+ if (err)
+ return err;
+
+ dl_opts_put(nlh, dl);
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int fmsg_value_show(struct dl *dl, int type, struct nlattr *nl_data)
+{
+ uint8_t *data;
+ uint32_t len;
+
+ switch (type) {
+ case MNL_TYPE_FLAG:
+ pr_out_bool_value(dl, mnl_attr_get_u8(nl_data));
+ break;
+ case MNL_TYPE_U8:
+ pr_out_uint_value(dl, mnl_attr_get_u8(nl_data));
+ break;
+ case MNL_TYPE_U16:
+ pr_out_uint_value(dl, mnl_attr_get_u16(nl_data));
+ break;
+ case MNL_TYPE_U32:
+ pr_out_uint_value(dl, mnl_attr_get_u32(nl_data));
+ break;
+ case MNL_TYPE_U64:
+ pr_out_uint64_value(dl, mnl_attr_get_u64(nl_data));
+ break;
+ case MNL_TYPE_NUL_STRING:
+ pr_out_str_value(dl, mnl_attr_get_str(nl_data));
+ break;
+ case MNL_TYPE_BINARY:
+ len = mnl_attr_get_payload_len(nl_data);
+ data = mnl_attr_get_payload(nl_data);
+ pr_out_binary_value(dl, data, len);
+ break;
+ default:
+ return -EINVAL;
+ }
+ return MNL_CB_OK;
+}
+
+struct nest_entry {
+ int attr_type;
+ struct list_head list;
+};
+
+struct fmsg_cb_data {
+ struct dl *dl;
+ uint8_t value_type;
+ struct list_head entry_list;
+};
+
+static int cmd_fmsg_nest_queue(struct fmsg_cb_data *fmsg_data,
+ uint8_t *attr_value, bool insert)
+{
+ struct nest_entry *entry;
+
+ if (insert) {
+ entry = malloc(sizeof(struct nest_entry));
+ if (!entry)
+ return -ENOMEM;
+
+ entry->attr_type = *attr_value;
+ list_add(&entry->list, &fmsg_data->entry_list);
+ } else {
+ if (list_empty(&fmsg_data->entry_list))
+ return MNL_CB_ERROR;
+ entry = list_first_entry(&fmsg_data->entry_list,
+ struct nest_entry, list);
+ *attr_value = entry->attr_type;
+ list_del(&entry->list);
+ free(entry);
+ }
+ return MNL_CB_OK;
+}
+
+static int cmd_fmsg_nest(struct fmsg_cb_data *fmsg_data, uint8_t nest_value,
+ bool start)
+{
+ struct dl *dl = fmsg_data->dl;
+ uint8_t value = nest_value;
+ int err;
+
+ err = cmd_fmsg_nest_queue(fmsg_data, &value, start);
+ if (err != MNL_CB_OK)
+ return err;
+
+ switch (value) {
+ case DEVLINK_ATTR_FMSG_OBJ_NEST_START:
+ if (start)
+ pr_out_entry_start(dl);
+ else
+ pr_out_entry_end(dl);
+ break;
+ case DEVLINK_ATTR_FMSG_PAIR_NEST_START:
+ break;
+ case DEVLINK_ATTR_FMSG_ARR_NEST_START:
+ if (dl->json_output) {
+ if (start)
+ jsonw_start_array(dl->jw);
+ else
+ jsonw_end_array(dl->jw);
+ } else {
+ if (start) {
+ __pr_out_newline();
+ __pr_out_indent_inc();
+ } else {
+ __pr_out_indent_dec();
+ }
+ }
+ break;
+ default:
+ return -EINVAL;
+ }
+ return MNL_CB_OK;
+}
+
+static int cmd_fmsg_object_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct fmsg_cb_data *fmsg_data = data;
+ struct dl *dl = fmsg_data->dl;
+ struct nlattr *nla_object;
+ int attr_type;
+ int err;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_FMSG])
+ return MNL_CB_ERROR;
+
+ mnl_attr_for_each_nested(nla_object, tb[DEVLINK_ATTR_FMSG]) {
+ attr_type = mnl_attr_get_type(nla_object);
+ switch (attr_type) {
+ case DEVLINK_ATTR_FMSG_OBJ_NEST_START:
+ case DEVLINK_ATTR_FMSG_PAIR_NEST_START:
+ case DEVLINK_ATTR_FMSG_ARR_NEST_START:
+ err = cmd_fmsg_nest(fmsg_data, attr_type, true);
+ if (err != MNL_CB_OK)
+ return err;
+ break;
+ case DEVLINK_ATTR_FMSG_NEST_END:
+ err = cmd_fmsg_nest(fmsg_data, attr_type, false);
+ if (err != MNL_CB_OK)
+ return err;
+ break;
+ case DEVLINK_ATTR_FMSG_OBJ_NAME:
+ pr_out_name(dl, mnl_attr_get_str(nla_object));
+ break;
+ case DEVLINK_ATTR_FMSG_OBJ_VALUE_TYPE:
+ fmsg_data->value_type = mnl_attr_get_u8(nla_object);
+ break;
+ case DEVLINK_ATTR_FMSG_OBJ_VALUE_DATA:
+ err = fmsg_value_show(dl, fmsg_data->value_type,
+ nla_object);
+ if (err != MNL_CB_OK)
+ return err;
+ break;
+ default:
+ return -EINVAL;
+ }
+ }
+ return MNL_CB_OK;
+}
+
+static int cmd_health_object_common(struct dl *dl, uint8_t cmd, uint16_t flags)
+{
+ struct fmsg_cb_data data;
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, cmd, flags | NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_HEALTH_REPORTER_NAME, 0);
+ if (err)
+ return err;
+
+ data.dl = dl;
+ INIT_LIST_HEAD(&data.entry_list);
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_fmsg_object_cb, &data);
+ return err;
+}
+
+static int cmd_health_dump_show(struct dl *dl)
+{
+ return cmd_health_object_common(dl,
+ DEVLINK_CMD_HEALTH_REPORTER_DUMP_GET,
+ NLM_F_DUMP);
+}
+
+static int cmd_health_diagnose(struct dl *dl)
+{
+ return cmd_health_object_common(dl,
+ DEVLINK_CMD_HEALTH_REPORTER_DIAGNOSE,
+ 0);
+}
+
+static int cmd_health_recover(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_HEALTH_REPORTER_RECOVER,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_HEALTH_REPORTER_NAME, 0);
+ if (err)
+ return err;
+
+ dl_opts_put(nlh, dl);
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+enum devlink_health_reporter_state {
+ DEVLINK_HEALTH_REPORTER_STATE_HEALTHY,
+ DEVLINK_HEALTH_REPORTER_STATE_ERROR,
+};
+
+static const char *health_state_name(uint8_t state)
+{
+ switch (state) {
+ case DEVLINK_HEALTH_REPORTER_STATE_HEALTHY:
+ return HEALTH_REPORTER_STATE_HEALTHY_STR;
+ case DEVLINK_HEALTH_REPORTER_STATE_ERROR:
+ return HEALTH_REPORTER_STATE_ERROR_STR;
+ default:
+ return "<unknown state>";
+ }
+}
+
+static void format_logtime(uint64_t time_ms, char *ts_date, char *ts_time)
+{
+ struct sysinfo s_info;
+ struct tm *info;
+ time_t now, sec;
+ int err;
+
+ time(&now);
+ info = localtime(&now);
+ err = sysinfo(&s_info);
+ if (err)
+ goto out;
+ /* Subtract uptime in sec from now yields the time of system
+ * uptime. To this, add time_ms which is the amount of
+ * milliseconds elapsed between uptime and the dump taken.
+ */
+ sec = now - s_info.uptime + time_ms / 1000;
+ info = localtime(&sec);
+out:
+ strftime(ts_date, HEALTH_REPORTER_TIMESTAMP_FMT_LEN, "%Y-%m-%d", info);
+ strftime(ts_time, HEALTH_REPORTER_TIMESTAMP_FMT_LEN, "%H:%M:%S", info);
+}
+
+static void pr_out_health(struct dl *dl, struct nlattr **tb_health)
+{
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ enum devlink_health_reporter_state state;
+ const struct nlattr *attr;
+ uint64_t time_ms;
+ int err;
+
+ err = mnl_attr_parse_nested(tb_health[DEVLINK_ATTR_HEALTH_REPORTER],
+ attr_cb, tb);
+ if (err != MNL_CB_OK)
+ return;
+
+ if (!tb[DEVLINK_ATTR_HEALTH_REPORTER_NAME] ||
+ !tb[DEVLINK_ATTR_HEALTH_REPORTER_ERR_COUNT] ||
+ !tb[DEVLINK_ATTR_HEALTH_REPORTER_RECOVER_COUNT] ||
+ !tb[DEVLINK_ATTR_HEALTH_REPORTER_STATE])
+ return;
+
+ pr_out_handle_start_arr(dl, tb_health);
+
+ pr_out_str(dl, "reporter",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_HEALTH_REPORTER_NAME]));
+ if (!dl->json_output) {
+ __pr_out_newline();
+ __pr_out_indent_inc();
+ }
+ state = mnl_attr_get_u8(tb[DEVLINK_ATTR_HEALTH_REPORTER_STATE]);
+ pr_out_str(dl, "state", health_state_name(state));
+ pr_out_u64(dl, "error",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_HEALTH_REPORTER_ERR_COUNT]));
+ pr_out_u64(dl, "recover",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_HEALTH_REPORTER_RECOVER_COUNT]));
+ if (tb[DEVLINK_ATTR_HEALTH_REPORTER_DUMP_TS]) {
+ char dump_date[HEALTH_REPORTER_TIMESTAMP_FMT_LEN];
+ char dump_time[HEALTH_REPORTER_TIMESTAMP_FMT_LEN];
+
+ attr = tb[DEVLINK_ATTR_HEALTH_REPORTER_DUMP_TS];
+ time_ms = mnl_attr_get_u64(attr);
+ format_logtime(time_ms, dump_date, dump_time);
+
+ pr_out_str(dl, "last_dump_date", dump_date);
+ pr_out_str(dl, "last_dump_time", dump_time);
+ }
+ if (tb[DEVLINK_ATTR_HEALTH_REPORTER_GRACEFUL_PERIOD])
+ pr_out_u64(dl, "grace_period",
+ mnl_attr_get_u64(tb[DEVLINK_ATTR_HEALTH_REPORTER_GRACEFUL_PERIOD]));
+ if (tb[DEVLINK_ATTR_HEALTH_REPORTER_AUTO_RECOVER])
+ pr_out_bool(dl, "auto_recover",
+ mnl_attr_get_u8(tb[DEVLINK_ATTR_HEALTH_REPORTER_AUTO_RECOVER]));
+
+ __pr_out_indent_dec();
+ pr_out_handle_end(dl);
+}
+
+static int cmd_health_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_HEALTH_REPORTER])
+ return MNL_CB_ERROR;
+
+ pr_out_health(dl, tb);
+
+ return MNL_CB_OK;
+}
+
+static int cmd_health_show(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_HEALTH_REPORTER_GET,
+ flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE |
+ DL_OPT_HEALTH_REPORTER_NAME, 0);
+ if (err)
+ return err;
+ }
+ pr_out_section_start(dl, "health");
+
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_health_show_cb, dl);
+ pr_out_section_end(dl);
+ return err;
+}
+
+static void cmd_health_help(void)
+{
+ pr_err("Usage: devlink health show [ dev DEV reporter REPORTER_NAME ]\n");
+ pr_err(" devlink health recover DEV reporter REPORTER_NAME\n");
+ pr_err(" devlink health diagnose DEV reporter REPORTER_NAME\n");
+ pr_err(" devlink health dump show DEV reporter REPORTER_NAME\n");
+ pr_err(" devlink health dump clear DEV reporter REPORTER_NAME\n");
+ pr_err(" devlink health set DEV reporter REPORTER_NAME { grace_period | auto_recover } { msec | boolean }\n");
+}
+
+static int cmd_health(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_health_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_health_show(dl);
+ } else if (dl_argv_match(dl, "recover")) {
+ dl_arg_inc(dl);
+ return cmd_health_recover(dl);
+ } else if (dl_argv_match(dl, "diagnose")) {
+ dl_arg_inc(dl);
+ return cmd_health_diagnose(dl);
+ } else if (dl_argv_match(dl, "dump")) {
+ dl_arg_inc(dl);
+ if (dl_argv_match(dl, "show")) {
+ dl_arg_inc(dl);
+ return cmd_health_dump_show(dl);
+ } else if (dl_argv_match(dl, "clear")) {
+ dl_arg_inc(dl);
+ return cmd_health_dump_clear(dl);
+ }
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_health_set_params(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static const char *trap_type_name(uint8_t type)
+{
+ switch (type) {
+ case DEVLINK_TRAP_TYPE_DROP:
+ return "drop";
+ case DEVLINK_TRAP_TYPE_EXCEPTION:
+ return "exception";
+ default:
+ return "<unknown type>";
+ }
+}
+
+static const char *trap_action_name(uint8_t action)
+{
+ switch (action) {
+ case DEVLINK_TRAP_ACTION_DROP:
+ return "drop";
+ case DEVLINK_TRAP_ACTION_TRAP:
+ return "trap";
+ default:
+ return "<unknown action>";
+ }
+}
+
+static const char *trap_metadata_name(const struct nlattr *attr)
+{
+ switch (attr->nla_type) {
+ case DEVLINK_ATTR_TRAP_METADATA_TYPE_IN_PORT:
+ return "input_port";
+ default:
+ return "<unknown metadata type>";
+ }
+}
+static void pr_out_trap_metadata(struct dl *dl, struct nlattr *attr)
+{
+ struct nlattr *attr_metadata;
+
+ pr_out_array_start(dl, "metadata");
+ mnl_attr_for_each_nested(attr_metadata, attr)
+ pr_out_str_value(dl, trap_metadata_name(attr_metadata));
+ pr_out_array_end(dl);
+}
+
+static void pr_out_trap(struct dl *dl, struct nlattr **tb, bool array)
+{
+ uint8_t action = mnl_attr_get_u8(tb[DEVLINK_ATTR_TRAP_ACTION]);
+ uint8_t type = mnl_attr_get_u8(tb[DEVLINK_ATTR_TRAP_TYPE]);
+
+ if (array)
+ pr_out_handle_start_arr(dl, tb);
+ else
+ __pr_out_handle_start(dl, tb, true, false);
+
+ pr_out_str(dl, "name", mnl_attr_get_str(tb[DEVLINK_ATTR_TRAP_NAME]));
+ pr_out_str(dl, "type", trap_type_name(type));
+ pr_out_bool(dl, "generic", !!tb[DEVLINK_ATTR_TRAP_GENERIC]);
+ pr_out_str(dl, "action", trap_action_name(action));
+ pr_out_str(dl, "group",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_TRAP_GROUP_NAME]));
+ if (dl->verbose)
+ pr_out_trap_metadata(dl, tb[DEVLINK_ATTR_TRAP_METADATA]);
+ pr_out_stats(dl, tb[DEVLINK_ATTR_STATS]);
+ pr_out_handle_end(dl);
+}
+
+static int cmd_trap_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_NAME] || !tb[DEVLINK_ATTR_TRAP_TYPE] ||
+ !tb[DEVLINK_ATTR_TRAP_ACTION] ||
+ !tb[DEVLINK_ATTR_TRAP_GROUP_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_METADATA] || !tb[DEVLINK_ATTR_STATS])
+ return MNL_CB_ERROR;
+
+ pr_out_trap(dl, tb, true);
+
+ return MNL_CB_OK;
+}
+
+static void cmd_trap_help(void)
+{
+ pr_err("Usage: devlink trap set DEV trap TRAP [ action { trap | drop } ]\n");
+ pr_err(" devlink trap show [ DEV trap TRAP ]\n");
+ pr_err(" devlink trap group set DEV group GROUP [ action { trap | drop } ]\n");
+ pr_err(" devlink trap group show [ DEV group GROUP ]\n");
+}
+
+static int cmd_trap_show(struct dl *dl)
+{
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ struct nlmsghdr *nlh;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_TRAP_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_TRAP_NAME, 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "trap");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_trap_show_cb, dl);
+ pr_out_section_end(dl);
+
+ return err;
+}
+
+static int cmd_trap_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_TRAP_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl, DL_OPT_HANDLE | DL_OPT_TRAP_NAME,
+ DL_OPT_TRAP_ACTION);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static void pr_out_trap_group(struct dl *dl, struct nlattr **tb, bool array)
+{
+ if (array)
+ pr_out_handle_start_arr(dl, tb);
+ else
+ __pr_out_handle_start(dl, tb, true, false);
+
+ pr_out_str(dl, "name",
+ mnl_attr_get_str(tb[DEVLINK_ATTR_TRAP_GROUP_NAME]));
+ pr_out_bool(dl, "generic", !!tb[DEVLINK_ATTR_TRAP_GENERIC]);
+ pr_out_stats(dl, tb[DEVLINK_ATTR_STATS]);
+ pr_out_handle_end(dl);
+}
+
+static int cmd_trap_group_show_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+ struct nlattr *tb[DEVLINK_ATTR_MAX + 1] = {};
+ struct dl *dl = data;
+
+ mnl_attr_parse(nlh, sizeof(*genl), attr_cb, tb);
+ if (!tb[DEVLINK_ATTR_BUS_NAME] || !tb[DEVLINK_ATTR_DEV_NAME] ||
+ !tb[DEVLINK_ATTR_TRAP_GROUP_NAME] || !tb[DEVLINK_ATTR_STATS])
+ return MNL_CB_ERROR;
+
+ pr_out_trap_group(dl, tb, true);
+
+ return MNL_CB_OK;
+}
+
+static int cmd_trap_group_show(struct dl *dl)
+{
+ uint16_t flags = NLM_F_REQUEST | NLM_F_ACK;
+ struct nlmsghdr *nlh;
+ int err;
+
+ if (dl_argc(dl) == 0)
+ flags |= NLM_F_DUMP;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_TRAP_GROUP_GET, flags);
+
+ if (dl_argc(dl) > 0) {
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_TRAP_GROUP_NAME,
+ 0);
+ if (err)
+ return err;
+ }
+
+ pr_out_section_start(dl, "trap_group");
+ err = _mnlg_socket_sndrcv(dl->nlg, nlh, cmd_trap_group_show_cb, dl);
+ pr_out_section_end(dl);
+
+ return err;
+}
+
+static int cmd_trap_group_set(struct dl *dl)
+{
+ struct nlmsghdr *nlh;
+ int err;
+
+ nlh = mnlg_msg_prepare(dl->nlg, DEVLINK_CMD_TRAP_GROUP_SET,
+ NLM_F_REQUEST | NLM_F_ACK);
+
+ err = dl_argv_parse_put(nlh, dl,
+ DL_OPT_HANDLE | DL_OPT_TRAP_GROUP_NAME,
+ DL_OPT_TRAP_ACTION);
+ if (err)
+ return err;
+
+ return _mnlg_socket_sndrcv(dl->nlg, nlh, NULL, NULL);
+}
+
+static int cmd_trap_group(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_trap_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_trap_group_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_trap_group_set(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int cmd_trap(struct dl *dl)
+{
+ if (dl_argv_match(dl, "help")) {
+ cmd_trap_help();
+ return 0;
+ } else if (dl_argv_match(dl, "show") ||
+ dl_argv_match(dl, "list") || dl_no_arg(dl)) {
+ dl_arg_inc(dl);
+ return cmd_trap_show(dl);
+ } else if (dl_argv_match(dl, "set")) {
+ dl_arg_inc(dl);
+ return cmd_trap_set(dl);
+ } else if (dl_argv_match(dl, "group")) {
+ dl_arg_inc(dl);
+ return cmd_trap_group(dl);
+ }
+ pr_err("Command \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static void help(void)
+{
+ pr_err("Usage: devlink [ OPTIONS ] OBJECT { COMMAND | help }\n"
+ " devlink [ -f[orce] ] -b[atch] filename\n"
+ "where OBJECT := { dev | port | sb | monitor | dpipe | resource | region | health | trap }\n"
+ " OPTIONS := { -V[ersion] | -n[o-nice-names] | -j[son] | -p[retty] | -v[erbose] -s[tatistics] }\n");
+}
+
+static int dl_cmd(struct dl *dl, int argc, char **argv)
+{
+ dl->argc = argc;
+ dl->argv = argv;
+
+ if (dl_argv_match(dl, "help") || dl_no_arg(dl)) {
+ help();
+ return 0;
+ } else if (dl_argv_match(dl, "dev")) {
+ dl_arg_inc(dl);
+ return cmd_dev(dl);
+ } else if (dl_argv_match(dl, "port")) {
+ dl_arg_inc(dl);
+ return cmd_port(dl);
+ } else if (dl_argv_match(dl, "sb")) {
+ dl_arg_inc(dl);
+ return cmd_sb(dl);
+ } else if (dl_argv_match(dl, "monitor")) {
+ dl_arg_inc(dl);
+ return cmd_mon(dl);
+ } else if (dl_argv_match(dl, "dpipe")) {
+ dl_arg_inc(dl);
+ return cmd_dpipe(dl);
+ } else if (dl_argv_match(dl, "resource")) {
+ dl_arg_inc(dl);
+ return cmd_resource(dl);
+ } else if (dl_argv_match(dl, "region")) {
+ dl_arg_inc(dl);
+ return cmd_region(dl);
+ } else if (dl_argv_match(dl, "health")) {
+ dl_arg_inc(dl);
+ return cmd_health(dl);
+ } else if (dl_argv_match(dl, "trap")) {
+ dl_arg_inc(dl);
+ return cmd_trap(dl);
+ }
+ pr_err("Object \"%s\" not found\n", dl_argv(dl));
+ return -ENOENT;
+}
+
+static int dl_init(struct dl *dl)
+{
+ int err;
+
+ dl->nlg = mnlg_socket_open(DEVLINK_GENL_NAME, DEVLINK_GENL_VERSION);
+ if (!dl->nlg) {
+ pr_err("Failed to connect to devlink Netlink\n");
+ return -errno;
+ }
+
+ err = ifname_map_init(dl);
+ if (err) {
+ pr_err("Failed to create index map\n");
+ goto err_ifname_map_create;
+ }
+ if (dl->json_output) {
+ dl->jw = jsonw_new(stdout);
+ if (!dl->jw) {
+ pr_err("Failed to create JSON writer\n");
+ goto err_json_new;
+ }
+ jsonw_pretty(dl->jw, dl->pretty_output);
+ }
+ return 0;
+
+err_json_new:
+ ifname_map_fini(dl);
+err_ifname_map_create:
+ mnlg_socket_close(dl->nlg);
+ return err;
+}
+
+static void dl_fini(struct dl *dl)
+{
+ if (dl->json_output)
+ jsonw_destroy(&dl->jw);
+ ifname_map_fini(dl);
+ mnlg_socket_close(dl->nlg);
+}
+
+static struct dl *dl_alloc(void)
+{
+ struct dl *dl;
+
+ dl = calloc(1, sizeof(*dl));
+ if (!dl)
+ return NULL;
+ return dl;
+}
+
+static void dl_free(struct dl *dl)
+{
+ free(dl);
+}
+
+static int dl_batch(struct dl *dl, const char *name, bool force)
+{
+ char *line = NULL;
+ size_t len = 0;
+ int ret = EXIT_SUCCESS;
+
+ if (name && strcmp(name, "-") != 0) {
+ if (freopen(name, "r", stdin) == NULL) {
+ fprintf(stderr,
+ "Cannot open file \"%s\" for reading: %s\n",
+ name, strerror(errno));
+ return EXIT_FAILURE;
+ }
+ }
+
+ cmdlineno = 0;
+ while (getcmdline(&line, &len, stdin) != -1) {
+ char *largv[100];
+ int largc;
+
+ largc = makeargs(line, largv, 100);
+ if (!largc)
+ continue; /* blank line */
+
+ if (dl_cmd(dl, largc, largv)) {
+ fprintf(stderr, "Command failed %s:%d\n",
+ name, cmdlineno);
+ ret = EXIT_FAILURE;
+ if (!force)
+ break;
+ }
+ }
+
+ if (line)
+ free(line);
+
+ return ret;
+}
+
+int main(int argc, char **argv)
+{
+ static const struct option long_options[] = {
+ { "Version", no_argument, NULL, 'V' },
+ { "force", no_argument, NULL, 'f' },
+ { "batch", required_argument, NULL, 'b' },
+ { "no-nice-names", no_argument, NULL, 'n' },
+ { "json", no_argument, NULL, 'j' },
+ { "pretty", no_argument, NULL, 'p' },
+ { "verbose", no_argument, NULL, 'v' },
+ { "statistics", no_argument, NULL, 's' },
+ { NULL, 0, NULL, 0 }
+ };
+ const char *batch_file = NULL;
+ bool force = false;
+ struct dl *dl;
+ int opt;
+ int err;
+ int ret;
+
+ dl = dl_alloc();
+ if (!dl) {
+ pr_err("Failed to allocate memory for devlink\n");
+ return EXIT_FAILURE;
+ }
+
+ while ((opt = getopt_long(argc, argv, "Vfb:njpvs",
+ long_options, NULL)) >= 0) {
+
+ switch (opt) {
+ case 'V':
+ printf("devlink utility, iproute2-ss%s\n", SNAPSHOT);
+ ret = EXIT_SUCCESS;
+ goto dl_free;
+ case 'f':
+ force = true;
+ break;
+ case 'b':
+ batch_file = optarg;
+ break;
+ case 'n':
+ dl->no_nice_names = true;
+ break;
+ case 'j':
+ dl->json_output = true;
+ break;
+ case 'p':
+ dl->pretty_output = true;
+ break;
+ case 'v':
+ dl->verbose = true;
+ break;
+ case 's':
+ dl->stats = true;
+ break;
+ default:
+ pr_err("Unknown option.\n");
+ help();
+ ret = EXIT_FAILURE;
+ goto dl_free;
+ }
+ }
+
+ argc -= optind;
+ argv += optind;
+
+ err = dl_init(dl);
+ if (err) {
+ ret = EXIT_FAILURE;
+ goto dl_free;
+ }
+
+ if (batch_file)
+ err = dl_batch(dl, batch_file, force);
+ else
+ err = dl_cmd(dl, argc, argv);
+
+ if (err) {
+ ret = EXIT_FAILURE;
+ goto dl_fini;
+ }
+
+ ret = EXIT_SUCCESS;
+
+dl_fini:
+ dl_fini(dl);
+dl_free:
+ dl_free(dl);
+
+ return ret;
+}
diff --git a/devlink/mnlg.c b/devlink/mnlg.c
new file mode 100644
index 0000000..c7d25e8
--- /dev/null
+++ b/devlink/mnlg.c
@@ -0,0 +1,327 @@
+/*
+ * mnlg.c Generic Netlink helpers for libmnl
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Jiri Pirko <jiri@mellanox.com>
+ */
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <time.h>
+#include <libmnl/libmnl.h>
+#include <linux/genetlink.h>
+
+#include "libnetlink.h"
+#include "utils.h"
+#include "mnlg.h"
+
+struct mnlg_socket {
+ struct mnl_socket *nl;
+ char *buf;
+ uint32_t id;
+ uint8_t version;
+ unsigned int seq;
+ unsigned int portid;
+};
+
+static struct nlmsghdr *__mnlg_msg_prepare(struct mnlg_socket *nlg, uint8_t cmd,
+ uint16_t flags, uint32_t id,
+ uint8_t version)
+{
+ struct nlmsghdr *nlh;
+ struct genlmsghdr *genl;
+
+ nlh = mnl_nlmsg_put_header(nlg->buf);
+ nlh->nlmsg_type = id;
+ nlh->nlmsg_flags = flags;
+ nlg->seq = time(NULL);
+ nlh->nlmsg_seq = nlg->seq;
+
+ genl = mnl_nlmsg_put_extra_header(nlh, sizeof(struct genlmsghdr));
+ genl->cmd = cmd;
+ genl->version = version;
+
+ return nlh;
+}
+
+struct nlmsghdr *mnlg_msg_prepare(struct mnlg_socket *nlg, uint8_t cmd,
+ uint16_t flags)
+{
+ return __mnlg_msg_prepare(nlg, cmd, flags, nlg->id, nlg->version);
+}
+
+int mnlg_socket_send(struct mnlg_socket *nlg, const struct nlmsghdr *nlh)
+{
+ return mnl_socket_sendto(nlg->nl, nlh, nlh->nlmsg_len);
+}
+
+static int mnlg_cb_noop(const struct nlmsghdr *nlh, void *data)
+{
+ return MNL_CB_OK;
+}
+
+static int mnlg_cb_error(const struct nlmsghdr *nlh, void *data)
+{
+ const struct nlmsgerr *err = mnl_nlmsg_get_payload(nlh);
+
+ /* Netlink subsystems returns the errno value with different signess */
+ if (err->error < 0)
+ errno = -err->error;
+ else
+ errno = err->error;
+
+ if (nl_dump_ext_ack(nlh, NULL))
+ return MNL_CB_ERROR;
+
+ return err->error == 0 ? MNL_CB_STOP : MNL_CB_ERROR;
+}
+
+static int mnlg_cb_stop(const struct nlmsghdr *nlh, void *data)
+{
+ int len = *(int *)NLMSG_DATA(nlh);
+
+ if (len < 0) {
+ errno = -len;
+ nl_dump_ext_ack_done(nlh, len);
+ return MNL_CB_ERROR;
+ }
+ return MNL_CB_STOP;
+}
+
+static mnl_cb_t mnlg_cb_array[NLMSG_MIN_TYPE] = {
+ [NLMSG_NOOP] = mnlg_cb_noop,
+ [NLMSG_ERROR] = mnlg_cb_error,
+ [NLMSG_DONE] = mnlg_cb_stop,
+ [NLMSG_OVERRUN] = mnlg_cb_noop,
+};
+
+int mnlg_socket_recv_run(struct mnlg_socket *nlg, mnl_cb_t data_cb, void *data)
+{
+ int err;
+
+ do {
+ err = mnl_socket_recvfrom(nlg->nl, nlg->buf,
+ MNL_SOCKET_BUFFER_SIZE);
+ if (err <= 0)
+ break;
+ err = mnl_cb_run2(nlg->buf, err, nlg->seq, nlg->portid,
+ data_cb, data, mnlg_cb_array,
+ ARRAY_SIZE(mnlg_cb_array));
+ } while (err > 0);
+
+ return err;
+}
+
+struct group_info {
+ bool found;
+ uint32_t id;
+ const char *name;
+};
+
+static int parse_mc_grps_cb(const struct nlattr *attr, void *data)
+{
+ const struct nlattr **tb = data;
+ int type = mnl_attr_get_type(attr);
+
+ if (mnl_attr_type_valid(attr, CTRL_ATTR_MCAST_GRP_MAX) < 0)
+ return MNL_CB_OK;
+
+ switch (type) {
+ case CTRL_ATTR_MCAST_GRP_ID:
+ if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0)
+ return MNL_CB_ERROR;
+ break;
+ case CTRL_ATTR_MCAST_GRP_NAME:
+ if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0)
+ return MNL_CB_ERROR;
+ break;
+ }
+ tb[type] = attr;
+ return MNL_CB_OK;
+}
+
+static void parse_genl_mc_grps(struct nlattr *nested,
+ struct group_info *group_info)
+{
+ struct nlattr *pos;
+ const char *name;
+
+ mnl_attr_for_each_nested(pos, nested) {
+ struct nlattr *tb[CTRL_ATTR_MCAST_GRP_MAX + 1] = {};
+
+ mnl_attr_parse_nested(pos, parse_mc_grps_cb, tb);
+ if (!tb[CTRL_ATTR_MCAST_GRP_NAME] ||
+ !tb[CTRL_ATTR_MCAST_GRP_ID])
+ continue;
+
+ name = mnl_attr_get_str(tb[CTRL_ATTR_MCAST_GRP_NAME]);
+ if (strcmp(name, group_info->name) != 0)
+ continue;
+
+ group_info->id = mnl_attr_get_u32(tb[CTRL_ATTR_MCAST_GRP_ID]);
+ group_info->found = true;
+ }
+}
+
+static int get_group_id_attr_cb(const struct nlattr *attr, void *data)
+{
+ const struct nlattr **tb = data;
+ int type = mnl_attr_get_type(attr);
+
+ if (mnl_attr_type_valid(attr, CTRL_ATTR_MAX) < 0)
+ return MNL_CB_ERROR;
+
+ if (type == CTRL_ATTR_MCAST_GROUPS &&
+ mnl_attr_validate(attr, MNL_TYPE_NESTED) < 0)
+ return MNL_CB_ERROR;
+ tb[type] = attr;
+ return MNL_CB_OK;
+}
+
+static int get_group_id_cb(const struct nlmsghdr *nlh, void *data)
+{
+ struct group_info *group_info = data;
+ struct nlattr *tb[CTRL_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), get_group_id_attr_cb, tb);
+ if (!tb[CTRL_ATTR_MCAST_GROUPS])
+ return MNL_CB_ERROR;
+ parse_genl_mc_grps(tb[CTRL_ATTR_MCAST_GROUPS], group_info);
+ return MNL_CB_OK;
+}
+
+int mnlg_socket_group_add(struct mnlg_socket *nlg, const char *group_name)
+{
+ struct nlmsghdr *nlh;
+ struct group_info group_info;
+ int err;
+
+ nlh = __mnlg_msg_prepare(nlg, CTRL_CMD_GETFAMILY,
+ NLM_F_REQUEST | NLM_F_ACK, GENL_ID_CTRL, 1);
+ mnl_attr_put_u16(nlh, CTRL_ATTR_FAMILY_ID, nlg->id);
+
+ err = mnlg_socket_send(nlg, nlh);
+ if (err < 0)
+ return err;
+
+ group_info.found = false;
+ group_info.name = group_name;
+ err = mnlg_socket_recv_run(nlg, get_group_id_cb, &group_info);
+ if (err < 0)
+ return err;
+
+ if (!group_info.found) {
+ errno = ENOENT;
+ return -1;
+ }
+
+ err = mnl_socket_setsockopt(nlg->nl, NETLINK_ADD_MEMBERSHIP,
+ &group_info.id, sizeof(group_info.id));
+ if (err < 0)
+ return err;
+
+ return 0;
+}
+
+static int get_family_id_attr_cb(const struct nlattr *attr, void *data)
+{
+ const struct nlattr **tb = data;
+ int type = mnl_attr_get_type(attr);
+
+ if (mnl_attr_type_valid(attr, CTRL_ATTR_MAX) < 0)
+ return MNL_CB_ERROR;
+
+ if (type == CTRL_ATTR_FAMILY_ID &&
+ mnl_attr_validate(attr, MNL_TYPE_U16) < 0)
+ return MNL_CB_ERROR;
+ tb[type] = attr;
+ return MNL_CB_OK;
+}
+
+static int get_family_id_cb(const struct nlmsghdr *nlh, void *data)
+{
+ uint32_t *p_id = data;
+ struct nlattr *tb[CTRL_ATTR_MAX + 1] = {};
+ struct genlmsghdr *genl = mnl_nlmsg_get_payload(nlh);
+
+ mnl_attr_parse(nlh, sizeof(*genl), get_family_id_attr_cb, tb);
+ if (!tb[CTRL_ATTR_FAMILY_ID])
+ return MNL_CB_ERROR;
+ *p_id = mnl_attr_get_u16(tb[CTRL_ATTR_FAMILY_ID]);
+ return MNL_CB_OK;
+}
+
+struct mnlg_socket *mnlg_socket_open(const char *family_name, uint8_t version)
+{
+ struct mnlg_socket *nlg;
+ struct nlmsghdr *nlh;
+ int one = 1;
+ int err;
+
+ nlg = malloc(sizeof(*nlg));
+ if (!nlg)
+ return NULL;
+
+ nlg->buf = malloc(MNL_SOCKET_BUFFER_SIZE);
+ if (!nlg->buf)
+ goto err_buf_alloc;
+
+ nlg->nl = mnl_socket_open(NETLINK_GENERIC);
+ if (!nlg->nl)
+ goto err_mnl_socket_open;
+
+ /* Older kernels may no support capped/extended ACK reporting */
+ mnl_socket_setsockopt(nlg->nl, NETLINK_CAP_ACK, &one, sizeof(one));
+ mnl_socket_setsockopt(nlg->nl, NETLINK_EXT_ACK, &one, sizeof(one));
+
+ err = mnl_socket_bind(nlg->nl, 0, MNL_SOCKET_AUTOPID);
+ if (err < 0)
+ goto err_mnl_socket_bind;
+
+ nlg->portid = mnl_socket_get_portid(nlg->nl);
+
+ nlh = __mnlg_msg_prepare(nlg, CTRL_CMD_GETFAMILY,
+ NLM_F_REQUEST | NLM_F_ACK, GENL_ID_CTRL, 1);
+ mnl_attr_put_strz(nlh, CTRL_ATTR_FAMILY_NAME, family_name);
+
+ err = mnlg_socket_send(nlg, nlh);
+ if (err < 0)
+ goto err_mnlg_socket_send;
+
+ err = mnlg_socket_recv_run(nlg, get_family_id_cb, &nlg->id);
+ if (err < 0)
+ goto err_mnlg_socket_recv_run;
+
+ nlg->version = version;
+ return nlg;
+
+err_mnlg_socket_recv_run:
+err_mnlg_socket_send:
+err_mnl_socket_bind:
+ mnl_socket_close(nlg->nl);
+err_mnl_socket_open:
+ free(nlg->buf);
+err_buf_alloc:
+ free(nlg);
+ return NULL;
+}
+
+void mnlg_socket_close(struct mnlg_socket *nlg)
+{
+ mnl_socket_close(nlg->nl);
+ free(nlg->buf);
+ free(nlg);
+}
+
+int mnlg_socket_get_fd(struct mnlg_socket *nlg)
+{
+ return mnl_socket_get_fd(nlg->nl);
+}
diff --git a/devlink/mnlg.h b/devlink/mnlg.h
new file mode 100644
index 0000000..61bc5a3
--- /dev/null
+++ b/devlink/mnlg.h
@@ -0,0 +1,28 @@
+/*
+ * mnlg.h Generic Netlink helpers for libmnl
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Jiri Pirko <jiri@mellanox.com>
+ */
+
+#ifndef _MNLG_H_
+#define _MNLG_H_
+
+#include <libmnl/libmnl.h>
+
+struct mnlg_socket;
+
+struct nlmsghdr *mnlg_msg_prepare(struct mnlg_socket *nlg, uint8_t cmd,
+ uint16_t flags);
+int mnlg_socket_send(struct mnlg_socket *nlg, const struct nlmsghdr *nlh);
+int mnlg_socket_recv_run(struct mnlg_socket *nlg, mnl_cb_t data_cb, void *data);
+int mnlg_socket_group_add(struct mnlg_socket *nlg, const char *group_name);
+struct mnlg_socket *mnlg_socket_open(const char *family_name, uint8_t version);
+void mnlg_socket_close(struct mnlg_socket *nlg);
+int mnlg_socket_get_fd(struct mnlg_socket *nlg);
+
+#endif /* _MNLG_H_ */
diff --git a/doc/actions/actions-general b/doc/actions/actions-general
new file mode 100644
index 0000000..407a514
--- /dev/null
+++ b/doc/actions/actions-general
@@ -0,0 +1,256 @@
+
+This documented is slightly dated but should give you idea of how things
+work.
+
+What is it?
+-----------
+
+An extension to the filtering/classification architecture of Linux Traffic
+Control.
+Up to 2.6.8 the only action that could be "attached" to a filter was policing.
+i.e you could say something like:
+
+-----
+tc filter add dev lo parent ffff: protocol ip prio 10 u32 match ip src \
+127.0.0.1/32 flowid 1:1 police mtu 4000 rate 1500kbit burst 90k
+-----
+
+which implies "if a packet is seen on the ingress of the lo device with
+a source IP address of 127.0.0.1/32 we give it a classification id of 1:1 and
+we execute a policing action which rate limits its bandwidth utilization
+to 1.5Mbps".
+
+The new extensions allow for more than just policing actions to be added.
+They are also fully backward compatible. If you have a kernel that doesn't
+understand them, then the effect is null i.e if you have a newer tc
+but older kernel, the actions are not installed. Likewise if you
+have a newer kernel but older tc, obviously the tc will use current
+syntax which will work fine. Of course to get the required effect you need
+both newer tc and kernel. If you are reading this you have the
+right tc ;->
+
+A side effect is that we can now get stateless firewalling to work with tc.
+Essentially this is now an alternative to iptables.
+I won't go into details of my dislike for iptables at times, but
+scalability is one of the main issues; however, if you need stateful
+classification - use netfilter (for now).
+
+This stuff works on both ingress and egress qdiscs.
+
+Features
+--------
+
+1) new additional syntax and actions enabled. Note old syntax is still valid.
+
+Essentially this is still the same syntax as tc with a new construct
+"action". The syntax is of the form:
+tc filter add <DEVICE> parent 1:0 protocol ip prio 10 <Filter description>
+flowid 1:1 action <ACTION description>*
+
+You can have as many actions as you want (within sensible reasoning).
+
+In the past the only real action was the policer; i.e you could do something
+along the lines of:
+tc filter add dev lo parent ffff: protocol ip prio 10 u32 \
+match ip src 127.0.0.1/32 flowid 1:1 \
+police mtu 4000 rate 1500kbit burst 90k
+
+Although you can still use the same syntax, now you can say:
+
+tc filter add dev lo parent 1:0 protocol ip prio 10 u32 \
+match ip src 127.0.0.1/32 flowid 1:1 \
+action police mtu 4000 rate 1500kbit burst 90k
+
+" generic Actions" (gact) at the moment are:
+{ drop, pass, reclassify, continue}
+(If you have others, no listed here give me a reason and we will add them)
++drop says to drop the packet
++pass and ok (are equivalent) says to accept it
++reclassify requests for reclassification of the packet
++continue requests for next lookup to match
+
+2)In order to take advantage of some of the targets written by the
+iptables people, a classifier can have a packet being massaged by an
+iptable target. I have only tested with mangler targets up to now.
+(infact anything that is not in the mangling table is disabled right now)
+
+In terms of hooks:
+*ingress is mapped to pre-routing hook
+*egress is mapped to post-routing hook
+I don't see much value in the other hooks, if you see it and email me good
+reasons, the addition is trivial.
+
+Example syntax for iptables targets usage becomes:
+tc filter add ..... u32 <u32 syntax> action ipt -j <iptables target syntax>
+
+example:
+tc filter add dev lo parent ffff: protocol ip prio 8 u32 \
+match ip dst 127.0.0.8/32 flowid 1:12 \
+action ipt -j mark --set-mark 2
+
+NOTE: flowid 1:12 is parsed flowid 0x1:0x12. Make sure if you want flowid
+decimal 12, then use flowid 1:c.
+
+3) A feature i call pipe
+The motivation is derived from Unix pipe mechanism but applied to packets.
+Essentially take a matching packet and pass it through
+action1 | action2 | action3 etc.
+You could do something similar to this with the tc policer and the "continue"
+operator but this rather restricts it to just the policer and requires
+multiple rules (and lookups, hence quiet inefficient);
+
+as an example -- and please note that this is just an example _not_ The
+Word Youve Been Waiting For (yes i have had problems giving examples
+which ended becoming dogma in documents and people modifying them a little
+to look clever);
+
+i selected the metering rates to be small so that i can show better how
+things work.
+
+The script below does the following:
+- an incoming packet from 10.0.0.21 is first given a firewall mark of 1.
+
+- It is then metered to make sure it does not exceed its allocated rate of
+1Kbps. If it doesn't exceed rate, this is where we terminate action execution.
+
+- If it does exceed its rate, its "color" changes to a mark of 2 and it is
+then passed through a second meter.
+
+-The second meter is shared across all flows on that device [i am surpised
+that this seems to be not a well know feature of the policer; Bert was telling
+me that someone was writing a qdisc just to do sharing across multiple devices;
+it must be the summer heat again; weve had someone doing that every year around
+summer -- the key to sharing is to use a operator "index" in your policer
+rules (example "index 20"). All your rules have to use the same index to
+share.]
+
+-If the second meter is exceeded the color of the flow changes further to 3.
+
+-We then pass the packet to another meter which is shared across all devices
+in the system. If this meter is exceeded we drop the packet.
+
+Note the mark can be used further up the system to do things like policy
+or more interesting things on the egress.
+
+------------------ cut here -------------------------------
+#
+# Add an ingress qdisc on eth0
+tc qdisc add dev eth0 ingress
+#
+#if you see an incoming packet from 10.0.0.21
+tc filter add dev eth0 parent ffff: protocol ip prio 1 \
+u32 match ip src 10.0.0.21/32 flowid 1:15 \
+#
+# first give it a mark of 1
+action ipt -j mark --set-mark 1 index 2 \
+#
+# then pass it through a policer which allows 1kbps; if the flow
+# doesn't exceed that rate, this is where we stop, if it exceeds we
+# pipe the packet to the next action
+action police rate 1kbit burst 9k pipe \
+#
+# which marks the packet fwmark as 2 and pipes
+action ipt -j mark --set-mark 2 \
+#
+# next attempt to borrow b/width from a meter
+# used across all flows incoming on eth0("index 30")
+# and if that is exceeded we pipe to the next action
+action police index 30 mtu 5000 rate 1kbit burst 10k pipe \
+# mark it as fwmark 3 if exceeded
+action ipt -j mark --set-mark 3 \
+# and then attempt to borrow from a meter used by all devices in the
+# system. Should this be exceeded, drop the packet on the floor.
+action police index 20 mtu 5000 rate 1kbit burst 90k drop
+---------------------------------
+
+Now lets see the actions installed with
+"tc filter show parent ffff: dev eth0"
+
+-------- output -----------
+jroot# tc filter show parent ffff: dev eth0
+filter protocol ip pref 1 u32
+filter protocol ip pref 1 u32 fh 800: ht divisor 1
+filter protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:15
+
+ action order 1: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x1 index 2
+
+ action order 2: police 1 action pipe rate 1Kbit burst 9Kb mtu 2Kb
+
+ action order 3: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x2 index 1
+
+ action order 4: police 30 action pipe rate 1Kbit burst 10Kb mtu 5000b
+
+ action order 5: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x3 index 3
+
+ action order 6: police 20 action drop rate 1Kbit burst 90Kb mtu 5000b
+
+ match 0a000015/ffffffff at 12
+-------------------------------
+
+Note the ordering of the actions is based on the order in which we entered
+them. In the future i will add explicit priorities.
+
+Now lets run a ping -f from 10.0.0.21 to this host; stop the ping after
+you see a few lines of dots
+
+----
+[root@jzny hadi]# ping -f 10.0.0.22
+PING 10.0.0.22 (10.0.0.22): 56 data bytes
+....................................................................................................................................................................................................................................................................................................................................................................................................................................................
+--- 10.0.0.22 ping statistics ---
+2248 packets transmitted, 1811 packets received, 19% packet loss
+round-trip min/avg/max = 0.7/9.3/20.1 ms
+-----------------------------
+
+Now lets take a look at the stats with "tc -s filter show parent ffff: dev eth0"
+
+--------------
+jroot# tc -s filter show parent ffff: dev eth0
+filter protocol ip pref 1 u32
+filter protocol ip pref 1 u32 fh 800: ht divisor 1
+filter protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1
+5
+
+ action order 1: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x1 index 2
+ Sent 188832 bytes 2248 pkts (dropped 0, overlimits 0)
+
+ action order 2: police 1 action pipe rate 1Kbit burst 9Kb mtu 2Kb
+ Sent 188832 bytes 2248 pkts (dropped 0, overlimits 2122)
+
+ action order 3: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x2 index 1
+ Sent 178248 bytes 2122 pkts (dropped 0, overlimits 0)
+
+ action order 4: police 30 action pipe rate 1Kbit burst 10Kb mtu 5000b
+ Sent 178248 bytes 2122 pkts (dropped 0, overlimits 1945)
+
+ action order 5: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x3 index 3
+ Sent 163380 bytes 1945 pkts (dropped 0, overlimits 0)
+
+ action order 6: police 20 action drop rate 1Kbit burst 90Kb mtu 5000b
+ Sent 163380 bytes 1945 pkts (dropped 0, overlimits 437)
+
+ match 0a000015/ffffffff at 12
+-------------------------------
+
+Neat, eh?
+
+
+Want to write an action module?
+------------------------------
+Its easy. Either look at the code or send me email. I will document at
+some point; will also accept documentation.
+
+TODO
+----
+
+Lotsa goodies/features coming. Requests also being accepted.
+At the moment the focus has been on getting the architecture in place.
+Expect new things in the spurious time i have to work on this
+(particularly around end of year when i have typically get time off
+from work).
diff --git a/doc/actions/gact-usage b/doc/actions/gact-usage
new file mode 100644
index 0000000..5fc3e62
--- /dev/null
+++ b/doc/actions/gact-usage
@@ -0,0 +1,78 @@
+
+gact <ACTION> [RAND] [INDEX]
+
+Where:
+ ACTION := reclassify | drop | continue | pass | ok
+ RAND := random <RANDTYPE> <ACTION> <VAL>
+ RANDTYPE := netrand | determ
+ VAL : = value not exceeding 10000
+ INDEX := index value used
+
+ACTION semantics
+- pass and ok are equivalent to accept
+- continue allows to restart classification lookup
+- drop drops packets
+- reclassify implies continue classification where we left off
+
+randomization
+--------------
+
+At the moment there are only two algorithms. One is deterministic
+and the other uses internal kernel netrand.
+
+Examples:
+
+Rules can be installed on both ingress and egress - this shows ingress
+only
+
+tc qdisc add dev eth0 ingress
+
+# example 1
+tc filter add dev eth0 parent ffff: protocol ip prio 6 u32 match ip src \
+10.0.0.9/32 flowid 1:16 action drop
+
+ping -c 20 10.0.0.9
+
+--
+filter u32
+filter u32 fh 800: ht divisor 1
+filter u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:16 (rule hit 32 success 20)
+ match 0a000009/ffffffff at 12 (success 20 )
+ action order 1: gact action drop
+ random type none pass val 0
+ index 1 ref 1 bind 1 installed 59 sec used 35 sec
+ Sent 1680 bytes 20 pkts (dropped 20, overlimits 0 )
+
+----
+
+# example 2
+#allow 1 out 10 randomly using the netrand generator
+tc filter add dev eth0 parent ffff: protocol ip prio 6 u32 match ip src \
+10.0.0.9/32 flowid 1:16 action drop random netrand ok 10
+
+ping -c 20 10.0.0.9
+
+----
+filter protocol ip pref 6 u32 filter protocol ip pref 6 u32 fh 800: ht divisor 1filter protocol ip pref 6 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:16 (rule hit 20 success 20)
+ match 0a000009/ffffffff at 12 (success 20 )
+ action order 1: gact action drop
+ random type netrand pass val 10
+ index 5 ref 1 bind 1 installed 49 sec used 25 sec
+ Sent 1680 bytes 20 pkts (dropped 16, overlimits 0 )
+
+--------
+#alternative: deterministically accept every second packet
+tc filter add dev eth0 parent ffff: protocol ip prio 6 u32 match ip src \
+10.0.0.9/32 flowid 1:16 action drop random determ ok 2
+
+ping -c 20 10.0.0.9
+
+tc -s filter show parent ffff: dev eth0
+-----
+filter protocol ip pref 6 u32 filter protocol ip pref 6 u32 fh 800: ht divisor 1filter protocol ip pref 6 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:16 (rule hit 20 success 20)
+ match 0a000009/ffffffff at 12 (success 20 )
+ action order 1: gact action drop
+ random type determ pass val 2
+ index 4 ref 1 bind 1 installed 118 sec used 82 sec
+ Sent 1680 bytes 20 pkts (dropped 10, overlimits 0 )
+-----
diff --git a/doc/actions/ifb-README b/doc/actions/ifb-README
new file mode 100644
index 0000000..5fe9171
--- /dev/null
+++ b/doc/actions/ifb-README
@@ -0,0 +1,125 @@
+
+IFB is intended to replace IMQ.
+Advantage over current IMQ; cleaner in particular in in SMP;
+with a _lot_ less code.
+
+Known IMQ/IFB USES
+------------------
+
+As far as i know the reasons listed below is why people use IMQ.
+It would be nice to know of anything else that i missed.
+
+1) qdiscs/policies that are per device as opposed to system wide.
+IFB allows for sharing.
+
+2) Allows for queueing incoming traffic for shaping instead of
+dropping. I am not aware of any study that shows policing is
+worse than shaping in achieving the end goal of rate control.
+I would be interested if anyone is experimenting.
+
+3) Very interesting use: if you are serving p2p you may want to give
+preference to your own locally originated traffic (when responses come back)
+vs someone using your system to do bittorent. So QoSing based on state
+comes in as the solution. What people did to achieve this was stick
+the IMQ somewhere prelocal hook.
+I think this is a pretty neat feature to have in Linux in general.
+(i.e not just for IMQ).
+But i won't go back to putting netfilter hooks in the device to satisfy
+this. I also don't think its worth it hacking ifb some more to be
+aware of say L3 info and play ip rule tricks to achieve this.
+--> Instead the plan is to have a conntrack related action. This action will
+selectively either query/create conntrack state on incoming packets.
+Packets could then be redirected to ifb based on what happens -> eg
+on incoming packets; if we find they are of known state we could send to
+a different queue than one which didn't have existing state. This
+all however is dependent on whatever rules the admin enters.
+
+At the moment this 3rd function does not exist yet. I have decided that
+instead of sitting on the patch for another year, to release it and then
+if there is pressure i will add this feature.
+
+An example, to provide functionality that most people use IMQ for below:
+
+--------
+export TC="/sbin/tc"
+
+$TC qdisc add dev ifb0 root handle 1: prio
+$TC qdisc add dev ifb0 parent 1:1 handle 10: sfq
+$TC qdisc add dev ifb0 parent 1:2 handle 20: tbf rate 20kbit buffer 1600 limit 3000
+$TC qdisc add dev ifb0 parent 1:3 handle 30: sfq
+$TC filter add dev ifb0 protocol ip pref 1 parent 1: handle 1 fw classid 1:1
+$TC filter add dev ifb0 protocol ip pref 2 parent 1: handle 2 fw classid 1:2
+
+ifconfig ifb0 up
+
+$TC qdisc add dev eth0 ingress
+
+# redirect all IP packets arriving in eth0 to ifb0
+# use mark 1 --> puts them onto class 1:1
+$TC filter add dev eth0 parent ffff: protocol ip prio 10 u32 \
+match u32 0 0 flowid 1:1 \
+action ipt -j MARK --set-mark 1 \
+action mirred egress redirect dev ifb0
+
+--------
+
+
+Run A Little test:
+
+from another machine ping so that you have packets going into the box:
+-----
+[root@jzny action-tests]# ping 10.22
+PING 10.22 (10.0.0.22): 56 data bytes
+64 bytes from 10.0.0.22: icmp_seq=0 ttl=64 time=2.8 ms
+64 bytes from 10.0.0.22: icmp_seq=1 ttl=64 time=0.6 ms
+64 bytes from 10.0.0.22: icmp_seq=2 ttl=64 time=0.6 ms
+
+--- 10.22 ping statistics ---
+3 packets transmitted, 3 packets received, 0% packet loss
+round-trip min/avg/max = 0.6/1.3/2.8 ms
+[root@jzny action-tests]#
+-----
+Now look at some stats:
+
+---
+[root@jmandrake]:~# $TC -s filter show parent ffff: dev eth0
+filter protocol ip pref 10 u32
+filter protocol ip pref 10 u32 fh 800: ht divisor 1
+filter protocol ip pref 10 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1
+ match 00000000/00000000 at 0
+ action order 1: tablename: mangle hook: NF_IP_PRE_ROUTING
+ target MARK set 0x1
+ index 1 ref 1 bind 1 installed 4195sec used 27sec
+ Sent 252 bytes 3 pkts (dropped 0, overlimits 0)
+
+ action order 2: mirred (Egress Redirect to device ifb0) stolen
+ index 1 ref 1 bind 1 installed 165 sec used 27 sec
+ Sent 252 bytes 3 pkts (dropped 0, overlimits 0)
+
+[root@jmandrake]:~# $TC -s qdisc
+qdisc sfq 30: dev ifb0 limit 128p quantum 1514b
+ Sent 0 bytes 0 pkts (dropped 0, overlimits 0)
+qdisc tbf 20: dev ifb0 rate 20Kbit burst 1575b lat 2147.5s
+ Sent 210 bytes 3 pkts (dropped 0, overlimits 0)
+qdisc sfq 10: dev ifb0 limit 128p quantum 1514b
+ Sent 294 bytes 3 pkts (dropped 0, overlimits 0)
+qdisc prio 1: dev ifb0 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1
+ Sent 504 bytes 6 pkts (dropped 0, overlimits 0)
+qdisc ingress ffff: dev eth0 ----------------
+ Sent 308 bytes 5 pkts (dropped 0, overlimits 0)
+
+[root@jmandrake]:~# ifconfig ifb0
+ifb0 Link encap:Ethernet HWaddr 00:00:00:00:00:00
+ inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link
+ UP BROADCAST RUNNING NOARP MTU:1500 Metric:1
+ RX packets:6 errors:0 dropped:3 overruns:0 frame:0
+ TX packets:3 errors:0 dropped:0 overruns:0 carrier:0
+ collisions:0 txqueuelen:32
+ RX bytes:504 (504.0 b) TX bytes:252 (252.0 b)
+-----
+
+You send it any packet not originating from the actions it will drop them.
+[In this case the three dropped packets were ipv6 ndisc].
+
+cheers,
+jamal
diff --git a/doc/actions/mirred-usage b/doc/actions/mirred-usage
new file mode 100644
index 0000000..482ff66
--- /dev/null
+++ b/doc/actions/mirred-usage
@@ -0,0 +1,164 @@
+
+Very funky action. I do plan to add to a few more things to it
+This is the basic stuff. Idea borrowed from the way ethernet switches
+mirror and redirect packets. The main difference with say a vannila
+ethernet switch is that you can use u32 classifier to select a
+flow to be mirrored. High end switches typically can select based
+on more than just a port (eg a 5 tuple classifier). They may also be
+capable of redirecting.
+
+Usage:
+
+mirred <DIRECTION> <ACTION> [index INDEX] <dev DEVICENAME>
+where:
+DIRECTION := <ingress | egress>
+ACTION := <mirror | redirect>
+INDEX is the specific policy instance id
+DEVICENAME is the devicename
+
+Direction:
+- Ingress is not supported at the moment. It will be in the
+future as well as mirror/redirecting to a socket.
+
+Action:
+- Mirror takes a copy of the packet and sends it to specified
+dev ("port" in ethernet switch/bridging terminology)
+- redirect
+steals the packet and redirects to specified destination dev.
+
+What NOT to do if you don't want your machine to crash:
+------------------------------------------------------
+
+Do not create loops!
+Loops are not hard to create in the egress qdiscs.
+
+Here are simple rules to follow if you don't want to get
+hurt:
+A) Do not have the same packet go to same netdevice twice
+in a single graph of policies. Your machine will just hang!
+This is design intent _not a bug_ to teach you some lessons.
+
+In the future if there are easy ways to do this in the kernel
+without affecting other packets not interested in this feature
+I will add them. At the moment that is not clear.
+
+Some examples of bad things NOT to do:
+1) redirecting eth0 to eth0
+2) eth0->eth1-> eth0
+3) eth0->lo-> eth1-> eth0
+
+B) Do not redirect from one IFB device to another.
+Remember that IFB is a very specialized case of packet redirecting
+device. Instead of redirecting it puts packets at the exact spot
+on the stack it found them from.
+Redirecting from ifbX->ifbY will actually not crash your machine but your
+packets will all be dropped (this is much simpler to detect
+and resolve and is only affecting users of ifb as opposed to the
+whole stack).
+
+In the case of A) the problem has to do with a recursive contention
+for the devices queue lock and in the second case for the transmit lock.
+
+Some examples:
+-------------
+
+1) Mirror all packets arriving on eth0 to be sent out on eth1.
+You may have a sniffer or some accounting box hooked up on eth1.
+
+---
+tc qdisc add dev eth0 ingress
+tc filter add dev eth0 parent ffff: protocol ip prio 10 u32 \
+match u32 0 0 flowid 1:2 action mirred egress mirror dev eth1
+---
+
+If you replace "mirror" with "redirect" then not a copy but rather
+the original packet is sent to eth1.
+
+2) Host A is hooked up to us on eth0
+
+# redirect all packets arriving on ingress of lo to eth0
+---
+tc qdisc add dev lo ingress
+tc filter add dev lo parent ffff: protocol ip prio 10 u32 \
+match u32 0 0 flowid 1:2 action mirred egress redirect dev eth0
+---
+
+On host A start a tcpdump on interface connecting to us.
+
+on our host ping -c 2 127.0.0.1
+
+Ping would fail since all packets are heading out eth0
+tcpudmp on host A would show them
+
+if you substitute the redirect with mirror above as in:
+tc filter add dev lo parent ffff: protocol ip prio 10 u32 \
+match u32 0 0 flowid 1:2 action mirred egress mirror dev eth0
+
+Then you should see the packets on both host A and the local
+stack (i.e ping would work).
+
+3) Even more funky example:
+
+#
+#allow 1 out 10 packets on ingress of lo to randomly make it to the
+# host A (Randomness uses the netrand generator)
+#
+---
+tc filter add dev lo parent ffff: protocol ip prio 10 u32 \
+match u32 0 0 flowid 1:2 \
+action drop random determ ok 10\
+action mirred egress mirror dev eth0
+---
+
+4)
+# for packets from 10.0.0.9 going out on eth0 (could be local
+# IP or something # we are forwarding) -
+# if exceeding a 100Kbps rate, then redirect to eth1
+#
+
+---
+tc qdisc add dev eth0 handle 1:0 root prio
+tc filter add dev eth0 parent 1:0 protocol ip prio 6 u32 \
+match ip src 10.0.0.9/32 flowid 1:16 \
+action police rate 100kbit burst 90k ok \
+action mirred egress mirror dev eth1
+---
+
+A more interesting example is when you mirror flows to a dummy device
+so you could tcpdump them (dummy by defaults drops all packets it sees).
+This is a very useful debug feature.
+
+Lets say you are policing packets from alias 192.168.200.200/32
+you don't want those to exceed 100kbps going out.
+
+---
+tc qdisc add dev eth0 handle 1:0 root prio
+tc filter add dev eth0 parent 1: protocol ip prio 10 u32 \
+match ip src 192.168.200.200/32 flowid 1:2 \
+action police rate 100kbit burst 90k drop
+---
+
+If you run tcpdump on eth0 you will see all packets going out
+with src 192.168.200.200/32 dropped or not (since tcpdump shows
+all packets being egressed).
+Extend the rule a little to see only the packets making it out.
+
+---
+tc qdisc add dev eth0 handle 1:0 root prio
+tc filter add dev eth0 parent 1: protocol ip prio 10 u32 \
+match ip src 192.168.200.200/32 flowid 1:2 \
+action police rate 10kbit burst 90k drop \
+action mirred egress mirror dev dummy0
+---
+
+Now fire tcpdump on dummy0 to see only those packets ..
+tcpdump -n -i dummy0 -x -e -t
+
+Essentially a good debugging/logging interface (sort of like
+BSDs speacialized log device does without needing one).
+
+If you replace mirror with redirect, those packets will be
+blackholed and will never make it out.
+
+cheers,
+jamal
diff --git a/etc/iproute2/bpf_pinning b/etc/iproute2/bpf_pinning
new file mode 100644
index 0000000..2b39c70
--- /dev/null
+++ b/etc/iproute2/bpf_pinning
@@ -0,0 +1,6 @@
+#
+# subpath mappings from mount point for pinning
+#
+#3 tracing
+#4 foo/bar
+#5 tc/cls1
diff --git a/etc/iproute2/ematch_map b/etc/iproute2/ematch_map
new file mode 100644
index 0000000..4d6bb2f
--- /dev/null
+++ b/etc/iproute2/ematch_map
@@ -0,0 +1,8 @@
+# lookup table for ematch kinds
+1 cmp
+2 nbyte
+3 u32
+4 meta
+7 canid
+8 ipset
+9 ipt
diff --git a/etc/iproute2/group b/etc/iproute2/group
new file mode 100644
index 0000000..6f000b2
--- /dev/null
+++ b/etc/iproute2/group
@@ -0,0 +1,2 @@
+# device group names
+0 default
diff --git a/etc/iproute2/nl_protos b/etc/iproute2/nl_protos
new file mode 100644
index 0000000..7c17cf0
--- /dev/null
+++ b/etc/iproute2/nl_protos
@@ -0,0 +1,23 @@
+# Netlink protocol names mapping
+
+0 rtnl
+1 unused
+2 usersock
+3 fw
+4 tcpdiag
+5 nflog
+6 xfrm
+7 selinux
+8 iscsi
+9 audit
+10 fiblookup
+11 connector
+12 nft
+13 ip6fw
+14 dec-rt
+15 uevent
+16 genl
+18 scsi-trans
+19 ecryptfs
+20 rdma
+21 crypto
diff --git a/etc/iproute2/rt_dsfield b/etc/iproute2/rt_dsfield
new file mode 100644
index 0000000..1426d60
--- /dev/null
+++ b/etc/iproute2/rt_dsfield
@@ -0,0 +1,26 @@
+# Differentiated field values
+# These include the DSCP and unused bits
+0x0 default
+# Newer RFC2597 values
+0x28 AF11
+0x30 AF12
+0x38 AF13
+0x48 AF21
+0x50 AF22
+0x58 AF23
+0x68 AF31
+0x70 AF32
+0x78 AF33
+0x88 AF41
+0x90 AF42
+0x98 AF43
+# Older values RFC2474
+0x20 CS1
+0x40 CS2
+0x60 CS3
+0x80 CS4
+0xA0 CS5
+0xC0 CS6
+0xE0 CS7
+# RFC 2598
+0xB8 EF
diff --git a/etc/iproute2/rt_protos b/etc/iproute2/rt_protos
new file mode 100644
index 0000000..b3a0ec8
--- /dev/null
+++ b/etc/iproute2/rt_protos
@@ -0,0 +1,23 @@
+#
+# Reserved protocols.
+#
+0 unspec
+1 redirect
+2 kernel
+3 boot
+4 static
+8 gated
+9 ra
+10 mrt
+11 zebra
+12 bird
+13 dnrouted
+14 xorp
+15 ntk
+16 dhcp
+42 babel
+186 bgp
+187 isis
+188 ospf
+189 rip
+192 eigrp
diff --git a/etc/iproute2/rt_protos.d/README b/etc/iproute2/rt_protos.d/README
new file mode 100644
index 0000000..f9c599c
--- /dev/null
+++ b/etc/iproute2/rt_protos.d/README
@@ -0,0 +1,2 @@
+Each file in this directory is an rt_protos configuration file. iproute2
+commands scan this directory processing all files that end in '.conf'.
diff --git a/etc/iproute2/rt_realms b/etc/iproute2/rt_realms
new file mode 100644
index 0000000..eedd76d
--- /dev/null
+++ b/etc/iproute2/rt_realms
@@ -0,0 +1,13 @@
+#
+# reserved values
+#
+0 cosmos
+#
+# local
+#
+#1 inr.ac
+#2 inr.ruhep
+#3 freenet
+#4 radio-msu
+#5 russia
+#6 internet
diff --git a/etc/iproute2/rt_scopes b/etc/iproute2/rt_scopes
new file mode 100644
index 0000000..8514bc1
--- /dev/null
+++ b/etc/iproute2/rt_scopes
@@ -0,0 +1,11 @@
+#
+# reserved values
+#
+0 global
+255 nowhere
+254 host
+253 link
+#
+# pseudo-reserved
+#
+200 site
diff --git a/etc/iproute2/rt_tables b/etc/iproute2/rt_tables
new file mode 100644
index 0000000..541abfd
--- /dev/null
+++ b/etc/iproute2/rt_tables
@@ -0,0 +1,11 @@
+#
+# reserved values
+#
+255 local
+254 main
+253 default
+0 unspec
+#
+# local
+#
+#1 inr.ruhep
diff --git a/etc/iproute2/rt_tables.d/README b/etc/iproute2/rt_tables.d/README
new file mode 100644
index 0000000..0920cb1
--- /dev/null
+++ b/etc/iproute2/rt_tables.d/README
@@ -0,0 +1,2 @@
+Each file in this directory is an rt_tables configuration file. iproute2
+commands scan this directory processing all files that end in '.conf'.
diff --git a/examples/bpf/README b/examples/bpf/README
new file mode 100644
index 0000000..1bbdda3
--- /dev/null
+++ b/examples/bpf/README
@@ -0,0 +1,8 @@
+eBPF toy code examples (running in kernel) to familiarize yourself
+with syntax and features:
+
+ - bpf_shared.c -> Ingress/egress map sharing example
+ - bpf_tailcall.c -> Using tail call chains
+ - bpf_cyclic.c -> Simple cycle as tail calls
+ - bpf_graft.c -> Demo on altering runtime behaviour
+ - bpf_map_in_map.c -> Using map in map example
diff --git a/examples/bpf/bpf_cyclic.c b/examples/bpf/bpf_cyclic.c
new file mode 100644
index 0000000..11d1c06
--- /dev/null
+++ b/examples/bpf/bpf_cyclic.c
@@ -0,0 +1,35 @@
+#include "../../include/bpf_api.h"
+
+/* Cyclic dependency example to test the kernel's runtime upper
+ * bound on loops. Also demonstrates on how to use direct-actions,
+ * loaded as: tc filter add [...] bpf da obj [...]
+ */
+#define JMP_MAP_ID 0xabccba
+
+struct bpf_elf_map __section_maps jmp_tc = {
+ .type = BPF_MAP_TYPE_PROG_ARRAY,
+ .id = JMP_MAP_ID,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_OBJECT_NS,
+ .max_elem = 1,
+};
+
+__section_tail(JMP_MAP_ID, 0)
+int cls_loop(struct __sk_buff *skb)
+{
+ printt("cb: %u\n", skb->cb[0]++);
+ tail_call(skb, &jmp_tc, 0);
+
+ skb->tc_classid = TC_H_MAKE(1, 42);
+ return TC_ACT_OK;
+}
+
+__section_cls_entry
+int cls_entry(struct __sk_buff *skb)
+{
+ tail_call(skb, &jmp_tc, 0);
+ return TC_ACT_SHOT;
+}
+
+BPF_LICENSE("GPL");
diff --git a/examples/bpf/bpf_graft.c b/examples/bpf/bpf_graft.c
new file mode 100644
index 0000000..07113d4
--- /dev/null
+++ b/examples/bpf/bpf_graft.c
@@ -0,0 +1,66 @@
+#include "../../include/bpf_api.h"
+
+/* This example demonstrates how classifier run-time behaviour
+ * can be altered with tail calls. We start out with an empty
+ * jmp_tc array, then add section aaa to the array slot 0, and
+ * later on atomically replace it with section bbb. Note that
+ * as shown in other examples, the tc loader can prepopulate
+ * tail called sections, here we start out with an empty one
+ * on purpose to show it can also be done this way.
+ *
+ * tc filter add dev foo parent ffff: bpf obj graft.o
+ * tc exec bpf dbg
+ * [...]
+ * Socket Thread-20229 [001] ..s. 138993.003923: : fallthrough
+ * <idle>-0 [001] ..s. 138993.202265: : fallthrough
+ * Socket Thread-20229 [001] ..s. 138994.004149: : fallthrough
+ * [...]
+ *
+ * tc exec bpf graft m:globals/jmp_tc key 0 obj graft.o sec aaa
+ * tc exec bpf dbg
+ * [...]
+ * Socket Thread-19818 [002] ..s. 139012.053587: : aaa
+ * <idle>-0 [002] ..s. 139012.172359: : aaa
+ * Socket Thread-19818 [001] ..s. 139012.173556: : aaa
+ * [...]
+ *
+ * tc exec bpf graft m:globals/jmp_tc key 0 obj graft.o sec bbb
+ * tc exec bpf dbg
+ * [...]
+ * Socket Thread-19818 [002] ..s. 139022.102967: : bbb
+ * <idle>-0 [002] ..s. 139022.155640: : bbb
+ * Socket Thread-19818 [001] ..s. 139022.156730: : bbb
+ * [...]
+ */
+
+struct bpf_elf_map __section_maps jmp_tc = {
+ .type = BPF_MAP_TYPE_PROG_ARRAY,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_GLOBAL_NS,
+ .max_elem = 1,
+};
+
+__section("aaa")
+int cls_aaa(struct __sk_buff *skb)
+{
+ printt("aaa\n");
+ return TC_H_MAKE(1, 42);
+}
+
+__section("bbb")
+int cls_bbb(struct __sk_buff *skb)
+{
+ printt("bbb\n");
+ return TC_H_MAKE(1, 43);
+}
+
+__section_cls_entry
+int cls_entry(struct __sk_buff *skb)
+{
+ tail_call(skb, &jmp_tc, 0);
+ printt("fallthrough\n");
+ return BPF_H_DEFAULT;
+}
+
+BPF_LICENSE("GPL");
diff --git a/examples/bpf/bpf_map_in_map.c b/examples/bpf/bpf_map_in_map.c
new file mode 100644
index 0000000..ff0e623
--- /dev/null
+++ b/examples/bpf/bpf_map_in_map.c
@@ -0,0 +1,56 @@
+#include "../../include/bpf_api.h"
+
+#define MAP_INNER_ID 42
+
+struct bpf_elf_map __section_maps map_inner = {
+ .type = BPF_MAP_TYPE_ARRAY,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .id = MAP_INNER_ID,
+ .inner_idx = 0,
+ .pinning = PIN_GLOBAL_NS,
+ .max_elem = 1,
+};
+
+struct bpf_elf_map __section_maps map_outer = {
+ .type = BPF_MAP_TYPE_ARRAY_OF_MAPS,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .inner_id = MAP_INNER_ID,
+ .pinning = PIN_GLOBAL_NS,
+ .max_elem = 1,
+};
+
+__section("egress")
+int emain(struct __sk_buff *skb)
+{
+ struct bpf_elf_map *map_inner;
+ int key = 0, *val;
+
+ map_inner = map_lookup_elem(&map_outer, &key);
+ if (map_inner) {
+ val = map_lookup_elem(map_inner, &key);
+ if (val)
+ lock_xadd(val, 1);
+ }
+
+ return BPF_H_DEFAULT;
+}
+
+__section("ingress")
+int imain(struct __sk_buff *skb)
+{
+ struct bpf_elf_map *map_inner;
+ int key = 0, *val;
+
+ map_inner = map_lookup_elem(&map_outer, &key);
+ if (map_inner) {
+ val = map_lookup_elem(map_inner, &key);
+ if (val)
+ printt("map val: %d\n", *val);
+ }
+
+ return BPF_H_DEFAULT;
+}
+
+BPF_LICENSE("GPL");
diff --git a/examples/bpf/bpf_shared.c b/examples/bpf/bpf_shared.c
new file mode 100644
index 0000000..21fe6f1
--- /dev/null
+++ b/examples/bpf/bpf_shared.c
@@ -0,0 +1,53 @@
+#include "../../include/bpf_api.h"
+
+/* Minimal, stand-alone toy map pinning example:
+ *
+ * clang -target bpf -O2 [...] -o bpf_shared.o -c bpf_shared.c
+ * tc filter add dev foo parent 1: bpf obj bpf_shared.o sec egress
+ * tc filter add dev foo parent ffff: bpf obj bpf_shared.o sec ingress
+ *
+ * Both classifier will share the very same map instance in this example,
+ * so map content can be accessed from ingress *and* egress side!
+ *
+ * This example has a pinning of PIN_OBJECT_NS, so it's private and
+ * thus shared among various program sections within the object.
+ *
+ * A setting of PIN_GLOBAL_NS would place it into a global namespace,
+ * so that it can be shared among different object files. A setting
+ * of PIN_NONE (= 0) means no sharing, so each tc invocation a new map
+ * instance is being created.
+ */
+
+struct bpf_elf_map __section_maps map_sh = {
+ .type = BPF_MAP_TYPE_ARRAY,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_OBJECT_NS, /* or PIN_GLOBAL_NS, or PIN_NONE */
+ .max_elem = 1,
+};
+
+__section("egress")
+int emain(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ val = map_lookup_elem(&map_sh, &key);
+ if (val)
+ lock_xadd(val, 1);
+
+ return BPF_H_DEFAULT;
+}
+
+__section("ingress")
+int imain(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ val = map_lookup_elem(&map_sh, &key);
+ if (val)
+ printt("map val: %d\n", *val);
+
+ return BPF_H_DEFAULT;
+}
+
+BPF_LICENSE("GPL");
diff --git a/examples/bpf/bpf_tailcall.c b/examples/bpf/bpf_tailcall.c
new file mode 100644
index 0000000..161eb60
--- /dev/null
+++ b/examples/bpf/bpf_tailcall.c
@@ -0,0 +1,117 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#include "../../include/bpf_api.h"
+
+#define ENTRY_INIT 3
+#define ENTRY_0 0
+#define ENTRY_1 1
+#define MAX_JMP_SIZE 2
+
+#define FOO 42
+#define BAR 43
+
+/* This example doesn't really do anything useful, but it's purpose is to
+ * demonstrate eBPF tail calls on a very simple example.
+ *
+ * cls_entry() is our classifier entry point, from there we jump based on
+ * skb->hash into cls_case1() or cls_case2(). They are both part of the
+ * program array jmp_tc. Indicated via __section_tail(), the tc loader
+ * populates the program arrays with the loaded file descriptors already.
+ *
+ * To demonstrate nested jumps, cls_case2() jumps within the same jmp_tc
+ * array to cls_case1(). And whenever we arrive at cls_case1(), we jump
+ * into cls_exit(), part of the jump array jmp_ex.
+ *
+ * Also, to show it's possible, all programs share map_sh and dump the value
+ * that the entry point incremented. The sections that are loaded into a
+ * program array can be atomically replaced during run-time, e.g. to change
+ * classifier behaviour.
+ */
+
+struct bpf_elf_map __section_maps jmp_tc = {
+ .type = BPF_MAP_TYPE_PROG_ARRAY,
+ .id = FOO,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_OBJECT_NS,
+ .max_elem = MAX_JMP_SIZE,
+};
+
+struct bpf_elf_map __section_maps jmp_ex = {
+ .type = BPF_MAP_TYPE_PROG_ARRAY,
+ .id = BAR,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_OBJECT_NS,
+ .max_elem = 1,
+};
+
+struct bpf_elf_map __section_maps map_sh = {
+ .type = BPF_MAP_TYPE_ARRAY,
+ .size_key = sizeof(uint32_t),
+ .size_value = sizeof(uint32_t),
+ .pinning = PIN_OBJECT_NS,
+ .max_elem = 1,
+};
+
+__section_tail(FOO, ENTRY_0)
+int cls_case1(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ val = map_lookup_elem(&map_sh, &key);
+ if (val)
+ printt("case1: map-val: %d from:%u\n", *val, skb->cb[0]);
+
+ skb->cb[0] = ENTRY_0;
+ tail_call(skb, &jmp_ex, ENTRY_0);
+
+ return BPF_H_DEFAULT;
+}
+
+__section_tail(FOO, ENTRY_1)
+int cls_case2(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ val = map_lookup_elem(&map_sh, &key);
+ if (val)
+ printt("case2: map-val: %d from:%u\n", *val, skb->cb[0]);
+
+ skb->cb[0] = ENTRY_1;
+ tail_call(skb, &jmp_tc, ENTRY_0);
+
+ return BPF_H_DEFAULT;
+}
+
+__section_tail(BAR, ENTRY_0)
+int cls_exit(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ val = map_lookup_elem(&map_sh, &key);
+ if (val)
+ printt("exit: map-val: %d from:%u\n", *val, skb->cb[0]);
+
+ /* Termination point. */
+ return BPF_H_DEFAULT;
+}
+
+__section_cls_entry
+int cls_entry(struct __sk_buff *skb)
+{
+ int key = 0, *val;
+
+ /* For transferring state, we can use skb->cb[0] ... skb->cb[4]. */
+ val = map_lookup_elem(&map_sh, &key);
+ if (val) {
+ lock_xadd(val, 1);
+
+ skb->cb[0] = ENTRY_INIT;
+ tail_call(skb, &jmp_tc, skb->hash & (MAX_JMP_SIZE - 1));
+ }
+
+ printt("fallthrough\n");
+ return BPF_H_DEFAULT;
+}
+
+BPF_LICENSE("GPL");
diff --git a/genl/.gitignore b/genl/.gitignore
new file mode 100644
index 0000000..383ef04
--- /dev/null
+++ b/genl/.gitignore
@@ -0,0 +1 @@
+genl
diff --git a/genl/Makefile b/genl/Makefile
new file mode 100644
index 0000000..2b7a45b
--- /dev/null
+++ b/genl/Makefile
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: GPL-2.0
+GENLOBJ=genl.o
+
+include ../config.mk
+SHARED_LIBS ?= y
+
+CFLAGS += -fno-strict-aliasing
+
+GENLMODULES :=
+GENLMODULES += ctrl.o
+
+GENLOBJ += $(GENLMODULES)
+
+GENLLIB :=
+
+ifeq ($(SHARED_LIBS),y)
+LDFLAGS += -Wl,-export-dynamic
+LDLIBS += -lm -ldl
+endif
+
+all: genl
+
+genl: $(GENLOBJ) $(LIBNETLINK) $(LIBUTIL) $(GENLLIB)
+ $(QUIET_LINK)$(CC) $^ $(LDFLAGS) $(LDLIBS) -o $@
+
+install: all
+ install -m 0755 genl $(DESTDIR)$(SBINDIR)
+
+clean:
+ rm -f $(GENLOBJ) $(GENLLIB) genl
+
+ifneq ($(SHARED_LIBS),y)
+
+genl: static-syms.o
+static-syms.o: static-syms.h
+static-syms.h: $(wildcard *.c)
+ files="$^" ; \
+ for s in `grep -B 3 '\<dlsym' $$files | sed -n '/snprintf/{s:.*"\([^"]*\)".*:\1:;s:%s::;p}'` ; do \
+ sed -n '/'$$s'[^ ]* =/{s:.* \([^ ]*'$$s'[^ ]*\) .*:extern char \1[] __attribute__((weak)); if (!strcmp(sym, "\1")) return \1;:;p}' $$files ; \
+ done > $@
+
+endif
diff --git a/genl/ctrl.c b/genl/ctrl.c
new file mode 100644
index 0000000..0fb464b
--- /dev/null
+++ b/genl/ctrl.c
@@ -0,0 +1,340 @@
+/*
+ * ctrl.c generic netlink controller
+ *
+ * This program is free software; you can distribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: J Hadi Salim (hadi@cyberus.ca)
+ * Johannes Berg (johannes@sipsolutions.net)
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <string.h>
+
+#include "utils.h"
+#include "genl_utils.h"
+
+#define GENL_MAX_FAM_OPS 256
+#define GENL_MAX_FAM_GRPS 256
+
+static int usage(void)
+{
+ fprintf(stderr,"Usage: ctrl <CMD>\n" \
+ "CMD := get <PARMS> | list | monitor\n" \
+ "PARMS := name <name> | id <id>\n" \
+ "Examples:\n" \
+ "\tctrl ls\n" \
+ "\tctrl monitor\n" \
+ "\tctrl get name foobar\n" \
+ "\tctrl get id 0xF\n");
+ return -1;
+}
+
+static void print_ctrl_cmd_flags(FILE *fp, __u32 fl)
+{
+ fprintf(fp, "\n\t\tCapabilities (0x%x):\n ", fl);
+ if (!fl) {
+ fprintf(fp, "\n");
+ return;
+ }
+ fprintf(fp, "\t\t ");
+
+ if (fl & GENL_ADMIN_PERM)
+ fprintf(fp, " requires admin permission;");
+ if (fl & GENL_CMD_CAP_DO)
+ fprintf(fp, " can doit;");
+ if (fl & GENL_CMD_CAP_DUMP)
+ fprintf(fp, " can dumpit;");
+ if (fl & GENL_CMD_CAP_HASPOL)
+ fprintf(fp, " has policy");
+
+ fprintf(fp, "\n");
+}
+
+static int print_ctrl_cmds(FILE *fp, struct rtattr *arg, __u32 ctrl_ver)
+{
+ struct rtattr *tb[CTRL_ATTR_OP_MAX + 1];
+
+ if (arg == NULL)
+ return -1;
+
+ parse_rtattr_nested(tb, CTRL_ATTR_OP_MAX, arg);
+ if (tb[CTRL_ATTR_OP_ID]) {
+ __u32 *id = RTA_DATA(tb[CTRL_ATTR_OP_ID]);
+ fprintf(fp, " ID-0x%x ",*id);
+ }
+ /* we are only gonna do this for newer version of the controller */
+ if (tb[CTRL_ATTR_OP_FLAGS] && ctrl_ver >= 0x2) {
+ __u32 *fl = RTA_DATA(tb[CTRL_ATTR_OP_FLAGS]);
+ print_ctrl_cmd_flags(fp, *fl);
+ }
+ return 0;
+
+}
+
+static int print_ctrl_grp(FILE *fp, struct rtattr *arg, __u32 ctrl_ver)
+{
+ struct rtattr *tb[CTRL_ATTR_MCAST_GRP_MAX + 1];
+
+ if (arg == NULL)
+ return -1;
+
+ parse_rtattr_nested(tb, CTRL_ATTR_MCAST_GRP_MAX, arg);
+ if (tb[2]) {
+ __u32 *id = RTA_DATA(tb[CTRL_ATTR_MCAST_GRP_ID]);
+ fprintf(fp, " ID-0x%x ",*id);
+ }
+ if (tb[1]) {
+ char *name = RTA_DATA(tb[CTRL_ATTR_MCAST_GRP_NAME]);
+ fprintf(fp, " name: %s ", name);
+ }
+ return 0;
+
+}
+
+/*
+ * The controller sends one nlmsg per family
+*/
+static int print_ctrl(struct rtnl_ctrl_data *ctrl,
+ struct nlmsghdr *n, void *arg)
+{
+ struct rtattr *tb[CTRL_ATTR_MAX + 1];
+ struct genlmsghdr *ghdr = NLMSG_DATA(n);
+ int len = n->nlmsg_len;
+ struct rtattr *attrs;
+ FILE *fp = (FILE *) arg;
+ __u32 ctrl_v = 0x1;
+
+ if (n->nlmsg_type != GENL_ID_CTRL) {
+ fprintf(stderr, "Not a controller message, nlmsg_len=%d "
+ "nlmsg_type=0x%x\n", n->nlmsg_len, n->nlmsg_type);
+ return 0;
+ }
+
+ if (ghdr->cmd != CTRL_CMD_GETFAMILY &&
+ ghdr->cmd != CTRL_CMD_DELFAMILY &&
+ ghdr->cmd != CTRL_CMD_NEWFAMILY &&
+ ghdr->cmd != CTRL_CMD_NEWMCAST_GRP &&
+ ghdr->cmd != CTRL_CMD_DELMCAST_GRP) {
+ fprintf(stderr, "Unknown controller command %d\n", ghdr->cmd);
+ return 0;
+ }
+
+ len -= NLMSG_LENGTH(GENL_HDRLEN);
+
+ if (len < 0) {
+ fprintf(stderr, "wrong controller message len %d\n", len);
+ return -1;
+ }
+
+ attrs = (struct rtattr *) ((char *) ghdr + GENL_HDRLEN);
+ parse_rtattr(tb, CTRL_ATTR_MAX, attrs, len);
+
+ if (tb[CTRL_ATTR_FAMILY_NAME]) {
+ char *name = RTA_DATA(tb[CTRL_ATTR_FAMILY_NAME]);
+ fprintf(fp, "\nName: %s\n",name);
+ }
+ if (tb[CTRL_ATTR_FAMILY_ID]) {
+ __u16 *id = RTA_DATA(tb[CTRL_ATTR_FAMILY_ID]);
+ fprintf(fp, "\tID: 0x%x ",*id);
+ }
+ if (tb[CTRL_ATTR_VERSION]) {
+ __u32 *v = RTA_DATA(tb[CTRL_ATTR_VERSION]);
+ fprintf(fp, " Version: 0x%x ",*v);
+ ctrl_v = *v;
+ }
+ if (tb[CTRL_ATTR_HDRSIZE]) {
+ __u32 *h = RTA_DATA(tb[CTRL_ATTR_HDRSIZE]);
+ fprintf(fp, " header size: %d ",*h);
+ }
+ if (tb[CTRL_ATTR_MAXATTR]) {
+ __u32 *ma = RTA_DATA(tb[CTRL_ATTR_MAXATTR]);
+ fprintf(fp, " max attribs: %d ",*ma);
+ }
+ /* end of family definitions .. */
+ fprintf(fp,"\n");
+ if (tb[CTRL_ATTR_OPS]) {
+ struct rtattr *tb2[GENL_MAX_FAM_OPS];
+ int i=0;
+ parse_rtattr_nested(tb2, GENL_MAX_FAM_OPS, tb[CTRL_ATTR_OPS]);
+ fprintf(fp, "\tcommands supported: \n");
+ for (i = 0; i < GENL_MAX_FAM_OPS; i++) {
+ if (tb2[i]) {
+ fprintf(fp, "\t\t#%d: ", i);
+ if (0 > print_ctrl_cmds(fp, tb2[i], ctrl_v)) {
+ fprintf(fp, "Error printing command\n");
+ }
+ /* for next command */
+ fprintf(fp,"\n");
+ }
+ }
+
+ /* end of family::cmds definitions .. */
+ fprintf(fp,"\n");
+ }
+
+ if (tb[CTRL_ATTR_MCAST_GROUPS]) {
+ struct rtattr *tb2[GENL_MAX_FAM_GRPS + 1];
+ int i;
+
+ parse_rtattr_nested(tb2, GENL_MAX_FAM_GRPS,
+ tb[CTRL_ATTR_MCAST_GROUPS]);
+ fprintf(fp, "\tmulticast groups:\n");
+
+ for (i = 0; i < GENL_MAX_FAM_GRPS; i++) {
+ if (tb2[i]) {
+ fprintf(fp, "\t\t#%d: ", i);
+ if (0 > print_ctrl_grp(fp, tb2[i], ctrl_v))
+ fprintf(fp, "Error printing group\n");
+ /* for next group */
+ fprintf(fp,"\n");
+ }
+ }
+
+ /* end of family::groups definitions .. */
+ fprintf(fp,"\n");
+ }
+
+ fflush(fp);
+ return 0;
+}
+
+static int print_ctrl2(struct nlmsghdr *n, void *arg)
+{
+ return print_ctrl(NULL, n, arg);
+}
+
+static int ctrl_list(int cmd, int argc, char **argv)
+{
+ struct rtnl_handle rth;
+ int ret = -1;
+ char d[GENL_NAMSIZ];
+ struct {
+ struct nlmsghdr n;
+ struct genlmsghdr g;
+ char buf[4096];
+ } req = {
+ .n.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN),
+ .n.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK,
+ .n.nlmsg_type = GENL_ID_CTRL,
+ .g.cmd = CTRL_CMD_GETFAMILY,
+ };
+ struct nlmsghdr *nlh = &req.n;
+ struct nlmsghdr *answer = NULL;
+
+ if (rtnl_open_byproto(&rth, 0, NETLINK_GENERIC) < 0) {
+ fprintf(stderr, "Cannot open generic netlink socket\n");
+ exit(1);
+ }
+
+ if (cmd == CTRL_CMD_GETFAMILY) {
+ if (argc != 2) {
+ fprintf(stderr, "Wrong number of params\n");
+ return -1;
+ }
+
+ if (matches(*argv, "name") == 0) {
+ NEXT_ARG();
+ strlcpy(d, *argv, sizeof(d));
+ addattr_l(nlh, 128, CTRL_ATTR_FAMILY_NAME,
+ d, strlen(d) + 1);
+ } else if (matches(*argv, "id") == 0) {
+ __u16 id;
+ NEXT_ARG();
+ if (get_u16(&id, *argv, 0)) {
+ fprintf(stderr, "Illegal \"id\"\n");
+ goto ctrl_done;
+ }
+
+ addattr_l(nlh, 128, CTRL_ATTR_FAMILY_ID, &id, 2);
+
+ } else {
+ fprintf(stderr, "Wrong params\n");
+ goto ctrl_done;
+ }
+
+ if (rtnl_talk(&rth, nlh, &answer) < 0) {
+ fprintf(stderr, "Error talking to the kernel\n");
+ goto ctrl_done;
+ }
+
+ if (print_ctrl2(answer, (void *) stdout) < 0) {
+ fprintf(stderr, "Dump terminated\n");
+ goto ctrl_done;
+ }
+
+ }
+
+ if (cmd == CTRL_CMD_UNSPEC) {
+ nlh->nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
+ nlh->nlmsg_seq = rth.dump = ++rth.seq;
+
+ if (rtnl_send(&rth, nlh, nlh->nlmsg_len) < 0) {
+ perror("Failed to send dump request\n");
+ goto ctrl_done;
+ }
+
+ rtnl_dump_filter(&rth, print_ctrl2, stdout);
+
+ }
+
+ ret = 0;
+ctrl_done:
+ free(answer);
+ rtnl_close(&rth);
+ return ret;
+}
+
+static int ctrl_listen(int argc, char **argv)
+{
+ struct rtnl_handle rth;
+
+ if (rtnl_open_byproto(&rth, nl_mgrp(GENL_ID_CTRL), NETLINK_GENERIC) < 0) {
+ fprintf(stderr, "Canot open generic netlink socket\n");
+ return -1;
+ }
+
+ if (rtnl_listen(&rth, print_ctrl, (void *) stdout) < 0)
+ return -1;
+
+ return 0;
+}
+
+static int parse_ctrl(struct genl_util *a, int argc, char **argv)
+{
+ argv++;
+ if (--argc <= 0) {
+ fprintf(stderr, "wrong controller params\n");
+ return -1;
+ }
+
+ if (matches(*argv, "monitor") == 0)
+ return ctrl_listen(argc-1, argv+1);
+ if (matches(*argv, "get") == 0)
+ return ctrl_list(CTRL_CMD_GETFAMILY, argc-1, argv+1);
+ if (matches(*argv, "list") == 0 ||
+ matches(*argv, "show") == 0 ||
+ matches(*argv, "lst") == 0)
+ return ctrl_list(CTRL_CMD_UNSPEC, argc-1, argv+1);
+ if (matches(*argv, "help") == 0)
+ return usage();
+
+ fprintf(stderr, "ctrl command \"%s\" is unknown, try \"ctrl help\".\n",
+ *argv);
+
+ return -1;
+}
+
+struct genl_util ctrl_genl_util = {
+ .name = "ctrl",
+ .parse_genlopt = parse_ctrl,
+ .print_genlopt = print_ctrl2,
+};
diff --git a/genl/genl.c b/genl/genl.c
new file mode 100644
index 0000000..aba3c13
--- /dev/null
+++ b/genl/genl.c
@@ -0,0 +1,149 @@
+/*
+ * genl.c "genl" utility frontend.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Jamal Hadi Salim
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <dlfcn.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <errno.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h> /* until we put our own header */
+#include "SNAPSHOT.h"
+#include "utils.h"
+#include "genl_utils.h"
+
+int show_stats;
+int show_details;
+int show_raw;
+
+static void *BODY;
+static struct genl_util *genl_list;
+
+
+static int print_nofopt(struct nlmsghdr *n, void *arg)
+{
+ fprintf((FILE *) arg, "unknown genl type ..\n");
+ return 0;
+}
+
+static int parse_nofopt(struct genl_util *f, int argc, char **argv)
+{
+ if (argc) {
+ fprintf(stderr,
+ "Unknown genl \"%s\", hence option \"%s\" is unparsable\n",
+ f->name, *argv);
+ return -1;
+ }
+
+ return 0;
+}
+
+static struct genl_util *get_genl_kind(const char *str)
+{
+ void *dlh;
+ char buf[256];
+ struct genl_util *f;
+
+ for (f = genl_list; f; f = f->next)
+ if (strcmp(f->name, str) == 0)
+ return f;
+
+ snprintf(buf, sizeof(buf), "%s.so", str);
+ dlh = dlopen(buf, RTLD_LAZY);
+ if (dlh == NULL) {
+ dlh = BODY;
+ if (dlh == NULL) {
+ dlh = BODY = dlopen(NULL, RTLD_LAZY);
+ if (dlh == NULL)
+ goto noexist;
+ }
+ }
+
+ snprintf(buf, sizeof(buf), "%s_genl_util", str);
+
+ f = dlsym(dlh, buf);
+ if (f == NULL)
+ goto noexist;
+reg:
+ f->next = genl_list;
+ genl_list = f;
+ return f;
+
+noexist:
+ f = calloc(1, sizeof(*f));
+ if (f) {
+ strncpy(f->name, str, 15);
+ f->parse_genlopt = parse_nofopt;
+ f->print_genlopt = print_nofopt;
+ goto reg;
+ }
+ return f;
+}
+
+static void usage(void) __attribute__((noreturn));
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: genl [ OPTIONS ] OBJECT [help] }\n"
+ "where OBJECT := { ctrl etc }\n"
+ " OPTIONS := { -s[tatistics] | -d[etails] | -r[aw] | -V[ersion] | -h[elp] }\n");
+ exit(-1);
+}
+
+int main(int argc, char **argv)
+{
+ while (argc > 1) {
+ if (argv[1][0] != '-')
+ break;
+ if (matches(argv[1], "-stats") == 0 ||
+ matches(argv[1], "-statistics") == 0) {
+ ++show_stats;
+ } else if (matches(argv[1], "-details") == 0) {
+ ++show_details;
+ } else if (matches(argv[1], "-raw") == 0) {
+ ++show_raw;
+ } else if (matches(argv[1], "-Version") == 0) {
+ printf("genl utility, iproute2-ss%s\n", SNAPSHOT);
+ exit(0);
+ } else if (matches(argv[1], "-help") == 0) {
+ usage();
+ } else {
+ fprintf(stderr,
+ "Option \"%s\" is unknown, try \"genl -help\".\n",
+ argv[1]);
+ exit(-1);
+ }
+ argc--; argv++;
+ }
+
+ if (argc > 1) {
+ struct genl_util *a;
+ int ret;
+
+ a = get_genl_kind(argv[1]);
+ if (!a) {
+ fprintf(stderr, "bad genl %s\n", argv[1]);
+ exit(-1);
+ }
+
+ ret = a->parse_genlopt(a, argc-1, argv+1);
+ return ret;
+ }
+
+ usage();
+}
diff --git a/genl/genl_utils.h b/genl/genl_utils.h
new file mode 100644
index 0000000..a8d433a
--- /dev/null
+++ b/genl/genl_utils.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _TC_UTIL_H_
+#define _TC_UTIL_H_ 1
+
+#include "utils.h"
+#include "linux/genetlink.h"
+
+struct genl_util
+{
+ struct genl_util *next;
+ char name[16];
+ int (*parse_genlopt)(struct genl_util *fu, int argc, char **argv);
+ int (*print_genlopt)(struct nlmsghdr *n, void *arg);
+};
+
+#endif
diff --git a/genl/static-syms.c b/genl/static-syms.c
new file mode 100644
index 0000000..47c4092
--- /dev/null
+++ b/genl/static-syms.c
@@ -0,0 +1,15 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * This file creates a dummy version of dynamic loading
+ * for environments where dynamic linking
+ * is not used or available.
+ */
+
+#include <string.h>
+#include "dlfcn.h"
+
+void *_dlsym(const char *sym)
+{
+#include "static-syms.h"
+ return NULL;
+}
diff --git a/include/SNAPSHOT.h b/include/SNAPSHOT.h
new file mode 100644
index 0000000..b98ad50
--- /dev/null
+++ b/include/SNAPSHOT.h
@@ -0,0 +1 @@
+static const char SNAPSHOT[] = "191125";
diff --git a/include/bpf_api.h b/include/bpf_api.h
new file mode 100644
index 0000000..89d3488
--- /dev/null
+++ b/include/bpf_api.h
@@ -0,0 +1,262 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __BPF_API__
+#define __BPF_API__
+
+/* Note:
+ *
+ * This file can be included into eBPF kernel programs. It contains
+ * a couple of useful helper functions, map/section ABI (bpf_elf.h),
+ * misc macros and some eBPF specific LLVM built-ins.
+ */
+
+#include <stdint.h>
+
+#include <linux/pkt_cls.h>
+#include <linux/bpf.h>
+#include <linux/filter.h>
+
+#include <asm/byteorder.h>
+
+#include "bpf_elf.h"
+
+/** Misc macros. */
+
+#ifndef __stringify
+# define __stringify(X) #X
+#endif
+
+#ifndef __maybe_unused
+# define __maybe_unused __attribute__((__unused__))
+#endif
+
+#ifndef offsetof
+# define offsetof(TYPE, MEMBER) __builtin_offsetof(TYPE, MEMBER)
+#endif
+
+#ifndef likely
+# define likely(X) __builtin_expect(!!(X), 1)
+#endif
+
+#ifndef unlikely
+# define unlikely(X) __builtin_expect(!!(X), 0)
+#endif
+
+#ifndef htons
+# define htons(X) __constant_htons((X))
+#endif
+
+#ifndef ntohs
+# define ntohs(X) __constant_ntohs((X))
+#endif
+
+#ifndef htonl
+# define htonl(X) __constant_htonl((X))
+#endif
+
+#ifndef ntohl
+# define ntohl(X) __constant_ntohl((X))
+#endif
+
+#ifndef __inline__
+# define __inline__ __attribute__((always_inline))
+#endif
+
+/** Section helper macros. */
+
+#ifndef __section
+# define __section(NAME) \
+ __attribute__((section(NAME), used))
+#endif
+
+#ifndef __section_tail
+# define __section_tail(ID, KEY) \
+ __section(__stringify(ID) "/" __stringify(KEY))
+#endif
+
+#ifndef __section_xdp_entry
+# define __section_xdp_entry \
+ __section(ELF_SECTION_PROG)
+#endif
+
+#ifndef __section_cls_entry
+# define __section_cls_entry \
+ __section(ELF_SECTION_CLASSIFIER)
+#endif
+
+#ifndef __section_act_entry
+# define __section_act_entry \
+ __section(ELF_SECTION_ACTION)
+#endif
+
+#ifndef __section_lwt_entry
+# define __section_lwt_entry \
+ __section(ELF_SECTION_PROG)
+#endif
+
+#ifndef __section_license
+# define __section_license \
+ __section(ELF_SECTION_LICENSE)
+#endif
+
+#ifndef __section_maps
+# define __section_maps \
+ __section(ELF_SECTION_MAPS)
+#endif
+
+/** Declaration helper macros. */
+
+#ifndef BPF_LICENSE
+# define BPF_LICENSE(NAME) \
+ char ____license[] __section_license = NAME
+#endif
+
+/** Classifier helper */
+
+#ifndef BPF_H_DEFAULT
+# define BPF_H_DEFAULT -1
+#endif
+
+/** BPF helper functions for tc. Individual flags are in linux/bpf.h */
+
+#ifndef __BPF_FUNC
+# define __BPF_FUNC(NAME, ...) \
+ (* NAME)(__VA_ARGS__) __maybe_unused
+#endif
+
+#ifndef BPF_FUNC
+# define BPF_FUNC(NAME, ...) \
+ __BPF_FUNC(NAME, __VA_ARGS__) = (void *) BPF_FUNC_##NAME
+#endif
+
+/* Map access/manipulation */
+static void *BPF_FUNC(map_lookup_elem, void *map, const void *key);
+static int BPF_FUNC(map_update_elem, void *map, const void *key,
+ const void *value, uint32_t flags);
+static int BPF_FUNC(map_delete_elem, void *map, const void *key);
+
+/* Time access */
+static uint64_t BPF_FUNC(ktime_get_ns);
+
+/* Debugging */
+
+/* FIXME: __attribute__ ((format(printf, 1, 3))) not possible unless
+ * llvm bug https://llvm.org/bugs/show_bug.cgi?id=26243 gets resolved.
+ * It would require ____fmt to be made const, which generates a reloc
+ * entry (non-map).
+ */
+static void BPF_FUNC(trace_printk, const char *fmt, int fmt_size, ...);
+
+#ifndef printt
+# define printt(fmt, ...) \
+ ({ \
+ char ____fmt[] = fmt; \
+ trace_printk(____fmt, sizeof(____fmt), ##__VA_ARGS__); \
+ })
+#endif
+
+/* Random numbers */
+static uint32_t BPF_FUNC(get_prandom_u32);
+
+/* Tail calls */
+static void BPF_FUNC(tail_call, struct __sk_buff *skb, void *map,
+ uint32_t index);
+
+/* System helpers */
+static uint32_t BPF_FUNC(get_smp_processor_id);
+static uint32_t BPF_FUNC(get_numa_node_id);
+
+/* Packet misc meta data */
+static uint32_t BPF_FUNC(get_cgroup_classid, struct __sk_buff *skb);
+static int BPF_FUNC(skb_under_cgroup, void *map, uint32_t index);
+
+static uint32_t BPF_FUNC(get_route_realm, struct __sk_buff *skb);
+static uint32_t BPF_FUNC(get_hash_recalc, struct __sk_buff *skb);
+static uint32_t BPF_FUNC(set_hash_invalid, struct __sk_buff *skb);
+
+/* Packet redirection */
+static int BPF_FUNC(redirect, int ifindex, uint32_t flags);
+static int BPF_FUNC(clone_redirect, struct __sk_buff *skb, int ifindex,
+ uint32_t flags);
+
+/* Packet manipulation */
+static int BPF_FUNC(skb_load_bytes, struct __sk_buff *skb, uint32_t off,
+ void *to, uint32_t len);
+static int BPF_FUNC(skb_store_bytes, struct __sk_buff *skb, uint32_t off,
+ const void *from, uint32_t len, uint32_t flags);
+
+static int BPF_FUNC(l3_csum_replace, struct __sk_buff *skb, uint32_t off,
+ uint32_t from, uint32_t to, uint32_t flags);
+static int BPF_FUNC(l4_csum_replace, struct __sk_buff *skb, uint32_t off,
+ uint32_t from, uint32_t to, uint32_t flags);
+static int BPF_FUNC(csum_diff, const void *from, uint32_t from_size,
+ const void *to, uint32_t to_size, uint32_t seed);
+static int BPF_FUNC(csum_update, struct __sk_buff *skb, uint32_t wsum);
+
+static int BPF_FUNC(skb_change_type, struct __sk_buff *skb, uint32_t type);
+static int BPF_FUNC(skb_change_proto, struct __sk_buff *skb, uint32_t proto,
+ uint32_t flags);
+static int BPF_FUNC(skb_change_tail, struct __sk_buff *skb, uint32_t nlen,
+ uint32_t flags);
+
+static int BPF_FUNC(skb_pull_data, struct __sk_buff *skb, uint32_t len);
+
+/* Event notification */
+static int __BPF_FUNC(skb_event_output, struct __sk_buff *skb, void *map,
+ uint64_t index, const void *data, uint32_t size) =
+ (void *) BPF_FUNC_perf_event_output;
+
+/* Packet vlan encap/decap */
+static int BPF_FUNC(skb_vlan_push, struct __sk_buff *skb, uint16_t proto,
+ uint16_t vlan_tci);
+static int BPF_FUNC(skb_vlan_pop, struct __sk_buff *skb);
+
+/* Packet tunnel encap/decap */
+static int BPF_FUNC(skb_get_tunnel_key, struct __sk_buff *skb,
+ struct bpf_tunnel_key *to, uint32_t size, uint32_t flags);
+static int BPF_FUNC(skb_set_tunnel_key, struct __sk_buff *skb,
+ const struct bpf_tunnel_key *from, uint32_t size,
+ uint32_t flags);
+
+static int BPF_FUNC(skb_get_tunnel_opt, struct __sk_buff *skb,
+ void *to, uint32_t size);
+static int BPF_FUNC(skb_set_tunnel_opt, struct __sk_buff *skb,
+ const void *from, uint32_t size);
+
+/** LLVM built-ins, mem*() routines work for constant size */
+
+#ifndef lock_xadd
+# define lock_xadd(ptr, val) ((void) __sync_fetch_and_add(ptr, val))
+#endif
+
+#ifndef memset
+# define memset(s, c, n) __builtin_memset((s), (c), (n))
+#endif
+
+#ifndef memcpy
+# define memcpy(d, s, n) __builtin_memcpy((d), (s), (n))
+#endif
+
+#ifndef memmove
+# define memmove(d, s, n) __builtin_memmove((d), (s), (n))
+#endif
+
+/* FIXME: __builtin_memcmp() is not yet fully useable unless llvm bug
+ * https://llvm.org/bugs/show_bug.cgi?id=26218 gets resolved. Also
+ * this one would generate a reloc entry (non-map), otherwise.
+ */
+#if 0
+#ifndef memcmp
+# define memcmp(a, b, n) __builtin_memcmp((a), (b), (n))
+#endif
+#endif
+
+unsigned long long load_byte(void *skb, unsigned long long off)
+ asm ("llvm.bpf.load.byte");
+
+unsigned long long load_half(void *skb, unsigned long long off)
+ asm ("llvm.bpf.load.half");
+
+unsigned long long load_word(void *skb, unsigned long long off)
+ asm ("llvm.bpf.load.word");
+
+#endif /* __BPF_API__ */
diff --git a/include/bpf_elf.h b/include/bpf_elf.h
new file mode 100644
index 0000000..84e8ae0
--- /dev/null
+++ b/include/bpf_elf.h
@@ -0,0 +1,53 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __BPF_ELF__
+#define __BPF_ELF__
+
+#include <asm/types.h>
+
+/* Note:
+ *
+ * Below ELF section names and bpf_elf_map structure definition
+ * are not (!) kernel ABI. It's rather a "contract" between the
+ * application and the BPF loader in tc. For compatibility, the
+ * section names should stay as-is. Introduction of aliases, if
+ * needed, are a possibility, though.
+ */
+
+/* ELF section names, etc */
+#define ELF_SECTION_LICENSE "license"
+#define ELF_SECTION_MAPS "maps"
+#define ELF_SECTION_PROG "prog"
+#define ELF_SECTION_CLASSIFIER "classifier"
+#define ELF_SECTION_ACTION "action"
+
+#define ELF_MAX_MAPS 64
+#define ELF_MAX_LICENSE_LEN 128
+
+/* Object pinning settings */
+#define PIN_NONE 0
+#define PIN_OBJECT_NS 1
+#define PIN_GLOBAL_NS 2
+
+/* ELF map definition */
+struct bpf_elf_map {
+ __u32 type;
+ __u32 size_key;
+ __u32 size_value;
+ __u32 max_elem;
+ __u32 flags;
+ __u32 id;
+ __u32 pinning;
+ __u32 inner_id;
+ __u32 inner_idx;
+};
+
+#define BPF_ANNOTATE_KV_PAIR(name, type_key, type_val) \
+ struct ____btf_map_##name { \
+ type_key key; \
+ type_val value; \
+ }; \
+ struct ____btf_map_##name \
+ __attribute__ ((section(".maps." #name), used)) \
+ ____btf_map_##name = { }
+
+#endif /* __BPF_ELF__ */
diff --git a/include/bpf_scm.h b/include/bpf_scm.h
new file mode 100644
index 0000000..669f053
--- /dev/null
+++ b/include/bpf_scm.h
@@ -0,0 +1,77 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __BPF_SCM__
+#define __BPF_SCM__
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+
+#include "utils.h"
+#include "bpf_elf.h"
+
+#define BPF_SCM_AUX_VER 1
+#define BPF_SCM_MAX_FDS ELF_MAX_MAPS
+#define BPF_SCM_MSG_SIZE 1024
+
+struct bpf_elf_st {
+ dev_t st_dev;
+ ino_t st_ino;
+};
+
+struct bpf_map_aux {
+ unsigned short uds_ver;
+ unsigned short num_ent;
+ char obj_name[64];
+ struct bpf_elf_st obj_st;
+ struct bpf_elf_map ent[BPF_SCM_MAX_FDS];
+};
+
+struct bpf_map_set_msg {
+ struct msghdr hdr;
+ struct iovec iov;
+ char msg_buf[BPF_SCM_MSG_SIZE];
+ struct bpf_map_aux aux;
+};
+
+static inline int *bpf_map_set_init(struct bpf_map_set_msg *msg,
+ struct sockaddr_un *addr,
+ unsigned int addr_len)
+{
+ const unsigned int cmsg_ctl_len = sizeof(int) * BPF_SCM_MAX_FDS;
+ struct cmsghdr *cmsg;
+
+ msg->iov.iov_base = &msg->aux;
+ msg->iov.iov_len = sizeof(msg->aux);
+
+ msg->hdr.msg_iov = &msg->iov;
+ msg->hdr.msg_iovlen = 1;
+
+ msg->hdr.msg_name = (struct sockaddr *)addr;
+ msg->hdr.msg_namelen = addr_len;
+
+ BUILD_BUG_ON(sizeof(msg->msg_buf) < cmsg_ctl_len);
+ msg->hdr.msg_control = &msg->msg_buf;
+ msg->hdr.msg_controllen = cmsg_ctl_len;
+
+ cmsg = CMSG_FIRSTHDR(&msg->hdr);
+ cmsg->cmsg_len = msg->hdr.msg_controllen;
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+
+ return (int *)CMSG_DATA(cmsg);
+}
+
+static inline void bpf_map_set_init_single(struct bpf_map_set_msg *msg,
+ int num)
+{
+ struct cmsghdr *cmsg;
+
+ msg->hdr.msg_controllen = CMSG_LEN(sizeof(int) * num);
+ msg->iov.iov_len = offsetof(struct bpf_map_aux, ent) +
+ sizeof(struct bpf_elf_map) * num;
+
+ cmsg = CMSG_FIRSTHDR(&msg->hdr);
+ cmsg->cmsg_len = msg->hdr.msg_controllen;
+}
+
+#endif /* __BPF_SCM__ */
diff --git a/include/bpf_util.h b/include/bpf_util.h
new file mode 100644
index 0000000..63db07c
--- /dev/null
+++ b/include/bpf_util.h
@@ -0,0 +1,303 @@
+/*
+ * bpf_util.h BPF common code
+ *
+ * This program is free software; you can distribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Daniel Borkmann <daniel@iogearbox.net>
+ * Jiri Pirko <jiri@resnulli.us>
+ */
+
+#ifndef __BPF_UTIL__
+#define __BPF_UTIL__
+
+#include <linux/bpf.h>
+#include <linux/btf.h>
+#include <linux/filter.h>
+#include <linux/magic.h>
+#include <linux/elf-em.h>
+#include <linux/if_alg.h>
+
+#include "utils.h"
+#include "bpf_scm.h"
+
+#define BPF_ENV_UDS "TC_BPF_UDS"
+#define BPF_ENV_MNT "TC_BPF_MNT"
+
+#ifndef BPF_MAX_LOG
+# define BPF_MAX_LOG 4096
+#endif
+
+#define BPF_DIR_GLOBALS "globals"
+
+#ifndef BPF_FS_MAGIC
+# define BPF_FS_MAGIC 0xcafe4a11
+#endif
+
+#define BPF_DIR_MNT "/sys/fs/bpf"
+
+#ifndef TRACEFS_MAGIC
+# define TRACEFS_MAGIC 0x74726163
+#endif
+
+#define TRACE_DIR_MNT "/sys/kernel/tracing"
+
+#ifndef AF_ALG
+# define AF_ALG 38
+#endif
+
+#ifndef EM_BPF
+# define EM_BPF 247
+#endif
+
+struct bpf_cfg_ops {
+ void (*cbpf_cb)(void *nl, const struct sock_filter *ops, int ops_len);
+ void (*ebpf_cb)(void *nl, int fd, const char *annotation);
+};
+
+enum bpf_mode {
+ CBPF_BYTECODE,
+ CBPF_FILE,
+ EBPF_OBJECT,
+ EBPF_PINNED,
+ BPF_MODE_MAX,
+};
+
+struct bpf_cfg_in {
+ const char *object;
+ const char *section;
+ const char *uds;
+ enum bpf_prog_type type;
+ enum bpf_mode mode;
+ __u32 ifindex;
+ bool verbose;
+ int argc;
+ char **argv;
+ struct sock_filter opcodes[BPF_MAXINSNS];
+ union {
+ int n_opcodes;
+ int prog_fd;
+ };
+};
+
+/* ALU ops on registers, bpf_add|sub|...: dst_reg += src_reg */
+
+#define BPF_ALU64_REG(OP, DST, SRC) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU64 | BPF_OP(OP) | BPF_X, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = 0, \
+ .imm = 0 })
+
+#define BPF_ALU32_REG(OP, DST, SRC) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU | BPF_OP(OP) | BPF_X, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = 0, \
+ .imm = 0 })
+
+/* ALU ops on immediates, bpf_add|sub|...: dst_reg += imm32 */
+
+#define BPF_ALU64_IMM(OP, DST, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU64 | BPF_OP(OP) | BPF_K, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = IMM })
+
+#define BPF_ALU32_IMM(OP, DST, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU | BPF_OP(OP) | BPF_K, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = IMM })
+
+/* Short form of mov, dst_reg = src_reg */
+
+#define BPF_MOV64_REG(DST, SRC) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU64 | BPF_MOV | BPF_X, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = 0, \
+ .imm = 0 })
+
+#define BPF_MOV32_REG(DST, SRC) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU | BPF_MOV | BPF_X, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = 0, \
+ .imm = 0 })
+
+/* Short form of mov, dst_reg = imm32 */
+
+#define BPF_MOV64_IMM(DST, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU64 | BPF_MOV | BPF_K, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = IMM })
+
+#define BPF_MOV32_IMM(DST, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_ALU | BPF_MOV | BPF_K, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = IMM })
+
+/* BPF_LD_IMM64 macro encodes single 'load 64-bit immediate' insn */
+#define BPF_LD_IMM64(DST, IMM) \
+ BPF_LD_IMM64_RAW(DST, 0, IMM)
+
+#define BPF_LD_IMM64_RAW(DST, SRC, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_LD | BPF_DW | BPF_IMM, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = 0, \
+ .imm = (__u32) (IMM) }), \
+ ((struct bpf_insn) { \
+ .code = 0, /* zero is reserved opcode */ \
+ .dst_reg = 0, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = ((__u64) (IMM)) >> 32 })
+
+#ifndef BPF_PSEUDO_MAP_FD
+# define BPF_PSEUDO_MAP_FD 1
+#endif
+
+/* pseudo BPF_LD_IMM64 insn used to refer to process-local map_fd */
+#define BPF_LD_MAP_FD(DST, MAP_FD) \
+ BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD)
+
+
+/* Direct packet access, R0 = *(uint *) (skb->data + imm32) */
+
+#define BPF_LD_ABS(SIZE, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \
+ .dst_reg = 0, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = IMM })
+
+/* Memory load, dst_reg = *(uint *) (src_reg + off16) */
+
+#define BPF_LDX_MEM(SIZE, DST, SRC, OFF) \
+ ((struct bpf_insn) { \
+ .code = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = OFF, \
+ .imm = 0 })
+
+/* Memory store, *(uint *) (dst_reg + off16) = src_reg */
+
+#define BPF_STX_MEM(SIZE, DST, SRC, OFF) \
+ ((struct bpf_insn) { \
+ .code = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = OFF, \
+ .imm = 0 })
+
+/* Memory store, *(uint *) (dst_reg + off16) = imm32 */
+
+#define BPF_ST_MEM(SIZE, DST, OFF, IMM) \
+ ((struct bpf_insn) { \
+ .code = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = OFF, \
+ .imm = IMM })
+
+/* Conditional jumps against registers, if (dst_reg 'op' src_reg) goto pc + off16 */
+
+#define BPF_JMP_REG(OP, DST, SRC, OFF) \
+ ((struct bpf_insn) { \
+ .code = BPF_JMP | BPF_OP(OP) | BPF_X, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = OFF, \
+ .imm = 0 })
+
+/* Conditional jumps against immediates, if (dst_reg 'op' imm32) goto pc + off16 */
+
+#define BPF_JMP_IMM(OP, DST, IMM, OFF) \
+ ((struct bpf_insn) { \
+ .code = BPF_JMP | BPF_OP(OP) | BPF_K, \
+ .dst_reg = DST, \
+ .src_reg = 0, \
+ .off = OFF, \
+ .imm = IMM })
+
+/* Raw code statement block */
+
+#define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM) \
+ ((struct bpf_insn) { \
+ .code = CODE, \
+ .dst_reg = DST, \
+ .src_reg = SRC, \
+ .off = OFF, \
+ .imm = IMM })
+
+/* Program exit */
+
+#define BPF_EXIT_INSN() \
+ ((struct bpf_insn) { \
+ .code = BPF_JMP | BPF_EXIT, \
+ .dst_reg = 0, \
+ .src_reg = 0, \
+ .off = 0, \
+ .imm = 0 })
+
+int bpf_parse_common(struct bpf_cfg_in *cfg, const struct bpf_cfg_ops *ops);
+int bpf_load_common(struct bpf_cfg_in *cfg, const struct bpf_cfg_ops *ops,
+ void *nl);
+int bpf_parse_and_load_common(struct bpf_cfg_in *cfg,
+ const struct bpf_cfg_ops *ops, void *nl);
+
+const char *bpf_prog_to_default_section(enum bpf_prog_type type);
+
+int bpf_graft_map(const char *map_path, uint32_t *key, int argc, char **argv);
+int bpf_trace_pipe(void);
+
+void bpf_print_ops(struct rtattr *bpf_ops, __u16 len);
+
+int bpf_prog_load(enum bpf_prog_type type, const struct bpf_insn *insns,
+ size_t size_insns, const char *license, char *log,
+ size_t size_log);
+
+int bpf_prog_attach_fd(int prog_fd, int target_fd, enum bpf_attach_type type);
+int bpf_prog_detach_fd(int target_fd, enum bpf_attach_type type);
+
+int bpf_dump_prog_info(FILE *f, uint32_t id);
+
+#ifdef HAVE_ELF
+int bpf_send_map_fds(const char *path, const char *obj);
+int bpf_recv_map_fds(const char *path, int *fds, struct bpf_map_aux *aux,
+ unsigned int entries);
+#else
+static inline int bpf_send_map_fds(const char *path, const char *obj)
+{
+ return 0;
+}
+
+static inline int bpf_recv_map_fds(const char *path, int *fds,
+ struct bpf_map_aux *aux,
+ unsigned int entries)
+{
+ return -1;
+}
+#endif /* HAVE_ELF */
+#endif /* __BPF_UTIL__ */
diff --git a/include/color.h b/include/color.h
new file mode 100644
index 0000000..17ec56f
--- /dev/null
+++ b/include/color.h
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __COLOR_H__
+#define __COLOR_H__ 1
+
+#include <stdbool.h>
+
+enum color_attr {
+ COLOR_IFNAME,
+ COLOR_MAC,
+ COLOR_INET,
+ COLOR_INET6,
+ COLOR_OPERSTATE_UP,
+ COLOR_OPERSTATE_DOWN,
+ COLOR_NONE
+};
+
+enum color_opt {
+ COLOR_OPT_NEVER = 0,
+ COLOR_OPT_AUTO = 1,
+ COLOR_OPT_ALWAYS = 2
+};
+
+bool check_enable_color(int color, int json);
+bool matches_color(const char *arg, int *val);
+int color_fprintf(FILE *fp, enum color_attr attr, const char *fmt, ...);
+enum color_attr ifa_family_color(__u8 ifa_family);
+enum color_attr oper_state_color(__u8 state);
+
+#endif
diff --git a/include/dlfcn.h b/include/dlfcn.h
new file mode 100644
index 0000000..1d8890a
--- /dev/null
+++ b/include/dlfcn.h
@@ -0,0 +1,41 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Stub dlfcn implementation for systems that lack shared library support
+ * but obviously can still reference compiled-in symbols.
+ */
+
+#ifndef NO_SHARED_LIBS
+#include_next <dlfcn.h>
+#else
+
+#define RTLD_LAZY 0
+#define RTLD_GLOBAL 1
+#define _FAKE_DLFCN_HDL (void *)0xbeefcafe
+
+static inline void *dlopen(const char *file, int flag)
+{
+ if (file == NULL)
+ return _FAKE_DLFCN_HDL;
+ else
+ return NULL;
+}
+
+void *_dlsym(const char *sym);
+static inline void *dlsym(void *handle, const char *sym)
+{
+ if (handle != _FAKE_DLFCN_HDL)
+ return NULL;
+ return _dlsym(sym);
+}
+
+static inline char *dlerror(void)
+{
+ return NULL;
+}
+
+static inline int dlclose(void *handle)
+{
+ return (handle == _FAKE_DLFCN_HDL) ? 0 : 1;
+}
+
+#endif
diff --git a/include/ip6tables.h b/include/ip6tables.h
new file mode 100644
index 0000000..bfb2868
--- /dev/null
+++ b/include/ip6tables.h
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _IP6TABLES_USER_H
+#define _IP6TABLES_USER_H
+
+#include <netinet/ip.h>
+#include <xtables.h>
+#include <libiptc/libip6tc.h>
+#include <iptables/internal.h>
+
+/* Your shared library should call one of these. */
+extern int do_command6(int argc, char *argv[], char **table,
+ struct xtc_handle **handle, bool restore);
+
+extern int for_each_chain6(int (*fn)(const xt_chainlabel, int, struct xtc_handle *), int verbose, int builtinstoo, struct xtc_handle *handle);
+extern int flush_entries6(const xt_chainlabel chain, int verbose, struct xtc_handle *handle);
+extern int delete_chain6(const xt_chainlabel chain, int verbose, struct xtc_handle *handle);
+void print_rule6(const struct ip6t_entry *e, struct xtc_handle *h, const char *chain, int counters);
+
+extern struct xtables_globals ip6tables_globals;
+
+#endif /*_IP6TABLES_USER_H*/
diff --git a/include/iptables.h b/include/iptables.h
new file mode 100644
index 0000000..78bc378
--- /dev/null
+++ b/include/iptables.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _IPTABLES_USER_H
+#define _IPTABLES_USER_H
+
+#include <netinet/ip.h>
+#include <xtables.h>
+#include <libiptc/libiptc.h>
+#include <iptables/internal.h>
+
+/* Your shared library should call one of these. */
+extern int do_command4(int argc, char *argv[], char **table,
+ struct xtc_handle **handle, bool restore);
+extern int delete_chain4(const xt_chainlabel chain, int verbose,
+ struct xtc_handle *handle);
+extern int flush_entries4(const xt_chainlabel chain, int verbose,
+ struct xtc_handle *handle);
+extern int for_each_chain4(int (*fn)(const xt_chainlabel, int, struct xtc_handle *),
+ int verbose, int builtinstoo, struct xtc_handle *handle);
+extern void print_rule4(const struct ipt_entry *e,
+ struct xtc_handle *handle, const char *chain, int counters);
+
+extern struct xtables_globals iptables_globals;
+
+extern struct xtables_globals xtables_globals;
+
+#endif /*_IPTABLES_USER_H*/
diff --git a/include/iptables/internal.h b/include/iptables/internal.h
new file mode 100644
index 0000000..1fd1372
--- /dev/null
+++ b/include/iptables/internal.h
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef IPTABLES_INTERNAL_H
+#define IPTABLES_INTERNAL_H 1
+
+#define IPTABLES_VERSION "1.6.0"
+
+/**
+ * Program's own name and version.
+ */
+extern const char *program_name, *program_version;
+
+extern int line;
+
+#endif /* IPTABLES_INTERNAL_H */
diff --git a/include/json_print.h b/include/json_print.h
new file mode 100644
index 0000000..fe92d14
--- /dev/null
+++ b/include/json_print.h
@@ -0,0 +1,77 @@
+/*
+ * json_print.h "print regular or json output, based on json_writer".
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version
+ * 2 of the License, or (at your option) any later version.
+ *
+ * Authors: Julien Fortin, <julien@cumulusnetworks.com>
+ */
+
+#ifndef _JSON_PRINT_H_
+#define _JSON_PRINT_H_
+
+#include "json_writer.h"
+#include "color.h"
+
+json_writer_t *get_json_writer(void);
+
+/*
+ * use:
+ * - PRINT_ANY for context based output
+ * - PRINT_FP for non json specific output
+ * - PRINT_JSON for json specific output
+ */
+enum output_type {
+ PRINT_FP = 1,
+ PRINT_JSON = 2,
+ PRINT_ANY = 4,
+};
+
+void new_json_obj(int json);
+void delete_json_obj(void);
+
+bool is_json_context(void);
+
+void fflush_fp(void);
+
+void open_json_object(const char *str);
+void close_json_object(void);
+void open_json_array(enum output_type type, const char *delim);
+void close_json_array(enum output_type type, const char *delim);
+
+void print_nl(void);
+
+#define _PRINT_FUNC(type_name, type) \
+ void print_color_##type_name(enum output_type t, \
+ enum color_attr color, \
+ const char *key, \
+ const char *fmt, \
+ type value); \
+ \
+ static inline void print_##type_name(enum output_type t, \
+ const char *key, \
+ const char *fmt, \
+ type value) \
+ { \
+ print_color_##type_name(t, COLOR_NONE, key, fmt, value); \
+ }
+
+_PRINT_FUNC(int, int)
+_PRINT_FUNC(s64, int64_t)
+_PRINT_FUNC(bool, bool)
+_PRINT_FUNC(null, const char*)
+_PRINT_FUNC(string, const char*)
+_PRINT_FUNC(uint, unsigned int)
+_PRINT_FUNC(u64, uint64_t)
+_PRINT_FUNC(hhu, unsigned char)
+_PRINT_FUNC(hu, unsigned short)
+_PRINT_FUNC(hex, unsigned int)
+_PRINT_FUNC(0xhex, unsigned long long)
+_PRINT_FUNC(luint, unsigned long)
+_PRINT_FUNC(lluint, unsigned long long)
+_PRINT_FUNC(float, double)
+#undef _PRINT_FUNC
+
+#endif /* _JSON_PRINT_H_ */
diff --git a/include/json_writer.h b/include/json_writer.h
new file mode 100644
index 0000000..b52dc2d
--- /dev/null
+++ b/include/json_writer.h
@@ -0,0 +1,76 @@
+/* SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) */
+/*
+ * Simple streaming JSON writer
+ *
+ * This takes care of the annoying bits of JSON syntax like the commas
+ * after elements
+ *
+ * Authors: Stephen Hemminger <stephen@networkplumber.org>
+ */
+
+#ifndef _JSON_WRITER_H_
+#define _JSON_WRITER_H_
+
+#include <stdbool.h>
+#include <stdint.h>
+
+/* Opaque class structure */
+typedef struct json_writer json_writer_t;
+
+/* Create a new JSON stream */
+json_writer_t *jsonw_new(FILE *f);
+/* End output to JSON stream */
+void jsonw_destroy(json_writer_t **self_p);
+
+/* Cause output to have pretty whitespace */
+void jsonw_pretty(json_writer_t *self, bool on);
+
+/* Add property name */
+void jsonw_name(json_writer_t *self, const char *name);
+
+/* Add value */
+__attribute__((format(printf, 2, 3)))
+void jsonw_printf(json_writer_t *self, const char *fmt, ...);
+void jsonw_string(json_writer_t *self, const char *value);
+void jsonw_bool(json_writer_t *self, bool value);
+void jsonw_float(json_writer_t *self, double number);
+void jsonw_float_fmt(json_writer_t *self, const char *fmt, double num);
+void jsonw_uint(json_writer_t *self, unsigned int number);
+void jsonw_u64(json_writer_t *self, uint64_t number);
+void jsonw_xint(json_writer_t *self, uint64_t number);
+void jsonw_hhu(json_writer_t *self, unsigned char num);
+void jsonw_hu(json_writer_t *self, unsigned short number);
+void jsonw_int(json_writer_t *self, int number);
+void jsonw_s64(json_writer_t *self, int64_t number);
+void jsonw_null(json_writer_t *self);
+void jsonw_luint(json_writer_t *self, unsigned long num);
+void jsonw_lluint(json_writer_t *self, unsigned long long num);
+
+/* Useful Combinations of name and value */
+void jsonw_string_field(json_writer_t *self, const char *prop, const char *val);
+void jsonw_bool_field(json_writer_t *self, const char *prop, bool value);
+void jsonw_float_field(json_writer_t *self, const char *prop, double num);
+void jsonw_uint_field(json_writer_t *self, const char *prop, unsigned int num);
+void jsonw_u64_field(json_writer_t *self, const char *prop, uint64_t num);
+void jsonw_xint_field(json_writer_t *self, const char *prop, uint64_t num);
+void jsonw_hhu_field(json_writer_t *self, const char *prop, unsigned char num);
+void jsonw_hu_field(json_writer_t *self, const char *prop, unsigned short num);
+void jsonw_int_field(json_writer_t *self, const char *prop, int num);
+void jsonw_s64_field(json_writer_t *self, const char *prop, int64_t num);
+void jsonw_null_field(json_writer_t *self, const char *prop);
+void jsonw_luint_field(json_writer_t *self, const char *prop,
+ unsigned long num);
+void jsonw_lluint_field(json_writer_t *self, const char *prop,
+ unsigned long long num);
+
+/* Collections */
+void jsonw_start_object(json_writer_t *self);
+void jsonw_end_object(json_writer_t *self);
+
+void jsonw_start_array(json_writer_t *self);
+void jsonw_end_array(json_writer_t *self);
+
+/* Override default exception handling */
+typedef void (jsonw_err_handler_fn)(const char *);
+
+#endif /* _JSON_WRITER_H_ */
diff --git a/include/libgenl.h b/include/libgenl.h
new file mode 100644
index 0000000..656493a
--- /dev/null
+++ b/include/libgenl.h
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __LIBGENL_H__
+#define __LIBGENL_H__
+
+#include "libnetlink.h"
+
+#define GENL_REQUEST(_req, _bufsiz, _family, _hdrsiz, _ver, _cmd, _flags) \
+struct { \
+ struct nlmsghdr n; \
+ struct genlmsghdr g; \
+ char buf[NLMSG_ALIGN(_hdrsiz) + (_bufsiz)]; \
+} _req = { \
+ .n = { \
+ .nlmsg_type = (_family), \
+ .nlmsg_flags = (_flags), \
+ .nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN + (_hdrsiz)), \
+ }, \
+ .g = { \
+ .cmd = (_cmd), \
+ .version = (_ver), \
+ }, \
+}
+
+int genl_resolve_family(struct rtnl_handle *grth, const char *family);
+int genl_init_handle(struct rtnl_handle *grth, const char *family,
+ int *genl_family);
+
+#endif /* __LIBGENL_H__ */
diff --git a/include/libiptc/ipt_kernel_headers.h b/include/libiptc/ipt_kernel_headers.h
new file mode 100644
index 0000000..3d2a2a3
--- /dev/null
+++ b/include/libiptc/ipt_kernel_headers.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* This is the userspace/kernel interface for Generic IP Chains,
+ required for libc6. */
+#ifndef _FWCHAINS_KERNEL_HEADERS_H
+#define _FWCHAINS_KERNEL_HEADERS_H
+
+#include <limits.h>
+
+#include <netinet/ip.h>
+#include <netinet/in.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/tcp.h>
+#include <netinet/udp.h>
+#include <net/if.h>
+#include <sys/types.h>
+#endif
diff --git a/include/libiptc/libip6tc.h b/include/libiptc/libip6tc.h
new file mode 100644
index 0000000..cd588de
--- /dev/null
+++ b/include/libiptc/libip6tc.h
@@ -0,0 +1,162 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LIBIP6TC_H
+#define _LIBIP6TC_H
+/* Library which manipulates firewall rules. Version 0.2. */
+
+#include <linux/types.h>
+#include <libiptc/ipt_kernel_headers.h>
+#ifdef __cplusplus
+# include <climits>
+#else
+# include <limits.h> /* INT_MAX in ip6_tables.h */
+#endif
+#include <linux/netfilter_ipv6/ip6_tables.h>
+#include <libiptc/xtcshared.h>
+
+#define ip6tc_handle xtc_handle
+#define ip6t_chainlabel xt_chainlabel
+
+#define IP6TC_LABEL_ACCEPT "ACCEPT"
+#define IP6TC_LABEL_DROP "DROP"
+#define IP6TC_LABEL_QUEUE "QUEUE"
+#define IP6TC_LABEL_RETURN "RETURN"
+
+/* Does this chain exist? */
+int ip6tc_is_chain(const char *chain, struct xtc_handle *const handle);
+
+/* Take a snapshot of the rules. Returns NULL on error. */
+struct xtc_handle *ip6tc_init(const char *tablename);
+
+/* Cleanup after ip6tc_init(). */
+void ip6tc_free(struct xtc_handle *h);
+
+/* Iterator functions to run through the chains. Returns NULL at end. */
+const char *ip6tc_first_chain(struct xtc_handle *handle);
+const char *ip6tc_next_chain(struct xtc_handle *handle);
+
+/* Get first rule in the given chain: NULL for empty chain. */
+const struct ip6t_entry *ip6tc_first_rule(const char *chain,
+ struct xtc_handle *handle);
+
+/* Returns NULL when rules run out. */
+const struct ip6t_entry *ip6tc_next_rule(const struct ip6t_entry *prev,
+ struct xtc_handle *handle);
+
+/* Returns a pointer to the target name of this position. */
+const char *ip6tc_get_target(const struct ip6t_entry *e,
+ struct xtc_handle *handle);
+
+/* Is this a built-in chain? */
+int ip6tc_builtin(const char *chain, struct xtc_handle *const handle);
+
+/* Get the policy of a given built-in chain */
+const char *ip6tc_get_policy(const char *chain,
+ struct xt_counters *counters,
+ struct xtc_handle *handle);
+
+/* These functions return TRUE for OK or 0 and set errno. If errno ==
+ 0, it means there was a version error (ie. upgrade libiptc). */
+/* Rule numbers start at 1 for the first rule. */
+
+/* Insert the entry `fw' in chain `chain' into position `rulenum'. */
+int ip6tc_insert_entry(const xt_chainlabel chain,
+ const struct ip6t_entry *e,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Atomically replace rule `rulenum' in `chain' with `fw'. */
+int ip6tc_replace_entry(const xt_chainlabel chain,
+ const struct ip6t_entry *e,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Append entry `fw' to chain `chain'. Equivalent to insert with
+ rulenum = length of chain. */
+int ip6tc_append_entry(const xt_chainlabel chain,
+ const struct ip6t_entry *e,
+ struct xtc_handle *handle);
+
+/* Check whether a matching rule exists */
+int ip6tc_check_entry(const xt_chainlabel chain,
+ const struct ip6t_entry *origfw,
+ unsigned char *matchmask,
+ struct xtc_handle *handle);
+
+/* Delete the first rule in `chain' which matches `fw'. */
+int ip6tc_delete_entry(const xt_chainlabel chain,
+ const struct ip6t_entry *origfw,
+ unsigned char *matchmask,
+ struct xtc_handle *handle);
+
+/* Delete the rule in position `rulenum' in `chain'. */
+int ip6tc_delete_num_entry(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Check the packet `fw' on chain `chain'. Returns the verdict, or
+ NULL and sets errno. */
+const char *ip6tc_check_packet(const xt_chainlabel chain,
+ struct ip6t_entry *,
+ struct xtc_handle *handle);
+
+/* Flushes the entries in the given chain (ie. empties chain). */
+int ip6tc_flush_entries(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Zeroes the counters in a chain. */
+int ip6tc_zero_entries(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Creates a new chain. */
+int ip6tc_create_chain(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Deletes a chain. */
+int ip6tc_delete_chain(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Renames a chain. */
+int ip6tc_rename_chain(const xt_chainlabel oldname,
+ const xt_chainlabel newname,
+ struct xtc_handle *handle);
+
+/* Sets the policy on a built-in chain. */
+int ip6tc_set_policy(const xt_chainlabel chain,
+ const xt_chainlabel policy,
+ struct xt_counters *counters,
+ struct xtc_handle *handle);
+
+/* Get the number of references to this chain */
+int ip6tc_get_references(unsigned int *ref, const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* read packet and byte counters for a specific rule */
+struct xt_counters *ip6tc_read_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* zero packet and byte counters for a specific rule */
+int ip6tc_zero_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* set packet and byte counters for a specific rule */
+int ip6tc_set_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xt_counters *counters,
+ struct xtc_handle *handle);
+
+/* Makes the actual changes. */
+int ip6tc_commit(struct xtc_handle *handle);
+
+/* Get raw socket. */
+int ip6tc_get_raw_socket(void);
+
+/* Translates errno numbers into more human-readable form than strerror. */
+const char *ip6tc_strerror(int err);
+
+extern void dump_entries6(struct xtc_handle *const);
+
+extern const struct xtc_ops ip6tc_ops;
+
+#endif /* _LIBIP6TC_H */
diff --git a/include/libiptc/libiptc.h b/include/libiptc/libiptc.h
new file mode 100644
index 0000000..1bfe4e1
--- /dev/null
+++ b/include/libiptc/libiptc.h
@@ -0,0 +1,173 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LIBIPTC_H
+#define _LIBIPTC_H
+/* Library which manipulates filtering rules. */
+
+#include <linux/types.h>
+#include <libiptc/ipt_kernel_headers.h>
+#ifdef __cplusplus
+# include <climits>
+#else
+# include <limits.h> /* INT_MAX in ip_tables.h */
+#endif
+#include <linux/netfilter_ipv4/ip_tables.h>
+#include <libiptc/xtcshared.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define iptc_handle xtc_handle
+#define ipt_chainlabel xt_chainlabel
+
+#define IPTC_LABEL_ACCEPT "ACCEPT"
+#define IPTC_LABEL_DROP "DROP"
+#define IPTC_LABEL_QUEUE "QUEUE"
+#define IPTC_LABEL_RETURN "RETURN"
+
+/* Does this chain exist? */
+int iptc_is_chain(const char *chain, struct xtc_handle *const handle);
+
+/* Take a snapshot of the rules. Returns NULL on error. */
+struct xtc_handle *iptc_init(const char *tablename);
+
+/* Cleanup after iptc_init(). */
+void iptc_free(struct xtc_handle *h);
+
+/* Iterator functions to run through the chains. Returns NULL at end. */
+const char *iptc_first_chain(struct xtc_handle *handle);
+const char *iptc_next_chain(struct xtc_handle *handle);
+
+/* Get first rule in the given chain: NULL for empty chain. */
+const struct ipt_entry *iptc_first_rule(const char *chain,
+ struct xtc_handle *handle);
+
+/* Returns NULL when rules run out. */
+const struct ipt_entry *iptc_next_rule(const struct ipt_entry *prev,
+ struct xtc_handle *handle);
+
+/* Returns a pointer to the target name of this entry. */
+const char *iptc_get_target(const struct ipt_entry *e,
+ struct xtc_handle *handle);
+
+/* Is this a built-in chain? */
+int iptc_builtin(const char *chain, struct xtc_handle *const handle);
+
+/* Get the policy of a given built-in chain */
+const char *iptc_get_policy(const char *chain,
+ struct xt_counters *counter,
+ struct xtc_handle *handle);
+
+/* These functions return TRUE for OK or 0 and set errno. If errno ==
+ 0, it means there was a version error (ie. upgrade libiptc). */
+/* Rule numbers start at 1 for the first rule. */
+
+/* Insert the entry `e' in chain `chain' into position `rulenum'. */
+int iptc_insert_entry(const xt_chainlabel chain,
+ const struct ipt_entry *e,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Atomically replace rule `rulenum' in `chain' with `e'. */
+int iptc_replace_entry(const xt_chainlabel chain,
+ const struct ipt_entry *e,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Append entry `e' to chain `chain'. Equivalent to insert with
+ rulenum = length of chain. */
+int iptc_append_entry(const xt_chainlabel chain,
+ const struct ipt_entry *e,
+ struct xtc_handle *handle);
+
+/* Check whether a mathching rule exists */
+int iptc_check_entry(const xt_chainlabel chain,
+ const struct ipt_entry *origfw,
+ unsigned char *matchmask,
+ struct xtc_handle *handle);
+
+/* Delete the first rule in `chain' which matches `e', subject to
+ matchmask (array of length == origfw) */
+int iptc_delete_entry(const xt_chainlabel chain,
+ const struct ipt_entry *origfw,
+ unsigned char *matchmask,
+ struct xtc_handle *handle);
+
+/* Delete the rule in position `rulenum' in `chain'. */
+int iptc_delete_num_entry(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* Check the packet `e' on chain `chain'. Returns the verdict, or
+ NULL and sets errno. */
+const char *iptc_check_packet(const xt_chainlabel chain,
+ struct ipt_entry *entry,
+ struct xtc_handle *handle);
+
+/* Flushes the entries in the given chain (ie. empties chain). */
+int iptc_flush_entries(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Zeroes the counters in a chain. */
+int iptc_zero_entries(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Creates a new chain. */
+int iptc_create_chain(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Deletes a chain. */
+int iptc_delete_chain(const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* Renames a chain. */
+int iptc_rename_chain(const xt_chainlabel oldname,
+ const xt_chainlabel newname,
+ struct xtc_handle *handle);
+
+/* Sets the policy on a built-in chain. */
+int iptc_set_policy(const xt_chainlabel chain,
+ const xt_chainlabel policy,
+ struct xt_counters *counters,
+ struct xtc_handle *handle);
+
+/* Get the number of references to this chain */
+int iptc_get_references(unsigned int *ref,
+ const xt_chainlabel chain,
+ struct xtc_handle *handle);
+
+/* read packet and byte counters for a specific rule */
+struct xt_counters *iptc_read_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* zero packet and byte counters for a specific rule */
+int iptc_zero_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xtc_handle *handle);
+
+/* set packet and byte counters for a specific rule */
+int iptc_set_counter(const xt_chainlabel chain,
+ unsigned int rulenum,
+ struct xt_counters *counters,
+ struct xtc_handle *handle);
+
+/* Makes the actual changes. */
+int iptc_commit(struct xtc_handle *handle);
+
+/* Get raw socket. */
+int iptc_get_raw_socket(void);
+
+/* Translates errno numbers into more human-readable form than strerror. */
+const char *iptc_strerror(int err);
+
+extern void dump_entries(struct xtc_handle *const);
+
+extern const struct xtc_ops iptc_ops;
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _LIBIPTC_H */
diff --git a/include/libiptc/libxtc.h b/include/libiptc/libxtc.h
new file mode 100644
index 0000000..1e9596a
--- /dev/null
+++ b/include/libiptc/libxtc.h
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LIBXTC_H
+#define _LIBXTC_H
+/* Library which manipulates filtering rules. */
+
+#include <libiptc/ipt_kernel_headers.h>
+#include <linux/netfilter/x_tables.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef XT_MIN_ALIGN
+/* xt_entry has pointers and u_int64_t's in it, so if you align to
+ it, you'll also align to any crazy matches and targets someone
+ might write */
+#define XT_MIN_ALIGN (__alignof__(struct xt_entry))
+#endif
+
+#ifndef XT_ALIGN
+#define XT_ALIGN(s) (((s) + ((XT_MIN_ALIGN)-1)) & ~((XT_MIN_ALIGN)-1))
+#endif
+
+#define XTC_LABEL_ACCEPT "ACCEPT"
+#define XTC_LABEL_DROP "DROP"
+#define XTC_LABEL_QUEUE "QUEUE"
+#define XTC_LABEL_RETURN "RETURN"
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBXTC_H */
diff --git a/include/libiptc/xtcshared.h b/include/libiptc/xtcshared.h
new file mode 100644
index 0000000..278a58f
--- /dev/null
+++ b/include/libiptc/xtcshared.h
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LIBXTC_SHARED_H
+#define _LIBXTC_SHARED_H 1
+
+typedef char xt_chainlabel[32];
+struct xtc_handle;
+struct xt_counters;
+
+struct xtc_ops {
+ int (*commit)(struct xtc_handle *);
+ void (*free)(struct xtc_handle *);
+ int (*builtin)(const char *, struct xtc_handle *const);
+ int (*is_chain)(const char *, struct xtc_handle *const);
+ int (*flush_entries)(const xt_chainlabel, struct xtc_handle *);
+ int (*create_chain)(const xt_chainlabel, struct xtc_handle *);
+ int (*set_policy)(const xt_chainlabel, const xt_chainlabel,
+ struct xt_counters *, struct xtc_handle *);
+ const char *(*strerror)(int);
+};
+
+#endif /* _LIBXTC_SHARED_H */
diff --git a/include/libnetlink.h b/include/libnetlink.h
new file mode 100644
index 0000000..8ebdc6d
--- /dev/null
+++ b/include/libnetlink.h
@@ -0,0 +1,286 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __LIBNETLINK_H__
+#define __LIBNETLINK_H__ 1
+
+#include <stdio.h>
+#include <string.h>
+#include <asm/types.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <linux/if_link.h>
+#include <linux/if_addr.h>
+#include <linux/neighbour.h>
+#include <linux/netconf.h>
+#include <arpa/inet.h>
+
+struct rtnl_handle {
+ int fd;
+ struct sockaddr_nl local;
+ struct sockaddr_nl peer;
+ __u32 seq;
+ __u32 dump;
+ int proto;
+ FILE *dump_fp;
+#define RTNL_HANDLE_F_LISTEN_ALL_NSID 0x01
+#define RTNL_HANDLE_F_SUPPRESS_NLERR 0x02
+#define RTNL_HANDLE_F_STRICT_CHK 0x04
+ int flags;
+};
+
+struct nlmsg_list {
+ struct nlmsg_list *next;
+ struct nlmsghdr h;
+};
+
+struct nlmsg_chain {
+ struct nlmsg_list *head;
+ struct nlmsg_list *tail;
+};
+
+extern int rcvbuf;
+
+int rtnl_open(struct rtnl_handle *rth, unsigned int subscriptions)
+ __attribute__((warn_unused_result));
+
+int rtnl_open_byproto(struct rtnl_handle *rth, unsigned int subscriptions,
+ int protocol)
+ __attribute__((warn_unused_result));
+int rtnl_add_nl_group(struct rtnl_handle *rth, unsigned int group)
+ __attribute__((warn_unused_result));
+void rtnl_close(struct rtnl_handle *rth);
+void rtnl_set_strict_dump(struct rtnl_handle *rth);
+
+typedef int (*req_filter_fn_t)(struct nlmsghdr *nlh, int reqlen);
+
+int rtnl_addrdump_req(struct rtnl_handle *rth, int family,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+int rtnl_addrlbldump_req(struct rtnl_handle *rth, int family)
+ __attribute__((warn_unused_result));
+int rtnl_routedump_req(struct rtnl_handle *rth, int family,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+int rtnl_ruledump_req(struct rtnl_handle *rth, int family)
+ __attribute__((warn_unused_result));
+int rtnl_neighdump_req(struct rtnl_handle *rth, int family,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+int rtnl_neightbldump_req(struct rtnl_handle *rth, int family)
+ __attribute__((warn_unused_result));
+int rtnl_mdbdump_req(struct rtnl_handle *rth, int family)
+ __attribute__((warn_unused_result));
+int rtnl_netconfdump_req(struct rtnl_handle *rth, int family)
+ __attribute__((warn_unused_result));
+
+int rtnl_linkdump_req(struct rtnl_handle *rth, int fam)
+ __attribute__((warn_unused_result));
+int rtnl_linkdump_req_filter(struct rtnl_handle *rth, int fam, __u32 filt_mask)
+ __attribute__((warn_unused_result));
+
+int rtnl_linkdump_req_filter_fn(struct rtnl_handle *rth, int fam,
+ req_filter_fn_t fn)
+ __attribute__((warn_unused_result));
+int rtnl_fdb_linkdump_req_filter_fn(struct rtnl_handle *rth,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+int rtnl_nsiddump_req_filter_fn(struct rtnl_handle *rth, int family,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+int rtnl_statsdump_req_filter(struct rtnl_handle *rth, int fam, __u32 filt_mask)
+ __attribute__((warn_unused_result));
+int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req,
+ int len)
+ __attribute__((warn_unused_result));
+int rtnl_dump_request_n(struct rtnl_handle *rth, struct nlmsghdr *n)
+ __attribute__((warn_unused_result));
+
+int rtnl_nexthopdump_req(struct rtnl_handle *rth, int family,
+ req_filter_fn_t filter_fn)
+ __attribute__((warn_unused_result));
+
+struct rtnl_ctrl_data {
+ int nsid;
+};
+
+typedef int (*rtnl_filter_t)(struct nlmsghdr *n, void *);
+
+typedef int (*rtnl_listen_filter_t)(struct rtnl_ctrl_data *,
+ struct nlmsghdr *n, void *);
+
+typedef int (*nl_ext_ack_fn_t)(const char *errmsg, uint32_t off,
+ const struct nlmsghdr *inner_nlh);
+
+struct rtnl_dump_filter_arg {
+ rtnl_filter_t filter;
+ void *arg1;
+ __u16 nc_flags;
+};
+
+int rtnl_dump_filter_nc(struct rtnl_handle *rth,
+ rtnl_filter_t filter,
+ void *arg, __u16 nc_flags);
+#define rtnl_dump_filter(rth, filter, arg) \
+ rtnl_dump_filter_nc(rth, filter, arg, 0)
+int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n,
+ struct nlmsghdr **answer)
+ __attribute__((warn_unused_result));
+int rtnl_talk_iov(struct rtnl_handle *rtnl, struct iovec *iovec, size_t iovlen,
+ struct nlmsghdr **answer)
+ __attribute__((warn_unused_result));
+int rtnl_talk_suppress_rtnl_errmsg(struct rtnl_handle *rtnl, struct nlmsghdr *n,
+ struct nlmsghdr **answer)
+ __attribute__((warn_unused_result));
+int rtnl_send(struct rtnl_handle *rth, const void *buf, int)
+ __attribute__((warn_unused_result));
+int rtnl_send_check(struct rtnl_handle *rth, const void *buf, int)
+ __attribute__((warn_unused_result));
+int nl_dump_ext_ack(const struct nlmsghdr *nlh, nl_ext_ack_fn_t errfn);
+int nl_dump_ext_ack_done(const struct nlmsghdr *nlh, int error);
+
+int addattr(struct nlmsghdr *n, int maxlen, int type);
+int addattr8(struct nlmsghdr *n, int maxlen, int type, __u8 data);
+int addattr16(struct nlmsghdr *n, int maxlen, int type, __u16 data);
+int addattr32(struct nlmsghdr *n, int maxlen, int type, __u32 data);
+int addattr64(struct nlmsghdr *n, int maxlen, int type, __u64 data);
+int addattrstrz(struct nlmsghdr *n, int maxlen, int type, const char *data);
+
+int addattr_l(struct nlmsghdr *n, int maxlen, int type,
+ const void *data, int alen);
+int addraw_l(struct nlmsghdr *n, int maxlen, const void *data, int len);
+struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type);
+int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest);
+struct rtattr *addattr_nest_compat(struct nlmsghdr *n, int maxlen, int type,
+ const void *data, int len);
+int addattr_nest_compat_end(struct nlmsghdr *n, struct rtattr *nest);
+int rta_addattr8(struct rtattr *rta, int maxlen, int type, __u8 data);
+int rta_addattr16(struct rtattr *rta, int maxlen, int type, __u16 data);
+int rta_addattr32(struct rtattr *rta, int maxlen, int type, __u32 data);
+int rta_addattr64(struct rtattr *rta, int maxlen, int type, __u64 data);
+int rta_addattr_l(struct rtattr *rta, int maxlen, int type,
+ const void *data, int alen);
+
+int parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len);
+int parse_rtattr_flags(struct rtattr *tb[], int max, struct rtattr *rta,
+ int len, unsigned short flags);
+struct rtattr *parse_rtattr_one(int type, struct rtattr *rta, int len);
+int __parse_rtattr_nested_compat(struct rtattr *tb[], int max, struct rtattr *rta, int len);
+
+struct rtattr *rta_nest(struct rtattr *rta, int maxlen, int type);
+int rta_nest_end(struct rtattr *rta, struct rtattr *nest);
+
+#define RTA_TAIL(rta) \
+ ((struct rtattr *) (((void *) (rta)) + \
+ RTA_ALIGN((rta)->rta_len)))
+
+#define parse_rtattr_nested(tb, max, rta) \
+ (parse_rtattr((tb), (max), RTA_DATA(rta), RTA_PAYLOAD(rta)))
+
+#define parse_rtattr_one_nested(type, rta) \
+ (parse_rtattr_one(type, RTA_DATA(rta), RTA_PAYLOAD(rta)))
+
+#define parse_rtattr_nested_compat(tb, max, rta, data, len) \
+ ({ data = RTA_PAYLOAD(rta) >= len ? RTA_DATA(rta) : NULL; \
+ __parse_rtattr_nested_compat(tb, max, rta, len); })
+
+static inline __u8 rta_getattr_u8(const struct rtattr *rta)
+{
+ return *(__u8 *)RTA_DATA(rta);
+}
+static inline __u16 rta_getattr_u16(const struct rtattr *rta)
+{
+ return *(__u16 *)RTA_DATA(rta);
+}
+static inline __be16 rta_getattr_be16(const struct rtattr *rta)
+{
+ return ntohs(rta_getattr_u16(rta));
+}
+static inline __u32 rta_getattr_u32(const struct rtattr *rta)
+{
+ return *(__u32 *)RTA_DATA(rta);
+}
+static inline __be32 rta_getattr_be32(const struct rtattr *rta)
+{
+ return ntohl(rta_getattr_u32(rta));
+}
+static inline __u64 rta_getattr_u64(const struct rtattr *rta)
+{
+ __u64 tmp;
+
+ memcpy(&tmp, RTA_DATA(rta), sizeof(__u64));
+ return tmp;
+}
+static inline __s32 rta_getattr_s32(const struct rtattr *rta)
+{
+ return *(__s32 *)RTA_DATA(rta);
+}
+static inline __s64 rta_getattr_s64(const struct rtattr *rta)
+{
+ __s64 tmp;
+
+ memcpy(&tmp, RTA_DATA(rta), sizeof(tmp));
+ return tmp;
+}
+static inline const char *rta_getattr_str(const struct rtattr *rta)
+{
+ return (const char *)RTA_DATA(rta);
+}
+
+int rtnl_listen_all_nsid(struct rtnl_handle *);
+int rtnl_listen(struct rtnl_handle *, rtnl_listen_filter_t handler,
+ void *jarg);
+int rtnl_from_file(FILE *, rtnl_listen_filter_t handler,
+ void *jarg);
+
+#define NLMSG_TAIL(nmsg) \
+ ((struct rtattr *) (((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
+
+#ifndef IFA_RTA
+#define IFA_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct ifaddrmsg))))
+#endif
+#ifndef IFA_PAYLOAD
+#define IFA_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct ifaddrmsg))
+#endif
+
+#ifndef IFLA_RTA
+#define IFLA_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct ifinfomsg))))
+#endif
+#ifndef IFLA_PAYLOAD
+#define IFLA_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct ifinfomsg))
+#endif
+
+#ifndef NDA_RTA
+#define NDA_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct ndmsg))))
+#endif
+#ifndef NDA_PAYLOAD
+#define NDA_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct ndmsg))
+#endif
+
+#ifndef NDTA_RTA
+#define NDTA_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct ndtmsg))))
+#endif
+#ifndef NDTA_PAYLOAD
+#define NDTA_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct ndtmsg))
+#endif
+
+#ifndef NETNS_RTA
+#define NETNS_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct rtgenmsg))))
+#endif
+#ifndef NETNS_PAYLOAD
+#define NETNS_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct rtgenmsg))
+#endif
+
+#ifndef IFLA_STATS_RTA
+#define IFLA_STATS_RTA(r) \
+ ((struct rtattr *)(((char *)(r)) + NLMSG_ALIGN(sizeof(struct if_stats_msg))))
+#endif
+
+/* User defined nlmsg_type which is used mostly for logging netlink
+ * messages from dump file */
+#define NLMSG_TSTAMP 15
+
+#endif /* __LIBNETLINK_H__ */
diff --git a/include/list.h b/include/list.h
new file mode 100644
index 0000000..5d86b13
--- /dev/null
+++ b/include/list.h
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __LIST_H__
+#define __LIST_H__ 1
+/* List and hash list stuff from kernel */
+
+#include <stddef.h>
+
+#define container_of(ptr, type, member) ({ \
+ const typeof( ((type *)0)->member ) *__mptr = (ptr); \
+ (type *)( (char *)__mptr - offsetof(type,member) );})
+
+struct list_head {
+ struct list_head *next, *prev;
+};
+
+static inline void INIT_LIST_HEAD(struct list_head *list)
+{
+ list->next = list;
+ list->prev = list;
+}
+
+static inline void __list_add(struct list_head *new,
+ struct list_head *prev,
+ struct list_head *next)
+{
+ next->prev = new;
+ new->next = next;
+ new->prev = prev;
+ prev->next = new;
+}
+
+static inline void list_add(struct list_head *new, struct list_head *head)
+{
+ __list_add(new, head, head->next);
+}
+
+static inline void list_add_tail(struct list_head *new, struct list_head *head)
+{
+ __list_add(new, head->prev, head);
+}
+
+static inline void __list_del(struct list_head *prev, struct list_head *next)
+{
+ next->prev = prev;
+ prev->next = next;
+}
+
+static inline void list_del(struct list_head *entry)
+{
+ __list_del(entry->prev, entry->next);
+}
+
+#define list_entry(ptr, type, member) \
+ container_of(ptr, type, member)
+
+#define list_first_entry(ptr, type, member) \
+ list_entry((ptr)->next, type, member)
+
+#define list_last_entry(ptr, type, member) \
+ list_entry((ptr)->prev, type, member)
+
+#define list_next_entry(pos, member) \
+ list_entry((pos)->member.next, typeof(*(pos)), member)
+
+#define list_prev_entry(pos, member) \
+ list_entry((pos)->member.prev, typeof(*(pos)), member)
+
+#define list_for_each_entry(pos, head, member) \
+ for (pos = list_first_entry(head, typeof(*pos), member); \
+ &pos->member != (head); \
+ pos = list_next_entry(pos, member))
+
+#define list_for_each_entry_safe(pos, n, head, member) \
+ for (pos = list_first_entry(head, typeof(*pos), member), \
+ n = list_next_entry(pos, member); \
+ &pos->member != (head); \
+ pos = n, n = list_next_entry(n, member))
+
+#define list_for_each_entry_reverse(pos, head, member) \
+ for (pos = list_last_entry(head, typeof(*pos), member); \
+ &pos->member != (head); \
+ pos = list_prev_entry(pos, member))
+
+struct hlist_head {
+ struct hlist_node *first;
+};
+
+struct hlist_node {
+ struct hlist_node *next, **pprev;
+};
+
+static inline void hlist_del(struct hlist_node *n)
+{
+ struct hlist_node *next = n->next;
+ struct hlist_node **pprev = n->pprev;
+ *pprev = next;
+ if (next)
+ next->pprev = pprev;
+}
+
+static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
+{
+ struct hlist_node *first = h->first;
+ n->next = first;
+ if (first)
+ first->pprev = &n->next;
+ h->first = n;
+ n->pprev = &h->first;
+}
+
+static inline int list_empty(const struct list_head *head)
+{
+ return head->next == head;
+}
+
+#define hlist_for_each(pos, head) \
+ for (pos = (head)->first; pos ; pos = pos->next)
+
+
+#define hlist_for_each_safe(pos, n, head) \
+ for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \
+ pos = n)
+
+#define hlist_entry_safe(ptr, type, member) \
+ ({ typeof(ptr) ____ptr = (ptr); \
+ ____ptr ? hlist_entry(____ptr, type, member) : NULL; \
+ })
+
+#define hlist_for_each_entry(pos, head, member) \
+ for (pos = hlist_entry_safe((head)->first, typeof(*(pos)), member);\
+ pos; \
+ pos = hlist_entry_safe((pos)->member.next, typeof(*(pos)), member))
+
+#endif /* __LIST_H__ */
diff --git a/include/ll_map.h b/include/ll_map.h
new file mode 100644
index 0000000..4de1041
--- /dev/null
+++ b/include/ll_map.h
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __LL_MAP_H__
+#define __LL_MAP_H__ 1
+
+int ll_remember_index(struct nlmsghdr *n, void *arg);
+
+void ll_init_map(struct rtnl_handle *rth);
+unsigned ll_name_to_index(const char *name);
+const char *ll_index_to_name(unsigned idx);
+int ll_index_to_type(unsigned idx);
+int ll_index_to_flags(unsigned idx);
+void ll_drop_by_index(unsigned index);
+unsigned namehash(const char *str);
+
+const char *ll_idx_n2a(unsigned int idx);
+
+#endif /* __LL_MAP_H__ */
diff --git a/include/names.h b/include/names.h
new file mode 100644
index 0000000..2fcaacc
--- /dev/null
+++ b/include/names.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef DB_NAMES_H_
+#define DB_NAMES_H_ 1
+
+#define IDNAME_MAX 256
+
+struct db_entry {
+ struct db_entry *next;
+ unsigned int id;
+ char *name;
+};
+
+struct db_names {
+ unsigned int size;
+ struct db_entry *cached;
+ struct db_entry **hash;
+ int max;
+};
+
+struct db_names *db_names_alloc(void);
+int db_names_load(struct db_names *db, const char *path);
+void db_names_free(struct db_names *db);
+
+char *id_to_name(struct db_names *db, int id, char *name);
+
+#endif
diff --git a/include/namespace.h b/include/namespace.h
new file mode 100644
index 0000000..e47f9b5
--- /dev/null
+++ b/include/namespace.h
@@ -0,0 +1,61 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __NAMESPACE_H__
+#define __NAMESPACE_H__ 1
+
+#include <sched.h>
+#include <sys/mount.h>
+#include <unistd.h>
+#include <sys/syscall.h>
+#include <errno.h>
+
+#ifndef NETNS_RUN_DIR
+#define NETNS_RUN_DIR "/var/run/netns"
+#endif
+
+#ifndef NETNS_ETC_DIR
+#define NETNS_ETC_DIR "/etc/netns"
+#endif
+
+#ifndef CLONE_NEWNET
+#define CLONE_NEWNET 0x40000000 /* New network namespace (lo, device, names sockets, etc) */
+#endif
+
+#ifndef MNT_DETACH
+#define MNT_DETACH 0x00000002 /* Just detach from the tree */
+#endif /* MNT_DETACH */
+
+/* sys/mount.h may be out too old to have these */
+#ifndef MS_REC
+#define MS_REC 16384
+#endif
+
+#ifndef MS_SLAVE
+#define MS_SLAVE (1 << 19)
+#endif
+
+#ifndef MS_SHARED
+#define MS_SHARED (1 << 20)
+#endif
+
+#ifndef HAVE_SETNS
+static inline int setns(int fd, int nstype)
+{
+#ifdef __NR_setns
+ return syscall(__NR_setns, fd, nstype);
+#else
+ errno = ENOSYS;
+ return -1;
+#endif
+}
+#endif /* HAVE_SETNS */
+
+int netns_switch(char *netns);
+int netns_get_fd(const char *netns);
+int netns_foreach(int (*func)(char *nsname, void *arg), void *arg);
+
+struct netns_func {
+ int (*func)(char *nsname, void *arg);
+ void *arg;
+};
+
+#endif /* __NAMESPACE_H__ */
diff --git a/include/netinet/tcp.h b/include/netinet/tcp.h
new file mode 100644
index 0000000..3f890a1
--- /dev/null
+++ b/include/netinet/tcp.h
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 1982, 1986, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)tcp.h 8.1 (Berkeley) 6/10/93
+ */
+
+#ifndef _NETINET_TCP_H
+#define _NETINET_TCP_H 1
+
+#include <features.h>
+
+/*
+ * User-settable options (used with setsockopt).
+ */
+#define TCP_NODELAY 1 /* Don't delay send to coalesce packets */
+#define TCP_MAXSEG 2 /* Set maximum segment size */
+#define TCP_CORK 3 /* Control sending of partial frames */
+#define TCP_KEEPIDLE 4 /* Start keeplives after this period */
+#define TCP_KEEPINTVL 5 /* Interval between keepalives */
+#define TCP_KEEPCNT 6 /* Number of keepalives before death */
+#define TCP_SYNCNT 7 /* Number of SYN retransmits */
+#define TCP_LINGER2 8 /* Life time of orphaned FIN-WAIT-2 state */
+#define TCP_DEFER_ACCEPT 9 /* Wake up listener only when data arrive */
+#define TCP_WINDOW_CLAMP 10 /* Bound advertised window */
+#define TCP_INFO 11 /* Information about this connection. */
+#define TCP_QUICKACK 12 /* Bock/reenable quick ACKs. */
+#define TCP_CONGESTION 13 /* Congestion control algorithm. */
+
+#ifdef __USE_MISC
+# include <sys/types.h>
+
+# ifdef __FAVOR_BSD
+typedef u_int32_t tcp_seq;
+/*
+ * TCP header.
+ * Per RFC 793, September, 1981.
+ */
+struct tcphdr
+ {
+ u_int16_t th_sport; /* source port */
+ u_int16_t th_dport; /* destination port */
+ tcp_seq th_seq; /* sequence number */
+ tcp_seq th_ack; /* acknowledgement number */
+# if __BYTE_ORDER == __LITTLE_ENDIAN
+ u_int8_t th_x2:4; /* (unused) */
+ u_int8_t th_off:4; /* data offset */
+# endif
+# if __BYTE_ORDER == __BIG_ENDIAN
+ u_int8_t th_off:4; /* data offset */
+ u_int8_t th_x2:4; /* (unused) */
+# endif
+ u_int8_t th_flags;
+# define TH_FIN 0x01
+# define TH_SYN 0x02
+# define TH_RST 0x04
+# define TH_PUSH 0x08
+# define TH_ACK 0x10
+# define TH_URG 0x20
+ u_int16_t th_win; /* window */
+ u_int16_t th_sum; /* checksum */
+ u_int16_t th_urp; /* urgent pointer */
+};
+
+# else /* !__FAVOR_BSD */
+struct tcphdr
+ {
+ u_int16_t source;
+ u_int16_t dest;
+ u_int32_t seq;
+ u_int32_t ack_seq;
+# if __BYTE_ORDER == __LITTLE_ENDIAN
+ u_int16_t res1:4;
+ u_int16_t doff:4;
+ u_int16_t fin:1;
+ u_int16_t syn:1;
+ u_int16_t rst:1;
+ u_int16_t psh:1;
+ u_int16_t ack:1;
+ u_int16_t urg:1;
+ u_int16_t res2:2;
+# elif __BYTE_ORDER == __BIG_ENDIAN
+ u_int16_t doff:4;
+ u_int16_t res1:4;
+ u_int16_t res2:2;
+ u_int16_t urg:1;
+ u_int16_t ack:1;
+ u_int16_t psh:1;
+ u_int16_t rst:1;
+ u_int16_t syn:1;
+ u_int16_t fin:1;
+# else
+# error "Adjust your <bits/endian.h> defines"
+# endif
+ u_int16_t window;
+ u_int16_t check;
+ u_int16_t urg_ptr;
+};
+# endif /* __FAVOR_BSD */
+
+enum
+{
+ TCP_ESTABLISHED = 1,
+ TCP_SYN_SENT,
+ TCP_SYN_RECV,
+ TCP_FIN_WAIT1,
+ TCP_FIN_WAIT2,
+ TCP_TIME_WAIT,
+ TCP_CLOSE,
+ TCP_CLOSE_WAIT,
+ TCP_LAST_ACK,
+ TCP_LISTEN,
+ TCP_CLOSING /* now a valid state */
+};
+
+# define TCPOPT_EOL 0
+# define TCPOPT_NOP 1
+# define TCPOPT_MAXSEG 2
+# define TCPOLEN_MAXSEG 4
+# define TCPOPT_WINDOW 3
+# define TCPOLEN_WINDOW 3
+# define TCPOPT_SACK_PERMITTED 4 /* Experimental */
+# define TCPOLEN_SACK_PERMITTED 2
+# define TCPOPT_SACK 5 /* Experimental */
+# define TCPOPT_TIMESTAMP 8
+# define TCPOLEN_TIMESTAMP 10
+# define TCPOLEN_TSTAMP_APPA (TCPOLEN_TIMESTAMP+2) /* appendix A */
+
+# define TCPOPT_TSTAMP_HDR \
+ (TCPOPT_NOP<<24|TCPOPT_NOP<<16|TCPOPT_TIMESTAMP<<8|TCPOLEN_TIMESTAMP)
+
+/*
+ * Default maximum segment size for TCP.
+ * With an IP MSS of 576, this is 536,
+ * but 512 is probably more convenient.
+ * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)).
+ */
+# define TCP_MSS 512
+
+# define TCP_MAXWIN 65535 /* largest value for (unscaled) window */
+
+# define TCP_MAX_WINSHIFT 14 /* maximum window shift */
+
+# define SOL_TCP 6 /* TCP level */
+
+
+# define TCPI_OPT_TIMESTAMPS 1
+# define TCPI_OPT_SACK 2
+# define TCPI_OPT_WSCALE 4
+# define TCPI_OPT_ECN 8
+# define TCPI_OPT_ECN_SEEN 16
+
+/* Values for tcpi_state. */
+enum tcp_ca_state
+{
+ TCP_CA_Open = 0,
+ TCP_CA_Disorder = 1,
+ TCP_CA_CWR = 2,
+ TCP_CA_Recovery = 3,
+ TCP_CA_Loss = 4
+};
+
+struct tcp_info
+{
+ u_int8_t tcpi_state;
+ u_int8_t tcpi_ca_state;
+ u_int8_t tcpi_retransmits;
+ u_int8_t tcpi_probes;
+ u_int8_t tcpi_backoff;
+ u_int8_t tcpi_options;
+ u_int8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4;
+
+ u_int32_t tcpi_rto;
+ u_int32_t tcpi_ato;
+ u_int32_t tcpi_snd_mss;
+ u_int32_t tcpi_rcv_mss;
+
+ u_int32_t tcpi_unacked;
+ u_int32_t tcpi_sacked;
+ u_int32_t tcpi_lost;
+ u_int32_t tcpi_retrans;
+ u_int32_t tcpi_fackets;
+
+ /* Times. */
+ u_int32_t tcpi_last_data_sent;
+ u_int32_t tcpi_last_ack_sent; /* Not remembered, sorry. */
+ u_int32_t tcpi_last_data_recv;
+ u_int32_t tcpi_last_ack_recv;
+
+ /* Metrics. */
+ u_int32_t tcpi_pmtu;
+ u_int32_t tcpi_rcv_ssthresh;
+ u_int32_t tcpi_rtt;
+ u_int32_t tcpi_rttvar;
+ u_int32_t tcpi_snd_ssthresh;
+ u_int32_t tcpi_snd_cwnd;
+ u_int32_t tcpi_advmss;
+ u_int32_t tcpi_reordering;
+ u_int32_t tcpi_rcv_rtt;
+ u_int32_t tcpi_rcv_space;
+ u_int32_t tcpi_total_retrans;
+
+};
+
+#endif /* Misc. */
+
+#endif /* netinet/tcp.h */
diff --git a/include/rt_names.h b/include/rt_names.h
new file mode 100644
index 0000000..62ebbd6
--- /dev/null
+++ b/include/rt_names.h
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef RT_NAMES_H_
+#define RT_NAMES_H_ 1
+
+#include <asm/types.h>
+
+const char *rtnl_rtprot_n2a(int id, char *buf, int len);
+const char *rtnl_rtscope_n2a(int id, char *buf, int len);
+const char *rtnl_rttable_n2a(__u32 id, char *buf, int len);
+const char *rtnl_rtrealm_n2a(int id, char *buf, int len);
+const char *rtnl_dsfield_n2a(int id, char *buf, int len);
+const char *rtnl_group_n2a(int id, char *buf, int len);
+
+int rtnl_rtprot_a2n(__u32 *id, const char *arg);
+int rtnl_rtscope_a2n(__u32 *id, const char *arg);
+int rtnl_rttable_a2n(__u32 *id, const char *arg);
+int rtnl_rtrealm_a2n(__u32 *id, const char *arg);
+int rtnl_dsfield_a2n(__u32 *id, const char *arg);
+int rtnl_group_a2n(int *id, const char *arg);
+
+const char *inet_proto_n2a(int proto, char *buf, int len);
+int inet_proto_a2n(const char *buf);
+
+
+const char * ll_type_n2a(int type, char *buf, int len);
+const char *ll_addr_n2a(const unsigned char *addr, int alen,
+ int type, char *buf, int blen);
+int ll_addr_a2n(char *lladdr, int len, const char *arg);
+
+const char * ll_proto_n2a(unsigned short id, ch