udev knows by netlink to mount such as usb disk and knows to invoke usb garget as device.
How udev know that is the way you know that and the answer for your question.
The basic knowledge is netlink of linux. the dmesg is also by netlink link udev. if you write down a netlink program you will get such as usb disk add remove message as udev does.
From the sysfs /sys/class, it also can know the usb role.
It is linux question not a question for i.MX Processors community.
It is too big topic, suggest you to learn the netlink, udev mechanism first.