In Linux kernel, I find the system call getsockopt finally calls sock->ops->getsockopt (code here). And sock->ops is a struct called proto_ops. This struct contains many function pointers such as getsockopt and I am wondering where it points to - I didn't find the place initiates this struct.
I'm using IPv4 and TCP for the system call and it may have some certain implementation functions to call here.
Any insights would be extremely helpful. Thanks in advance!
For an IPv4 socket, the ops will be one of the structures
inet_stream_ops,inet_dgram_ops,inet_sockraw_opsdefined innet/ipv4/af_inet.c(unless you're using something weird like SCTP that has its own ops defined elsewhere). To see how those pointers get there, look atinet_createin the same file, which is called from__sock_createaspf->create().To see how that pointer gets there, note that
inet_createis thecreatemember of a struct calledinet_family_opswhich is passed tosock_register(), causing it to be placed in thenet_familiesarray which is consulted when a socket is created.Functions with
registerin their names are a good thing to look for when you want to see how different kernel components are connected.Now back to
getsockopt. If you look at where thegetsockoptpointer actually goes, in all 3 of theinet_*_opsstructs it points tosock_common_getsockoptfor thegetsockoptfunction.sock_common_getsockoptinnet/core/sock.cisn't very interesting. It just extracts astruct sockfrom astruct socketand then callssk->sk_prot->getsockopt. So next you'll be wondering where that comes from.It comes from the next layer up. I'm going to assume TCP as an example.
In
net/ipv4/tcp_ipv4.cthere's astruct proto tcp_protin which thegetsockoptmember points totcp_getsockopt, a function defined innet/ipv4/tcp.c. It implementsSOL_TCPoptions itself, and for others, it calls thegetsockoptmethod from another ops structure calledicsk_af_ops. That brings us back tonet/ipv4/tcp_ipv4.cwherestruct inet_connection_sock_af_ops ipv4_specifichasgetsockoptpointing toip_getsockopt.ip_getsockoptis innet/ipv4/ip_sockglue.cand it callsdo_ip_getsockoptin the same file, which is where theSOL_IPoptions are actually handled.