メインコンテンツへスキップ

セキュリティ・キャンプ2025 Y2 CDN自作ゼミ 応募課題さらし Linuxの調査ログ

·6549 文字·31 分·
応募課題 コードリーディング Linux C言語
著者
on-keyday
隠者

Copyright (C) 2025 on-keyday

This work 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 work 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 work; if not, see https://www.gnu.org/licenses/ .

Please contact: on-keyday (https://mixi.social/@onkeyday ) for inquiries.

Linux部分の調査ログが著作権法における引用という条件を満たせるかどうかが怪しい気がしているため、 本記事について明示的にGPL version 2の下に置きGPL派生作品としての立場を明確にする。(それ言ったら前のいくつかの記事もそうかもしれんのでもし該当しそうであれば遠慮なく https://mixi.social/@onkeyday までお知らせください。ソースコード出します)

ソースコードに当たるmarkdownファイルは以下に配置してある。

ソースコード

https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.en

GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
<https://fsf.org/>
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 Lesser 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.

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 an idea of what it does.
Copyright (C) yyyy  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, see
<https://www.gnu.org/licenses/>.
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 Moe Ghoul, 1 April 1989
Moe Ghoul, 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 Lesser General Public License instead of this License.

以下からが本文である。

6. 宛先のOSレイヤー(Linux)
#

調査の都合の良いように宛先のサーバーはLinuxで動いているものと仮定する。またネットワークデバイスをiceデバイスドライバのものとして仮定する。 またコードについては提出時点で最新のものを参照したためバージョンがちがう可能性は十分にある(というよりおそらくこのバージョンではないことは確かである) https://github.com/torvalds/linux/tree/5b032cac622533631b8f9b7826498b7ce75001c6

まずiceデバイスはここに定義される。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L5913C1-L5925C1

static struct pci_driver ice_driver = {
	.name = KBUILD_MODNAME,
	.id_table = ice_pci_tbl,
	.probe = ice_probe,
	.remove = ice_remove,
	.driver.pm = pm_sleep_ptr(&ice_pm_ops),
	.shutdown = ice_shutdown,
	.sriov_configure = ice_sriov_configure,
	.sriov_get_vf_total_msix = ice_sriov_get_vf_total_msix,
	.sriov_set_msix_vec_count = ice_sriov_set_msix_vec_count,
	.err_handler = &ice_pci_err_handler
};

デバイス起動時には以下ルーチンが呼ばれる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L5239C1-L5249C1

/**
 * ice_probe - Device initialization routine
 * @pdev: PCI device information struct
 * @ent: entry in ice_pci_tbl
 *
 * Returns 0 on success, negative on failure
 */
static int
ice_probe(struct pci_dev *pdev, const struct pci_device_id __always_unused *ent)

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L5351 ice_probe内からice_loadが呼ばれ https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L5125

/**
 * ice_load - load pf by init hw and starting VSI
 * @pf: pointer to the pf instance
 *
 * This function has to be called under devl_lock.
 */
int ice_load(struct ice_pf *pf)

ここで実際の受信処理ice_napi_pollが登録される。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L2845

  /**
 * ice_napi_add - register NAPI handler for the VSI
 * @vsi: VSI for which NAPI handler is to be registered
 *
 * This function is only called in the driver's load path. Registering the NAPI
 * handler is done in ice_vsi_alloc_q_vector() for all other cases (i.e. resume,
 * reset/rebuild, etc.)
 */
void ice_napi_add(struct ice_vsi *vsi)
{
	int v_idx;

	if (!vsi->netdev)
		return;

	ice_for_each_q_vector(vsi, v_idx)
		netif_napi_add_config(vsi->netdev,
				      &vsi->q_vectors[v_idx]->napi,
				      ice_napi_poll,
				      v_idx);
}

netif_napi_add_configは最終的にここに行き着く。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L7242

void netif_napi_add_weight_locked(struct net_device *dev,
				  struct napi_struct *napi,
				  int (*poll)(struct napi_struct *, int),
				  int weight)
{
	netdev_assert_locked(dev);
	if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
		return;

	INIT_LIST_HEAD(&napi->poll_list);
	INIT_HLIST_NODE(&napi->napi_hash_node);
	hrtimer_setup(&napi->timer, napi_watchdog, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
	gro_init(&napi->gro);
	napi->skb = NULL;
	napi->poll = poll;
	if (weight > NAPI_POLL_WEIGHT)
		netdev_err_once(dev, "%s() called with weight %d\n", __func__,
				weight);
	napi->weight = weight;
	napi->dev = dev;
#ifdef CONFIG_NETPOLL
	napi->poll_owner = -1;
#endif
	napi->list_owner = -1;
	set_bit(NAPI_STATE_SCHED, &napi->state);
	set_bit(NAPI_STATE_NPSVC, &napi->state);
	netif_napi_dev_list_add(dev, napi);

	/* default settings from sysfs are applied to all NAPIs. any per-NAPI
	 * configuration will be loaded in napi_enable
	 */
	napi_set_defer_hard_irqs(napi, READ_ONCE(dev->napi_defer_hard_irqs));
	napi_set_gro_flush_timeout(napi, READ_ONCE(dev->gro_flush_timeout));

	napi_get_frags_check(napi);
	/* Create kthread for this napi if dev->threaded is set.
	 * Clear dev->threaded if kthread creation failed so that
	 * threaded mode will not be enabled in napi_enable().
	 */
	if (dev->threaded && napi_kthread_create(napi))
		dev->threaded = false;
	netif_napi_set_irq_locked(napi, -1);
}
EXPORT_SYMBOL(netif_napi_add_weight_locked);

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L7199

/* Netlink wants the NAPI list to be sorted by ID, if adding a NAPI which will
 * inherit an existing ID try to insert it at the right position.
 */
static void
netif_napi_dev_list_add(struct net_device *dev, struct napi_struct *napi)
{
	unsigned int new_id, pos_id;
	struct list_head *higher;
	struct napi_struct *pos;

	new_id = UINT_MAX;
	if (napi->config && napi->config->napi_id)
		new_id = napi->config->napi_id;

	higher = &dev->napi_list;
	list_for_each_entry(pos, &dev->napi_list, dev_list) {
		if (napi_id_valid(pos->napi_id))
			pos_id = pos->napi_id;
		else if (pos->config)
			pos_id = pos->config->napi_id;
		else
			pos_id = UINT_MAX;

		if (pos_id <= new_id)
			break;
		higher = &pos->dev_list;
	}
	list_add_rcu(&napi->dev_list, higher); /* adds after higher */
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/linux/rculist.h#L87

/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_add_rcu(struct list_head *new,
		struct list_head *prev, struct list_head *next)
{
	if (!__list_add_valid(new, prev, next))
		return;

	new->next = next;
	new->prev = prev;
	rcu_assign_pointer(list_next_rcu(prev), new);
	next->prev = new;
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/linux/rcupdate.h#L557C1-L599C1

/**
 * rcu_assign_pointer() - assign to RCU-protected pointer
 * @p: pointer to assign to
 * @v: value to assign (publish)
 *
 * Assigns the specified value to the specified RCU-protected
 * pointer, ensuring that any concurrent RCU readers will see
 * any prior initialization.
 *
 * Inserts memory barriers on architectures that require them
 * (which is most of them), and also prevents the compiler from
 * reordering the code that initializes the structure after the pointer
 * assignment.  More importantly, this call documents which pointers
 * will be dereferenced by RCU read-side code.
 *
 * In some special cases, you may use RCU_INIT_POINTER() instead
 * of rcu_assign_pointer().  RCU_INIT_POINTER() is a bit faster due
 * to the fact that it does not constrain either the CPU or the compiler.
 * That said, using RCU_INIT_POINTER() when you should have used
 * rcu_assign_pointer() is a very bad thing that results in
 * impossible-to-diagnose memory corruption.  So please be careful.
 * See the RCU_INIT_POINTER() comment header for details.
 *
 * Note that rcu_assign_pointer() evaluates each of its arguments only
 * once, appearances notwithstanding.  One of the "extra" evaluations
 * is in typeof() and the other visible only to sparse (__CHECKER__),
 * neither of which actually execute the argument.  As with most cpp
 * macros, this execute-arguments-only-once property is important, so
 * please be careful when making changes to rcu_assign_pointer() and the
 * other macros that it invokes.
 */
#define rcu_assign_pointer(p, v)					      \
do {									      \
	uintptr_t _r_a_p__v = (uintptr_t)(v);				      \
	rcu_check_sparse(p, __rcu);					      \
									      \
	if (__builtin_constant_p(v) && (_r_a_p__v) == (uintptr_t)NULL)	      \
		WRITE_ONCE((p), (typeof(p))(_r_a_p__v));		      \
	else								      \
		smp_store_release(&p, RCU_INITIALIZER((typeof(p))_r_a_p__v)); \
} while (0)

https://vh21.github.io/linux/2015/04/25/linux-barrier-api.html https://lwn.net/Articles/576486/

RCUによって並列で読み書きができるようになっている。 https://zenn.dev/labbase_sano/articles/c690f9e9539bf4

napi_scheduleを登録するまでの流れ https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L4963 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L4963 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_main.c#L3689 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L2558 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L2469 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L2316 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L580

登録されている関数 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_lib.c#L499

/**
 * ice_msix_clean_rings - MSIX mode Interrupt Handler
 * @irq: interrupt number
 * @data: pointer to a q_vector
 */
static irqreturn_t ice_msix_clean_rings(int __always_unused irq, void *data)
{
	struct ice_q_vector *q_vector = (struct ice_q_vector *)data;

	if (!q_vector->tx.tx_ring && !q_vector->rx.rx_ring)
		return IRQ_HANDLED;

	q_vector->total_events++;

	napi_schedule(&q_vector->napi);

	return IRQ_HANDLED;
}

NAPI Schedule https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/linux/netdevice.h#L552

/**
 *	napi_schedule - schedule NAPI poll
 *	@n: NAPI context
 *
 * Schedule NAPI poll routine to be called if it is not already
 * running.
 * Return: true if we schedule a NAPI or false if not.
 * Refer to napi_schedule_prep() for additional reason on why
 * a NAPI might not be scheduled.
 */
static inline bool napi_schedule(struct napi_struct *n)
{
	if (napi_schedule_prep(n)) {
		__napi_schedule(n);
		return true;
	}

	return false;
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L6494

/**
 * __napi_schedule - schedule for receive
 * @n: entry to schedule
 *
 * The entry's receive function will be scheduled to run.
 * Consider using __napi_schedule_irqoff() if hard irqs are masked.
 */
void __napi_schedule(struct napi_struct *n)
{
	unsigned long flags;

	local_irq_save(flags);
	____napi_schedule(this_cpu_ptr(&softnet_data), n);
	local_irq_restore(flags);
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L4792

/* Called with irq disabled */
static inline void ____napi_schedule(struct softnet_data *sd,
				     struct napi_struct *napi)
{
	struct task_struct *thread;

	lockdep_assert_irqs_disabled();

	if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
		/* Paired with smp_mb__before_atomic() in
		 * napi_enable()/dev_set_threaded().
		 * Use READ_ONCE() to guarantee a complete
		 * read on napi->thread. Only call
		 * wake_up_process() when it's not NULL.
		 */
		thread = READ_ONCE(napi->thread);
		if (thread) {
			if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi))
				goto use_local_napi;

			set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
			wake_up_process(thread);
			return;
		}
	}

use_local_napi:
	DEBUG_NET_WARN_ON_ONCE(!list_empty(&napi->poll_list));
	list_add_tail(&napi->poll_list, &sd->poll_list);
	WRITE_ONCE(napi->list_owner, smp_processor_id());
	/* If not called from net_rx_action()
	 * we have to raise NET_RX_SOFTIRQ.
	 */
	if (!sd->in_net_rx_action)
		raise_softirq_irqoff(NET_RX_SOFTIRQ);
}

スレッドを使う場合はおそらくこちらを延々と実行しており、wake_up_processするとこちらに処理が移る。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L7560

static int napi_threaded_poll(void *data)
{
	struct napi_struct *napi = data;

	while (!napi_thread_wait(napi))
		napi_threaded_poll_loop(napi);

	return 0;
}

napi_threaded_poll_loopから__napi_pollが呼ばれそして最終的にここでpollingがなされる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L7414

static int __napi_poll(struct napi_struct *n, bool *repoll)
{
	int work, weight;

	weight = n->weight;

	/* This NAPI_STATE_SCHED test is for avoiding a race
	 * with netpoll's poll_napi().  Only the entity which
	 * obtains the lock and sees NAPI_STATE_SCHED set will
	 * actually make the ->poll() call.  Therefore we avoid
	 * accidentally calling ->poll() when NAPI is not scheduled.
	 */
	work = 0;
	if (napi_is_scheduled(n)) {
		work = n->poll(n, weight);
		trace_napi_poll(n, work, weight);

		xdp_do_check_flushed(n);
	}

	if (unlikely(work > weight))
		netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
				n->poll, work, weight);

	if (likely(work < weight))
		return work;

	/* Drivers must not modify the NAPI state if they
	 * consume the entire weight.  In such cases this code
	 * still "owns" the NAPI instance and therefore can
	 * move the instance around on the list at-will.
	 */
	if (unlikely(napi_disable_pending(n))) {
		napi_complete(n);
		return work;
	}

	/* The NAPI context has more processing work, but busy-polling
	 * is preferred. Exit early.
	 */
	if (napi_prefer_busy_poll(n)) {
		if (napi_complete_done(n, work)) {
			/* If timeout is not set, we need to make sure
			 * that the NAPI is re-scheduled.
			 */
			napi_schedule(n);
		}
		return work;
	}

	/* Flush too old packets. If HZ < 1000, flush all packets */
	gro_flush(&n->gro, HZ >= 1000);
	gro_normal_list(&n->gro);

	/* Some drivers may have called napi_schedule
	 * prior to exhausting their budget.
	 */
	if (unlikely(!list_empty(&n->poll_list))) {
		pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
			     n->dev ? n->dev->name : "backlog");
		return work;
	}

	*repoll = true;

	return work;
}

n->pollの実態ice_napi_pollは以下。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_txrx.c#L1527

/**
 * ice_napi_poll - NAPI polling Rx/Tx cleanup routine
 * @napi: napi struct with our devices info in it
 * @budget: amount of work driver is allowed to do this pass, in packets
 *
 * This function will clean all queues associated with a q_vector.
 *
 * Returns the amount of work done
 */
int ice_napi_poll(struct napi_struct *napi, int budget)

特に以下のところで受信処理が走っているようである。

ice_for_each_rx_ring(rx_ring, q_vector->rx) {
		struct xsk_buff_pool *xsk_pool = READ_ONCE(rx_ring->xsk_pool);
		int cleaned;

		/* A dedicated path for zero-copy allows making a single
		 * comparison in the irq context instead of many inside the
		 * ice_clean_rx_irq function and makes the codebase cleaner.
		 */
		cleaned = rx_ring->xsk_pool ?
			  ice_clean_rx_irq_zc(rx_ring, xsk_pool, budget_per_ring) :
			  ice_clean_rx_irq(rx_ring, budget_per_ring);
		work_done += cleaned;
		/* if we clean as many as budgeted, we must not be done */
		if (cleaned >= budget_per_ring)
			clean_complete = false;
	}

とりあえずzero-copy版を追ってみる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_xsk.c#L813

/**
 * ice_clean_rx_irq_zc - consumes packets from the hardware ring
 * @rx_ring: AF_XDP Rx ring
 * @xsk_pool: AF_XDP buffer pool pointer
 * @budget: NAPI budget
 *
 * Returns number of processed packets on success, remaining budget on failure.
 */
int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring,
			struct xsk_buff_pool *xsk_pool,
			int budget)

まずXDPでbpfプログラムが走るなどしている。

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_xsk.c#L761

/**
 * ice_run_xdp_zc - Executes an XDP program in zero-copy path
 * @rx_ring: Rx ring
 * @xdp: xdp_buff used as input to the XDP program
 * @xdp_prog: XDP program to run
 * @xdp_ring: ring to be used for XDP_TX action
 * @xsk_pool: AF_XDP buffer pool pointer
 *
 * Returns any of ICE_XDP_{PASS, CONSUMED, TX, REDIR}
 */
static int
ice_run_xdp_zc(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp,
	       struct bpf_prog *xdp_prog, struct ice_tx_ring *xdp_ring,
	       struct xsk_buff_pool *xsk_pool)
{
	int err, result = ICE_XDP_PASS;
	u32 act;

	act = bpf_prog_run_xdp(xdp_prog, xdp);

	if (likely(act == XDP_REDIRECT)) {
		err = xdp_do_redirect(rx_ring->netdev, xdp, xdp_prog);
		if (!err)
			return ICE_XDP_REDIR;
		if (xsk_uses_need_wakeup(xsk_pool) && err == -ENOBUFS)
			result = ICE_XDP_EXIT;
		else
			result = ICE_XDP_CONSUMED;
		goto out_failure;
	}

	switch (act) {
	case XDP_PASS:
		break;
	case XDP_TX:
		result = ice_xmit_xdp_tx_zc(xdp, xdp_ring, xsk_pool);
		if (result == ICE_XDP_CONSUMED)
			goto out_failure;
		break;
	case XDP_DROP:
		result = ICE_XDP_CONSUMED;
		break;
	default:
		bpf_warn_invalid_xdp_action(rx_ring->netdev, xdp_prog, act);
		fallthrough;
	case XDP_ABORTED:
		result = ICE_XDP_CONSUMED;
out_failure:
		trace_xdp_exception(rx_ring->netdev, xdp_prog, act);
		break;
	}

	return result;
}

その後sk_buffの構築が行われている。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_xsk.c#L550

/**
 * ice_construct_skb_zc - Create an sk_buff from zero-copy buffer
 * @rx_ring: Rx ring
 * @xdp: Pointer to XDP buffer
 *
 * This function allocates a new skb from a zero-copy Rx buffer.
 *
 * Returns the skb on success, NULL on failure.
 */
static struct sk_buff *
ice_construct_skb_zc(struct ice_rx_ring *rx_ring, struct xdp_buff *xdp)
{
	unsigned int totalsize = xdp->data_end - xdp->data_meta;
	unsigned int metasize = xdp->data - xdp->data_meta;
	struct skb_shared_info *sinfo = NULL;
	struct sk_buff *skb;
	u32 nr_frags = 0;

	if (unlikely(xdp_buff_has_frags(xdp))) {
		sinfo = xdp_get_shared_info_from_buff(xdp);
		nr_frags = sinfo->nr_frags;
	}
	net_prefetch(xdp->data_meta);

	skb = napi_alloc_skb(&rx_ring->q_vector->napi, totalsize);
	if (unlikely(!skb))
		return NULL;

	memcpy(__skb_put(skb, totalsize), xdp->data_meta,
	       ALIGN(totalsize, sizeof(long)));

	if (metasize) {
		skb_metadata_set(skb, metasize);
		__skb_pull(skb, metasize);
	}

	if (likely(!xdp_buff_has_frags(xdp)))
		goto out;

	for (int i = 0; i < nr_frags; i++) {
		struct skb_shared_info *skinfo = skb_shinfo(skb);
		skb_frag_t *frag = &sinfo->frags[i];
		struct page *page;
		void *addr;

		page = dev_alloc_page();
		if (!page) {
			dev_kfree_skb(skb);
			return NULL;
		}
		addr = page_to_virt(page);

		memcpy(addr, skb_frag_page(frag), skb_frag_size(frag));

		__skb_fill_page_desc_noacc(skinfo, skinfo->nr_frags++,
					   addr, 0, skb_frag_size(frag));
	}

out:
	xsk_buff_free(xdp);
	return skb;
}

最終的にnapi_gro_receiveに送られている。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/drivers/net/ethernet/intel/ice/ice_txrx_lib.c#L254

/**
 * ice_receive_skb - Send a completed packet up the stack
 * @rx_ring: Rx ring in play
 * @skb: packet to send up
 * @vlan_tci: VLAN TCI for packet
 *
 * This function sends the completed packet (via. skb) up the stack using
 * gro receive functions (with/without VLAN tag)
 */
void
ice_receive_skb(struct ice_rx_ring *rx_ring, struct sk_buff *skb, u16 vlan_tci)
{
	if ((vlan_tci & VLAN_VID_MASK) && rx_ring->vlan_proto)
		__vlan_hwaccel_put_tag(skb, rx_ring->vlan_proto,
				       vlan_tci);

	napi_gro_receive(&rx_ring->q_vector->napi, skb);
}

napi_gro_receiveはgro_receive_skbを呼び出している https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/gro.c#L596

gro_result_t gro_receive_skb(struct gro_node *gro, struct sk_buff *skb)

gro_receive_skbはgro_normal_oneを呼び出す。受信パケット数が閾値を超えたらバッチ処理を開始するようだ。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/net/gro.h#L540

/* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
 * pass the whole batch up to the stack.
 */
static inline void gro_normal_one(struct gro_node *gro, struct sk_buff *skb,
				  int segs)
{
	list_add_tail(&skb->list, &gro->rx_list);
	gro->rx_count += segs;
	if (gro->rx_count >= READ_ONCE(net_hotdata.gro_normal_batch))
		gro_normal_list(gro);
}

netif_receive_skb_list_internalに渡される。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/net/gro.h#L528

/* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
static inline void gro_normal_list(struct gro_node *gro)
{
	if (!gro->rx_count)
		return;
	netif_receive_skb_list_internal(&gro->rx_list);
	INIT_LIST_HEAD(&gro->rx_list);
	gro->rx_count = 0;
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L6181

void netif_receive_skb_list_internal(struct list_head *head)
{
	struct sk_buff *skb, *next;
	LIST_HEAD(sublist);

	list_for_each_entry_safe(skb, next, head, list) {
		net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
				    skb);
		skb_list_del_init(skb);
		if (!skb_defer_rx_timestamp(skb))
			list_add_tail(&skb->list, &sublist);
	}
	list_splice_init(&sublist, head);

	rcu_read_lock();
#ifdef CONFIG_RPS
	if (static_branch_unlikely(&rps_needed)) {
		list_for_each_entry_safe(skb, next, head, list) {
			struct rps_dev_flow voidflow, *rflow = &voidflow;
			int cpu = get_rps_cpu(skb->dev, skb, &rflow);

			if (cpu >= 0) {
				/* Will be handled, remove from list */
				skb_list_del_init(skb);
				enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
			}
		}
	}
#endif
	__netif_receive_skb_list(head);
	rcu_read_unlock();
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L6095

static void __netif_receive_skb_list(struct list_head *head)
{
	unsigned long noreclaim_flag = 0;
	struct sk_buff *skb, *next;
	bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */

	list_for_each_entry_safe(skb, next, head, list) {
		if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
			struct list_head sublist;

			/* Handle the previous sublist */
			list_cut_before(&sublist, head, &skb->list);
			if (!list_empty(&sublist))
				__netif_receive_skb_list_core(&sublist, pfmemalloc);
			pfmemalloc = !pfmemalloc;
			/* See comments in __netif_receive_skb */
			if (pfmemalloc)
				noreclaim_flag = memalloc_noreclaim_save();
			else
				memalloc_noreclaim_restore(noreclaim_flag);
		}
	}
	/* Handle the remaining sublist */
	if (!list_empty(head))
		__netif_receive_skb_list_core(head, pfmemalloc);
	/* Restore pflags */
	if (pfmemalloc)
		memalloc_noreclaim_restore(noreclaim_flag);
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L6029

static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
{
	/* Fast-path assumptions:
	 * - There is no RX handler.
	 * - Only one packet_type matches.
	 * If either of these fails, we will end up doing some per-packet
	 * processing in-line, then handling the 'last ptype' for the whole
	 * sublist.  This can't cause out-of-order delivery to any single ptype,
	 * because the 'last ptype' must be constant across the sublist, and all
	 * other ptypes are handled per-packet.
	 */
	/* Current (common) ptype of sublist */
	struct packet_type *pt_curr = NULL;
	/* Current (common) orig_dev of sublist */
	struct net_device *od_curr = NULL;
	struct sk_buff *skb, *next;
	LIST_HEAD(sublist);

	list_for_each_entry_safe(skb, next, head, list) {
		struct net_device *orig_dev = skb->dev;
		struct packet_type *pt_prev = NULL;

		skb_list_del_init(skb);
		__netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
		if (!pt_prev)
			continue;
		if (pt_curr != pt_prev || od_curr != orig_dev) {
			/* dispatch old sublist */
			__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
			/* start new sublist */
			INIT_LIST_HEAD(&sublist);
			pt_curr = pt_prev;
			od_curr = orig_dev;
		}
		list_add_tail(&skb->list, &sublist);
	}

	/* dispatch final sublist */
	__netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
}

そしてここでバッチ受信処理が呼ばれている。ipv6_list_rcv及びip_list_rcvは特に直接呼び出しになるように最適化を図っているようだ。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/core/dev.c#L6009

static inline void __netif_receive_skb_list_ptype(struct list_head *head,
						  struct packet_type *pt_prev,
						  struct net_device *orig_dev)
{
	struct sk_buff *skb, *next;

	if (!pt_prev)
		return;
	if (list_empty(head))
		return;
	if (pt_prev->list_func != NULL)
		INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
				   ip_list_rcv, head, pt_prev, orig_dev);
	else
		list_for_each_entry_safe(skb, next, head, list) {
			skb_list_del_init(skb);
			pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
		}
}

まとめて受信処理を行い同じデバイス、同じネットワーク名前空間のパケットについてはまとめて処理を行う工夫が見られる。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/ip_input.c#L639

/* Receive a list of IP packets */
void ip_list_rcv(struct list_head *head, struct packet_type *pt,
		 struct net_device *orig_dev)
{
	struct net_device *curr_dev = NULL;
	struct net *curr_net = NULL;
	struct sk_buff *skb, *next;
	LIST_HEAD(sublist);

	list_for_each_entry_safe(skb, next, head, list) {
		struct net_device *dev = skb->dev;
		struct net *net = dev_net(dev);

		skb_list_del_init(skb);
		skb = ip_rcv_core(skb, net);
		if (skb == NULL)
			continue;

		if (curr_dev != dev || curr_net != net) {
			/* dispatch old sublist */
			if (!list_empty(&sublist))
				ip_sublist_rcv(&sublist, curr_dev, curr_net);
			/* start new sublist */
			INIT_LIST_HEAD(&sublist);
			curr_dev = dev;
			curr_net = net;
		}
		list_add_tail(&skb->list, &sublist);
	}
	/* dispatch final sublist */
	if (!list_empty(&sublist))
		ip_sublist_rcv(&sublist, curr_dev, curr_net);
}

https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/linux/indirect_call_wrapper.h#L56

/*
 * INDIRECT_CALL_$NR - wrapper for indirect calls with $NR known builtin
 *  @f: function pointer
 *  @f$NR: builtin functions names, up to $NR of them
 *  @__VA_ARGS__: arguments for @f
 *
 * Avoid retpoline overhead for known builtin, checking @f vs each of them and
 * eventually invoking directly the builtin function. The functions are checked
 * in the given order. Fallback to the indirect call.
 */
#define INDIRECT_CALL_1(f, f1, ...)					\
	({								\
		likely(f == f1) ? f1(__VA_ARGS__) : f(__VA_ARGS__);	\
	})
#define INDIRECT_CALL_2(f, f2, f1, ...)					\
	({								\
		likely(f == f2) ? f2(__VA_ARGS__) :			\
				  INDIRECT_CALL_1(f, f1, __VA_ARGS__);	\
	})
#define INDIRECT_CALL_3(f, f3, f2, f1, ...)					\
	({									\
		likely(f == f3) ? f3(__VA_ARGS__) :				\
				  INDIRECT_CALL_2(f, f2, f1, __VA_ARGS__);	\
	})
#define INDIRECT_CALL_4(f, f4, f3, f2, f1, ...)					\
	({									\
		likely(f == f4) ? f4(__VA_ARGS__) :				\
				  INDIRECT_CALL_3(f, f3, f2, f1, __VA_ARGS__);	\
	})

#define INDIRECT_CALLABLE_DECLARE(f)	f
#define INDIRECT_CALLABLE_SCOPE
#define EXPORT_INDIRECT_CALLABLE(f)	EXPORT_SYMBOL(f)

#else
#define INDIRECT_CALL_1(f, f1, ...) f(__VA_ARGS__)
#define INDIRECT_CALL_2(f, f2, f1, ...) f(__VA_ARGS__)
#define INDIRECT_CALL_3(f, f3, f2, f1, ...) f(__VA_ARGS__)
#define INDIRECT_CALL_4(f, f4, f3, f2, f1, ...) f(__VA_ARGS__)
#define INDIRECT_CALLABLE_DECLARE(f)
#define INDIRECT_CALLABLE_SCOPE		static
#define EXPORT_INDIRECT_CALLABLE(f)
#endif

/*
 * We can use INDIRECT_CALL_$NR for ipv6 related functions only if ipv6 is
 * builtin, this macro simplify dealing with indirect calls with only ipv4/ipv6
 * alternatives
 */
#if IS_BUILTIN(CONFIG_IPV6)
#define INDIRECT_CALL_INET(f, f2, f1, ...) \
	INDIRECT_CALL_2(f, f2, f1, __VA_ARGS__)
#elif IS_ENABLED(CONFIG_INET)
#define INDIRECT_CALL_INET(f, f2, f1, ...) INDIRECT_CALL_1(f, f1, __VA_ARGS__)
#else
#define INDIRECT_CALL_INET(f, f2, f1, ...) f(__VA_ARGS__)
#endif

今回の想定ではIPv4なのでip_list_rcvへ行く https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L639

/* Receive a list of IP packets */
void ip_list_rcv(struct list_head *head, struct packet_type *pt,
		 struct net_device *orig_dev)
{
	struct net_device *curr_dev = NULL;
	struct net *curr_net = NULL;
	struct sk_buff *skb, *next;
	LIST_HEAD(sublist);

	list_for_each_entry_safe(skb, next, head, list) {
		struct net_device *dev = skb->dev;
		struct net *net = dev_net(dev);

		skb_list_del_init(skb);
		skb = ip_rcv_core(skb, net);
		if (skb == NULL)
			continue;

		if (curr_dev != dev || curr_net != net) {
			/* dispatch old sublist */
			if (!list_empty(&sublist))
				ip_sublist_rcv(&sublist, curr_dev, curr_net);
			/* start new sublist */
			INIT_LIST_HEAD(&sublist);
			curr_dev = dev;
			curr_net = net;
		}
		list_add_tail(&skb->list, &sublist);
	}
	/* dispatch final sublist */
	if (!list_empty(&sublist))
		ip_sublist_rcv(&sublist, curr_dev, curr_net);
}

まずip_rcv_coreでパケットのバリデーション等を行っている。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L454

static struct sk_buff *ip_rcv_core(struct sk_buff *skb, struct net *net)

その後ip_sublist_rcvにおいてNetfilterのhookがかかりつつip_list_rcv_finishで実際のip_rcv_finish呼び出しがされる https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L630

static void ip_sublist_rcv(struct list_head *head, struct net_device *dev,
			   struct net *net)
{
	NF_HOOK_LIST(NFPROTO_IPV4, NF_INET_PRE_ROUTING, net, NULL,
		     head, dev, NULL, ip_rcv_finish);
	ip_list_rcv_finish(net, head);
}

ip_rcv_finishはip_rcv_finish_coreを呼んでいる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L317

static int ip_rcv_finish_core(struct net *net,
			      struct sk_buff *skb, struct net_device *dev,
			      const struct sk_buff *hint)

TCPの確立済みコネクションに紐づくパケットについてあらかじめソケットを関連付ける最適化が行われている? https://sysctl-explorer.net/net/ipv4/ip_early_demux/ https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_ipv4.c#L1975

int tcp_v4_early_demux(struct sk_buff *skb)
{
	struct net *net = dev_net_rcu(skb->dev);
	const struct iphdr *iph;
	const struct tcphdr *th;
	struct sock *sk;

	if (skb->pkt_type != PACKET_HOST)
		return 0;

	if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct tcphdr)))
		return 0;

	iph = ip_hdr(skb);
	th = tcp_hdr(skb);

	if (th->doff < sizeof(struct tcphdr) / 4)
		return 0;

	sk = __inet_lookup_established(net, net->ipv4.tcp_death_row.hashinfo,
				       iph->saddr, th->source,
				       iph->daddr, ntohs(th->dest),
				       skb->skb_iif, inet_sdif(skb));
	if (sk) {
		skb->sk = sk;
		skb->destructor = sock_edemux;
		if (sk_fullsock(sk)) {
			struct dst_entry *dst = rcu_dereference(sk->sk_rx_dst);

			if (dst)
				dst = dst_check(dst, 0);
			if (dst &&
			    sk->sk_rx_dst_ifindex == skb->skb_iif)
				skb_dst_set_noref(skb, dst);
		}
	}
	return 0;
}

そしてdropされたりしつつ最終的にip_sublist_rcv_finishに到達。dst_inputが呼ばれる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L572

static void ip_sublist_rcv_finish(struct list_head *head)
{
	struct sk_buff *skb, *next;

	list_for_each_entry_safe(skb, next, head, list) {
		skb_list_del_init(skb);
		dst_input(skb);
	}
}

dst_inputではip_local_deliver https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/include/net/dst.h#L467

/* Input packet from network to transport.  */
static inline int dst_input(struct sk_buff *skb)
{
	return INDIRECT_CALL_INET(skb_dst(skb)->input,
				  ip6_input, ip_local_deliver, skb);
}

なおForwardingに行く場合はip_rcv_finish_coreから呼ばれる以下の呼び出し等によってskb_dst(skb)->inputはip_forwardになる。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L364 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/route.c#L2537 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/route.c#L2485 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/route.c#L2254 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/route.c#L2160 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/route.c#L1885

ip_local_deliverで https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L242

/*
 * 	Deliver IP Packets to the higher protocol layers.
 */
int ip_local_deliver(struct sk_buff *skb)
{
	/*
	 *	Reassemble IP fragments.
	 */
	struct net *net = dev_net(skb->dev);

	if (ip_is_fragment(ip_hdr(skb))) {
		if (ip_defrag(net, skb, IP_DEFRAG_LOCAL_DELIVER))
			return 0;
	}

	return NF_HOOK(NFPROTO_IPV4, NF_INET_LOCAL_IN,
		       net, NULL, skb, skb->dev, NULL,
		       ip_local_deliver_finish);
}
EXPORT_SYMBOL(ip_local_deliver);

そして呼び出し階層を辿ったここでtcp_v4_rcvに渡される。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/ip_input.c#L205

ret = INDIRECT_CALL_2(ipprot->handler, tcp_v4_rcv, udp_rcv,
				      skb);

まず、最初の接続部分で考えていく。 https://github.com/torvalds/linux/blob/5b032cac622533631b8f9b7826498b7ce75001c6/net/ipv4/tcp_ipv4.c#L2187

まず最初SYNパケットを受信する https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_ipv4.c#L2240

	if (sk->sk_state == TCP_NEW_SYN_RECV) {

ここで受信ソケットの処理が行われ、TCP_SYN_RECV以外の状態になったら親ソケットに通知される?SIGIOを通知するようであるが https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_minisocks.c#L939

/*
 * Queue segment on the new socket if the new socket is active,
 * otherwise we just shortcircuit this and continue with
 * the new socket.
 *
 * For the vast majority of cases child->sk_state will be TCP_SYN_RECV
 * when entering. But other states are possible due to a race condition
 * where after __inet_lookup_established() fails but before the listener
 * locked is obtained, other packets cause the same connection to
 * be created.
 */

enum skb_drop_reason tcp_child_process(struct sock *parent, struct sock *child,
				       struct sk_buff *skb)
	__releases(&((child)->sk_lock.slock))
{
	enum skb_drop_reason reason = SKB_NOT_DROPPED_YET;
	int state = child->sk_state;

	/* record sk_napi_id and sk_rx_queue_mapping of child. */
	sk_mark_napi_id_set(child, skb);

	tcp_segs_in(tcp_sk(child), skb);
	if (!sock_owned_by_user(child)) {
		reason = tcp_rcv_state_process(child, skb);
		/* Wakeup parent, send SIGIO */
		if (state == TCP_SYN_RECV && child->sk_state != state)
			parent->sk_data_ready(parent);
	} else {
		/* Alas, it is possible again, because we do lookup
		 * in main socket hash table and lock on listening
		 * socket does not protect us more.
		 */
		__sk_add_backlog(child, skb);
	}

	bh_unlock_sock(child);
	sock_put(child);
	return reason;
}
EXPORT_IPV6_MOD(tcp_child_process);

そしてここでステートマシンの処理が行われる。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_input.c#L6768

enum skb_drop_reason
tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)

tcp_rcv_state_processでまず最初はTCP_LISTENステートのところにやってきて https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_ipv4.c#L1733

int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)

cookieを使う場合は一旦確保したコンテキストを破棄。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_input.c#L7371C18-L7372C26

	tcp_rsk(req)->tfo_listener = false;
		if (!want_cookie) {
			req->timeout = tcp_timeout_init((struct sock *)req);
			if (unlikely(!inet_csk_reqsk_queue_hash_add(sk, req,
								    req->timeout))) {
				reqsk_free(req);
				dst_release(dst);
				return 0;
			}

		}
		af_ops->send_synack(sk, dst, &fl, req, &foc,
				    !want_cookie ? TCP_SYNACK_NORMAL :
						   TCP_SYNACK_COOKIE,
				    skb);
		if (want_cookie) {
			reqsk_free(req);
			return 0;
		}

どうやらsyncookiesを利用するipv4_tcp_syncookiesフラグは1と言われるが2を設定すると強制的にsyncookieを使うモードにできるようである。 https://kaworu.jpn.org/security/Linux_SYN_cookies%E3%82%92%E6%9C%89%E5%8A%B9%E3%81%AB%E3%81%99%E3%82%8B https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_input.c#L7250

	  syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);

		if (syncookies == 2 || inet_csk_reqsk_queue_is_full(sk)) {
			want_cookie = tcp_syn_flood_action(sk,
							   rsk_ops->slab_name);
			if (!want_cookie)
				goto drop;
		}

ここでTCP_ESTABLISHEDに遷移する https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_input.c#L6886

tcp_set_state(sk, TCP_ESTABLISHED);

TCP SYN Cookieを使う場合は最終的にここでキューに追加 tcp_v4_do_rcv https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_ipv4.c#L2363 tcp_v4_cookie_check https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/tcp_ipv4.c#L1933 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/syncookies.c#L399 tcp_get_cookie_sock https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/syncookies.c#L196 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/syncookies.c#L215

	if (inet_csk_reqsk_queue_add(sk, req, child))
			return child;

キューに追加する処理本体。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/inet_connection_sock.c#L1406

struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
				      struct request_sock *req,
				      struct sock *child)

&inet_csk(sk)->icsk_accept_queueに追加される。

これが最終的にacceptで受信するソケットをユーザー側が&inet_csk(sk)->icsk_accept_queueから取ってくるところ https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/inet_connection_sock.c#L662

/*
 * This will accept the next outstanding connection.
 */
struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg)

そしてinet_csk_acceptはinet_acceptからREAD_ONCE(sk1->sk_prot)->accept(sk1, arg);として呼ばれる。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/ipv4/af_inet.c#L781

int inet_accept(struct socket *sock, struct socket *newsock,
		struct proto_accept_arg *arg)
{
	struct sock *sk1 = sock->sk, *sk2;

	/* IPV6_ADDRFORM can change sk->sk_prot under us. */
	arg->err = -EINVAL;
	sk2 = READ_ONCE(sk1->sk_prot)->accept(sk1, arg);
	if (!sk2)
		return arg->err;

	lock_sock(sk2);
	__inet_accept(sock, newsock, sk2);
	release_sock(sk2);
	return 0;
}
EXPORT_SYMBOL(inet_accept);

そしてinet_acceptはdo_acceptからops->accept(sock, newsock, arg);として呼ばれる。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/socket.c#L1924

err = ops->accept(sock, newsock, arg);

__sys_accept4_fileからdo_acceptが呼ばれ https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/socket.c#L1964

__sys_accept4から__sys_accept4_fileが呼ばれ https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/socket.c#L1993

そしてaccept及びaccept4システムコール経由で__sys_accept4が呼ばれる。 https://github.com/torvalds/linux/blob/8630c59e99363c4b655788fd01134aef9bcd9264/net/socket.c#L1997

参考等: https://www.valinux.co.jp/blog/entry/20250515 https://www.intel.co.jp/content/www/jp/ja/docs/programmable/683501/22-3-7-0-0/implementing-msi-x-interrupts.html