xref: /illumos-gate/usr/src/uts/common/io/mac/mac_sched.c (revision a92282e44f968185a6bba094d1e5fece2da819cf)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  * Copyright 2018 Joyent, Inc.
25  * Copyright 2013 Nexenta Systems, Inc. All rights reserved.
26  */
27 
28 /*
29  * MAC data path
30  *
31  * The MAC data path is concerned with the flow of traffic from mac clients --
32  * DLS, IP, etc. -- to various GLDv3 device drivers -- e1000g, vnic, aggr,
33  * ixgbe, etc. -- and from the GLDv3 device drivers back to clients.
34  *
35  * -----------
36  * Terminology
37  * -----------
38  *
39  * MAC uses a lot of different, but related terms that are associated with the
40  * design and structure of the data path. Before we cover other aspects, first
41  * let's review the terminology that MAC uses.
42  *
43  * MAC
44  *
45  *	This driver. It interfaces with device drivers and provides abstractions
46  *	that the rest of the system consumes. All data links -- things managed
47  *	with dladm(1M), are accessed through MAC.
48  *
49  * GLDv3 DEVICE DRIVER
50  *
51  *	A GLDv3 device driver refers to a driver, both for pseudo-devices and
52  *	real devices, which implement the GLDv3 driver API. Common examples of
53  *	these are igb and ixgbe, which are drivers for various Intel networking
54  *	cards. These devices may or may not have various features, such as
55  *	hardware rings and checksum offloading. For MAC, a GLDv3 device is the
56  *	final point for the transmission of a packet and the starting point for
57  *	the receipt of a packet.
58  *
59  * FLOWS
60  *
61  *	At a high level, a flow refers to a series of packets that are related.
62  *	Often times the term is used in the context of TCP to indicate a unique
63  *	TCP connection and the traffic over it. However, a flow can exist at
64  *	other levels of the system as well. MAC has a notion of a default flow
65  *	which is used for all unicast traffic addressed to the address of a MAC
66  *	device. For example, when a VNIC is created, a default flow is created
67  *	for the VNIC's MAC address. In addition, flows are created for broadcast
68  *	groups and a user may create a flow with flowadm(1M).
69  *
70  * CLASSIFICATION
71  *
72  *	Classification refers to the notion of identifying an incoming frame
73  *	based on its destination address and optionally its source addresses and
74  *	doing different processing based on that information. Classification can
75  *	be done in both hardware and software. In general, we usually only
76  *	classify based on the layer two destination, eg. for Ethernet, the
77  *	destination MAC address.
78  *
79  *	The system also will do classification based on layer three and layer
80  *	four properties. This is used to support things like flowadm(1M), which
81  *	allows setting QoS and other properties on a per-flow basis.
82  *
83  * RING
84  *
85  *	Conceptually, a ring represents a series of framed messages, often in a
86  *	contiguous chunk of memory that acts as a circular buffer. Rings come in
87  *	a couple of forms. Generally they are either a hardware construct (hw
88  *	ring) or they are a software construct (sw ring) maintained by MAC.
89  *
90  * HW RING
91  *
92  *	A hardware ring is a set of resources provided by a GLDv3 device driver
93  *	(even if it is a pseudo-device). A hardware ring comes in two different
94  *	forms: receive (rx) rings and transmit (tx) rings. An rx hw ring is
95  *	something that has a unique DMA (direct memory access) region and
96  *	generally supports some form of classification (though it isn't always
97  *	used), as well as a means of generating an interrupt specific to that
98  *	ring. For example, the device may generate a specific MSI-X for a PCI
99  *	express device. A tx ring is similar, except that it is dedicated to
100  *	transmission. It may also be a vector for enabling features such as VLAN
101  *	tagging and large transmit offloading. It usually has its own dedicated
102  *	interrupts for transmit being completed.
103  *
104  * SW RING
105  *
106  *	A software ring is a construction of MAC. It represents the same thing
107  *	that a hardware ring generally does, a collection of frames. However,
108  *	instead of being in a contiguous ring of memory, they're instead linked
109  *	by using the mblk_t's b_next pointer. Each frame may itself be multiple
110  *	mblk_t's linked together by the b_cont pointer. A software ring always
111  *	represents a collection of classified packets; however, it varies as to
112  *	whether it uses only layer two information, or a combination of that and
113  *	additional layer three and layer four data.
114  *
115  * FANOUT
116  *
117  *	Fanout is the idea of spreading out the load of processing frames based
118  *	on the source and destination information contained in the layer two,
119  *	three, and four headers, such that the data can then be processed in
120  *	parallel using multiple hardware threads.
121  *
122  *	A fanout algorithm hashes the headers and uses that to place different
123  *	flows into a bucket. The most important thing is that packets that are
124  *	in the same flow end up in the same bucket. If they do not, performance
125  *	can be adversely affected. Consider the case of TCP.  TCP severely
126  *	penalizes a connection if the data arrives out of order. If a given flow
127  *	is processed on different CPUs, then the data will appear out of order,
128  *	hence the invariant that fanout always hash a given flow to the same
129  *	bucket and thus get processed on the same CPU.
130  *
131  * RECEIVE SIDE SCALING (RSS)
132  *
133  *
134  *	Receive side scaling is a term that isn't common in illumos, but is used
135  *	by vendors and was popularized by Microsoft. It refers to the idea of
136  *	spreading the incoming receive load out across multiple interrupts which
137  *	can be directed to different CPUs. This allows a device to leverage
138  *	hardware rings even when it doesn't support hardware classification. The
139  *	hardware uses an algorithm to perform fanout that ensures the flow
140  *	invariant is maintained.
141  *
142  * SOFT RING SET
143  *
144  *	A soft ring set, commonly abbreviated SRS, is a collection of rings and
145  *	is used for both transmitting and receiving. It is maintained in the
146  *	structure mac_soft_ring_set_t. A soft ring set is usually associated
147  *	with flows, and coordinates both the use of hardware and software rings.
148  *	Because the use of hardware rings can change as devices such as VNICs
149  *	come and go, we always ensure that the set has software classification
150  *	rules that correspond to the hardware classification rules from rings.
151  *
152  *	Soft ring sets are also used for the enforcement of various QoS
153  *	properties. For example, if a bandwidth limit has been placed on a
154  *	specific flow or device, then that will be enforced by the soft ring
155  *	set.
156  *
157  * SERVICE ATTACHMENT POINT (SAP)
158  *
159  *	The service attachment point is a DLPI (Data Link Provider Interface)
160  *	concept; however, it comes up quite often in MAC. Most MAC devices speak
161  *	a protocol that has some notion of different channels or message type
162  *	identifiers. For example, Ethernet defines an EtherType which is a part
163  *	of the Ethernet header and defines the particular protocol of the data
164  *	payload. If the EtherType is set to 0x0800, then it defines that the
165  *	contents of that Ethernet frame is IPv4 traffic. For Ethernet, the
166  *	EtherType is the SAP.
167  *
168  *	In DLPI, a given consumer attaches to a specific SAP. In illumos, the ip
169  *	and arp drivers attach to the EtherTypes for IPv4, IPv6, and ARP. Using
170  *	libdlpi(3LIB) user software can attach to arbitrary SAPs. With the
171  *	exception of 802.1Q VLAN tagged traffic, MAC itself does not directly
172  *	consume the SAP; however, it uses that information as part of hashing
173  *	and it may be used as part of the construction of flows.
174  *
175  * PRIMARY MAC CLIENT
176  *
177  *	The primary mac client refers to a mac client whose unicast address
178  *	matches the address of the device itself. For example, if the system has
179  *	instance of the e1000g driver such as e1000g0, e1000g1, etc., the
180  *	primary mac client is the one named after the device itself. VNICs that
181  *	are created on top of such devices are not the primary client.
182  *
183  * TRANSMIT DESCRIPTORS
184  *
185  *	Transmit descriptors are a resource that most GLDv3 device drivers have.
186  *	Generally, a GLDv3 device driver takes a frame that's meant to be output
187  *	and puts a copy of it into a region of memory. Each region of memory
188  *	usually has an associated descriptor that the device uses to manage
189  *	properties of the frames. Devices have a limited number of such
190  *	descriptors. They get reclaimed once the device finishes putting the
191  *	frame on the wire.
192  *
193  *	If the driver runs out of transmit descriptors, for example, the OS is
194  *	generating more frames than it can put on the wire, then it will return
195  *	them back to the MAC layer.
196  *
197  * ---------------------------------
198  * Rings, Classification, and Fanout
199  * ---------------------------------
200  *
201  * The heart of MAC is made up of rings, and not those that Elven-kings wear.
202  * When receiving a packet, MAC breaks the work into two different, though
203  * interrelated phases. The first phase is generally classification and then the
204  * second phase is generally fanout. When a frame comes in from a GLDv3 Device,
205  * MAC needs to determine where that frame should be delivered. If it's a
206  * unicast frame (say a normal TCP/IP packet), then it will be delivered to a
207  * single MAC client; however, if it's a broadcast or multicast frame, then MAC
208  * may need to deliver it to multiple MAC clients.
209  *
210  * On transmit, classification isn't quite as important, but may still be used.
211  * Unlike with the receive path, the classification is not used to determine
212  * devices that should transmit something, but rather is used for special
213  * properties of a flow, eg. bandwidth limits for a given IP address, device, or
214  * connection.
215  *
216  * MAC employs a software classifier and leverages hardware classification as
217  * well. The software classifier can leverage the full layer two information,
218  * source, destination, VLAN, and SAP. If the SAP indicates that IP traffic is
219  * being sent, it can classify based on the IP header, and finally, it also
220  * knows how to classify based on the local and remote ports of TCP, UDP, and
221  * SCTP.
222  *
223  * Hardware classifiers vary in capability. Generally all hardware classifiers
224  * provide the capability to classify based on the destination MAC address. Some
225  * hardware has additional filters built in for performing more in-depth
226  * classification; however, it often has much more limited resources for these
227  * activities as compared to the layer two destination address classification.
228  *
229  * The modus operandi in MAC is to always ensure that we have software-based
230  * capabilities and rules in place and then to supplement that with hardware
231  * resources when available. In general, simple layer two classification is
232  * sufficient and nothing else is used, unless a specific flow is created with
233  * tools such as flowadm(1M) or bandwidth limits are set on a device with
234  * dladm(1M).
235  *
236  * RINGS AND GROUPS
237  *
238  * To get into how rings and classification play together, it's first important
239  * to understand how hardware devices commonly associate rings and allow them to
240  * be programmed. Recall that a hardware ring should be thought of as a DMA
241  * buffer and an interrupt resource. Rings are then collected into groups. A
242  * group itself has a series of classification rules. One or more MAC addresses
243  * are assigned to a group.
244  *
245  * Hardware devices vary in terms of what capabilities they provide. Sometimes
246  * they allow for a dynamic assignment of rings to a group and sometimes they
247  * have a static assignment of rings to a group. For example, the ixgbe driver
248  * has a static assignment of rings to groups such that every group has exactly
249  * one ring and the number of groups is equal to the number of rings.
250  *
251  * Classification and receive side scaling both come into play with how a device
252  * advertises itself to MAC and how MAC uses it. If a device supports layer two
253  * classification of frames, then MAC will assign MAC addresses to a group as a
254  * form of primary classification. If a single MAC address is assigned to a
255  * group, a common case, then MAC will consider packets that come in from rings
256  * on that group to be fully classified and will not need to do any software
257  * classification unless a specific flow has been created.
258  *
259  * If a device supports receive side scaling, then it may advertise or support
260  * groups with multiple rings. In those cases, then receive side scaling will
261  * come into play and MAC will use that as a means of fanning out received
262  * frames across multiple CPUs. This can also be combined with groups that
263  * support layer two classification.
264  *
265  * If a device supports dynamic assignments of rings to groups, then MAC will
266  * change around the way that rings are assigned to various groups as devices
267  * come and go from the system. For example, when a VNIC is created, a new flow
268  * will be created for the VNIC's MAC address. If a hardware ring is available,
269  * MAC may opt to reassign it from one group to another.
270  *
271  * ASSIGNMENT OF HARDWARE RINGS
272  *
273  * This is a bit of a complicated subject that varies depending on the device,
274  * the use of aggregations, the special nature of the primary mac client. This
275  * section deserves being fleshed out.
276  *
277  * FANOUT
278  *
279  * illumos uses fanout to help spread out the incoming processing load of chains
280  * of frames away from a single CPU. If a device supports receive side scaling,
281  * then that provides an initial form of fanout; however, what we're concerned
282  * with all happens after the context of a given set of frames being classified
283  * to a soft ring set.
284  *
285  * After frames reach a soft ring set and account for any potential bandwidth
286  * related accounting, they may be fanned out based on one of the following
287  * three modes:
288  *
289  *     o No Fanout
290  *     o Protocol level fanout
291  *     o Full software ring protocol fanout
292  *
293  * MAC makes the determination as to which of these modes a given soft ring set
294  * obtains based on parameters such as whether or not it's the primary mac
295  * client, whether it's on a 10 GbE or faster device, user controlled dladm(1M)
296  * properties, and the nature of the hardware and the resources that it has.
297  *
298  * When there is no fanout, MAC does not create any soft rings for a device and
299  * the device has frames delivered directly to the MAC client.
300  *
301  * Otherwise, all fanout is performed by software. MAC divides incoming frames
302  * into one of three buckets -- IPv4 TCP traffic, IPv4 UDP traffic, and
303  * everything else. Regardless of the type of fanout, these three categories
304  * or buckets are always used.
305  *
306  * The difference between protocol level fanout and full software ring protocol
307  * fanout is the number of software rings that end up getting created. The
308  * system always uses the same number of software rings per protocol bucket. So
309  * in the first case when we're just doing protocol level fanout, we just create
310  * one software ring each for IPv4 TCP traffic, IPv4 UDP traffic, and everything
311  * else.
312  *
313  * In the case where we do full software ring protocol fanout, we generally use
314  * mac_compute_soft_ring_count() to determine the number of rings. There are
315  * other combinations of properties and devices that may send us down other
316  * paths, but this is a common starting point. If it's a non-bandwidth enforced
317  * device and we're on at least a 10 GbE link, then we'll use eight soft rings
318  * per protocol bucket as a starting point. See mac_compute_soft_ring_count()
319  * for more information on the total number.
320  *
321  * For each of these rings, we create a mac_soft_ring_t and an associated worker
322  * thread. Particularly when doing full software ring protocol fanout, we bind
323  * each of the worker threads to individual CPUs.
324  *
325  * The other advantage of these software rings is that it allows upper layers to
326  * optionally poll on them. For example, TCP can leverage an squeue to poll on
327  * the software ring, see squeue.c for more information.
328  *
329  * DLS BYPASS
330  *
331  * DLS is the data link services module. It interfaces with DLPI, which is the
332  * primary way that other parts of the system such as IP interface with the MAC
333  * layer. While DLS is traditionally a STREAMS-based interface, it allows for
334  * certain modules such as IP to negotiate various more modern interfaces to be
335  * used, which are useful for higher performance and allow it to use direct
336  * function calls to DLS instead of using STREAMS.
337  *
338  * When we have IPv4 TCP or UDP software rings, then traffic on those rings is
339  * eligible for what we call the dls bypass. In those cases, rather than going
340  * out mac_rx_deliver() to DLS, DLS instead registers them to go directly via
341  * the direct callback registered with DLS, generally ip_input().
342  *
343  * HARDWARE RING POLLING
344  *
345  * GLDv3 devices with hardware rings generally deliver chains of messages
346  * (mblk_t chain) during the context of a single interrupt. However, interrupts
347  * are not the only way that these devices may be used. As part of implementing
348  * ring support, a GLDv3 device driver must have a way to disable the generation
349  * of that interrupt and allow for the operating system to poll on that ring.
350  *
351  * To implement this, every soft ring set has a worker thread and a polling
352  * thread. If a sufficient packet rate comes into the system, MAC will 'blank'
353  * (disable) interrupts on that specific ring and the polling thread will start
354  * consuming packets from the hardware device and deliver them to the soft ring
355  * set, where the worker thread will take over.
356  *
357  * Once the rate of packet intake drops down below a certain threshold, then
358  * polling on the hardware ring will be quiesced and interrupts will be
359  * re-enabled for the given ring. This effectively allows the system to shift
360  * how it handles a ring based on its load. At high packet rates, polling on the
361  * device as opposed to relying on interrupts can actually reduce overall system
362  * load due to the minimization of interrupt activity.
363  *
364  * Note the importance of each ring having its own interrupt source. The whole
365  * idea here is that we do not disable interrupts on the device as a whole, but
366  * rather each ring can be independently toggled.
367  *
368  * USE OF WORKER THREADS
369  *
370  * Both the soft ring set and individual soft rings have a worker thread
371  * associated with them that may be bound to a specific CPU in the system. Any
372  * such assignment will get reassessed as part of dynamic reconfiguration events
373  * in the system such as the onlining and offlining of CPUs and the creation of
374  * CPU partitions.
375  *
376  * In many cases, while in an interrupt, we try to deliver a frame all the way
377  * through the stack in the context of the interrupt itself. However, if the
378  * amount of queued frames has exceeded a threshold, then we instead defer to
379  * the worker thread to do this work and signal it. This is particularly useful
380  * when you have the soft ring set delivering frames into multiple software
381  * rings. If it was only delivering frames into a single software ring then
382  * there'd be no need to have another thread take over. However, if it's
383  * delivering chains of frames to multiple rings, then it's worthwhile to have
384  * the worker for the software ring take over so that the different software
385  * rings can be processed in parallel.
386  *
387  * In a similar fashion to the hardware polling thread, if we don't have a
388  * backlog or there's nothing to do, then the worker thread will go back to
389  * sleep and frames can be delivered all the way from an interrupt. This
390  * behavior is useful as it's designed to minimize latency and the default
391  * disposition of MAC is to optimize for latency.
392  *
393  * MAINTAINING CHAINS
394  *
395  * Another useful idea that MAC uses is to try and maintain frames in chains for
396  * as long as possible. The idea is that all of MAC can handle chains of frames
397  * structured as a series of mblk_t structures linked with the b_next pointer.
398  * When performing software classification and software fanout, MAC does not
399  * simply determine the destination and send the frame along. Instead, in the
400  * case of classification, it tries to maintain a chain for as long as possible
401  * before passing it along and performing additional processing.
402  *
403  * In the case of fanout, MAC first determines what the target software ring is
404  * for every frame in the original chain and constructs a new chain for each
405  * target. MAC then delivers the new chain to each software ring in succession.
406  *
407  * The whole rationale for doing this is that we want to try and maintain the
408  * pipe as much as possible and deliver as many frames through the stack at once
409  * that we can, rather than just pushing a single frame through. This can often
410  * help bring down latency and allows MAC to get a better sense of the overall
411  * activity in the system and properly engage worker threads.
412  *
413  * --------------------
414  * Bandwidth Management
415  * --------------------
416  *
417  * Bandwidth management is something that's built into the soft ring set itself.
418  * When bandwidth limits are placed on a flow, a corresponding soft ring set is
419  * toggled into bandwidth mode. This changes how we transmit and receive the
420  * frames in question.
421  *
422  * Bandwidth management is done on a per-tick basis. We translate the user's
423  * requested bandwidth from a quantity per-second into a quantity per-tick. MAC
424  * cannot process a frame across more than one tick, thus it sets a lower bound
425  * for the bandwidth cap to be a single MTU. This also means that when
426  * hires ticks are enabled (hz is set to 1000), that the minimum amount of
427  * bandwidth is higher, because the number of ticks has increased and MAC has to
428  * go from accepting 100 packets / sec to 1000 / sec.
429  *
430  * The bandwidth counter is reset by either the soft ring set's worker thread or
431  * a thread that is doing an inline transmit or receive if they discover that
432  * the current tick is in the future from the recorded tick.
433  *
434  * Whenever we're receiving or transmitting data, we end up leaving most of the
435  * work to the soft ring set's worker thread. This forces data inserted into the
436  * soft ring set to be effectively serialized and allows us to exhume bandwidth
437  * at a reasonable rate. If there is nothing in the soft ring set at the moment
438  * and the set has available bandwidth, then it may processed inline.
439  * Otherwise, the worker is responsible for taking care of the soft ring set.
440  *
441  * ---------------------
442  * The Receive Data Path
443  * ---------------------
444  *
445  * The following series of ASCII art images breaks apart the way that a frame
446  * comes in and is processed in MAC.
447  *
448  * Part 1 -- Initial frame receipt, SRS classification
449  *
450  * Here, a frame is received by a GLDv3 driver, generally in the context of an
451  * interrupt, and it ends up in mac_rx_common(). A driver calls either mac_rx or
452  * mac_rx_ring, depending on whether or not it supports rings and can identify
453  * the interrupt as having come from a specific ring. Here we determine whether
454  * or not it's fully classified and perform software classification as
455  * appropriate. From here, everything always ends up going to either entry [A]
456  * or entry [B] based on whether or not they have subflow processing needed. We
457  * leave via fanout or delivery.
458  *
459  *           +===========+
460  *           v hardware  v
461  *           v interrupt v
462  *           +===========+
463  *                 |
464  *                 * . . appropriate
465  *                 |     upcall made
466  *                 |     by GLDv3 driver  . . always
467  *                 |                      .
468  *  +--------+     |     +----------+     .    +---------------+
469  *  | GLDv3  |     +---->| mac_rx   |-----*--->| mac_rx_common |
470  *  | Driver |-->--+     +----------+          +---------------+
471  *  +--------+     |        ^                         |
472  *      |          |        ^                         v
473  *      ^          |        * . . always   +----------------------+
474  *      |          |        |              | mac_promisc_dispatch |
475  *      |          |    +-------------+    +----------------------+
476  *      |          +--->| mac_rx_ring |               |
477  *      |               +-------------+               * . . hw classified
478  *      |                                             v     or single flow?
479  *      |                                             |
480  *      |                                   +--------++--------------+
481  *      |                                   |        |               * hw class,
482  *      |                                   |        * hw classified | subflows
483  *      |                 no hw class and . *        | or single     | exist
484  *      |                 subflows          |        | flow          |
485  *      |                                   |        v               v
486  *      |                                   |   +-----------+   +-----------+
487  *      |                                   |   |   goto    |   |  goto     |
488  *      |                                   |   | entry [A] |   | entry [B] |
489  *      |                                   |   +-----------+   +-----------+
490  *      |                                   v          ^
491  *      |                            +-------------+   |
492  *      |                            | mac_rx_flow |   * SRS and flow found,
493  *      |                            +-------------+   | call flow cb
494  *      |                                   |          +------+
495  *      |                                   v                 |
496  *      v                             +==========+    +-----------------+
497  *      |                             v For each v--->| mac_rx_classify |
498  * +----------+                       v  mblk_t  v    +-----------------+
499  * |   srs    |                       +==========+
500  * | pollling |
501  * |  thread  |->------------------------------------------+
502  * +----------+                                            |
503  *                                                         v       . inline
504  *            +--------------------+   +----------+   +---------+  .
505  *    [A]---->| mac_rx_srs_process |-->| check bw |-->| enqueue |--*---------+
506  *            +--------------------+   |  limits  |   | frames  |            |
507  *               ^                     +----------+   | to SRS  |            |
508  *               |                                    +---------+            |
509  *               |  send chain              +--------+    |                  |
510  *               *  when clasified          | signal |    * BW limits,       |
511  *               |  flow changes            |  srs   |<---+ loopback,        |
512  *               |                          | worker |      stack too        |
513  *               |                          +--------+      deep             |
514  *      +-----------------+        +--------+                                |
515  *      | mac_flow_lookup |        |  srs   |     +---------------------+    |
516  *      +-----------------+        | worker |---->| mac_rx_srs_drain    |<---+
517  *               ^                 | thread |     | mac_rx_srs_drain_bw |
518  *               |                 +--------+     +---------------------+
519  *               |                                          |
520  *         +----------------------------+                   * software rings
521  *   [B]-->| mac_rx_srs_subflow_process |                   | for fanout?
522  *         +----------------------------+                   |
523  *                                               +----------+-----------+
524  *                                               |                      |
525  *                                               v                      v
526  *                                          +--------+             +--------+
527  *                                          |  goto  |             |  goto  |
528  *                                          | Part 2 |             | Part 3 |
529  *                                          +--------+             +--------+
530  *
531  * Part 2 -- Fanout
532  *
533  * This part is concerned with using software fanout to assign frames to
534  * software rings and then deliver them to MAC clients or allow those rings to
535  * be polled upon. While there are two different primary fanout entry points,
536  * mac_rx_fanout and mac_rx_proto_fanout, they behave in similar ways, and aside
537  * from some of the individual hashing techniques used, most of the general
538  * flow is the same.
539  *
540  *  +--------+              +-------------------+
541  *  |  From  |---+--------->| mac_rx_srs_fanout |----+
542  *  | Part 1 |   |          +-------------------+    |    +=================+
543  *  +--------+   |                                   |    v for each mblk_t v
544  *               * . . protocol only                 +--->v assign to new   v
545  *               |     fanout                        |    v chain based on  v
546  *               |                                   |    v hash % nrings   v
547  *               |    +-------------------------+    |    +=================+
548  *               +--->| mac_rx_srs_proto_fanout |----+             |
549  *                    +-------------------------+                  |
550  *                                                                 v
551  *    +------------+    +--------------------------+       +================+
552  *    | enqueue in |<---| mac_rx_soft_ring_process |<------v for each chain v
553  *    | soft ring  |    +--------------------------+       +================+
554  *    +------------+
555  *         |                                    +-----------+
556  *         * soft ring set                      | soft ring |
557  *         | empty and no                       |  worker   |
558  *         | worker?                            |  thread   |
559  *         |                                    +-----------+
560  *         +------*----------------+                  |
561  *         |      .                |                  v
562  *    No . *      . Yes            |       +------------------------+
563  *         |                       +----<--| mac_rx_soft_ring_drain |
564  *         |                       |       +------------------------+
565  *         v                       |
566  *   +-----------+                 v
567  *   |   signal  |         +---------------+
568  *   | soft ring |         | Deliver chain |
569  *   |   worker  |         | goto Part 3   |
570  *   +-----------+         +---------------+
571  *
572  *
573  * Part 3 -- Packet Delivery
574  *
575  * Here, we go through and deliver the mblk_t chain directly to a given
576  * processing function. In a lot of cases this is mac_rx_deliver(). In the case
577  * of DLS bypass being used, then instead we end up going ahead and deliver it
578  * to the direct callback registered with DLS, generally ip_input.
579  *
580  *
581  *   +---------+            +----------------+    +------------------+
582  *   |  From   |---+------->| mac_rx_deliver |--->| Off to DLS, or   |
583  *   | Parts 1 |   |        +----------------+    | other MAC client |
584  *   |  and 2  |   * DLS bypass                   +------------------+
585  *   +---------+   | enabled   +----------+    +-------------+
586  *                 +---------->| ip_input |--->|    To IP    |
587  *                             +----------+    | and beyond! |
588  *                                             +-------------+
589  *
590  * ----------------------
591  * The Transmit Data Path
592  * ----------------------
593  *
594  * Before we go into the images, it's worth talking about a problem that is a
595  * bit different from the receive data path. GLDv3 device drivers have a finite
596  * amount of transmit descriptors. When they run out, they return unused frames
597  * back to MAC. MAC, at this point has several options about what it will do,
598  * which vary based upon the settings that the client uses.
599  *
600  * When a device runs out of descriptors, the next thing that MAC does is
601  * enqueue them off of the soft ring set or a software ring, depending on the
602  * configuration of the soft ring set. MAC will enqueue up to a high watermark
603  * of mblk_t chains, at which point it will indicate flow control back to the
604  * client. Once this condition is reached, any mblk_t chains that were not
605  * enqueued will be returned to the caller and they will have to decide what to
606  * do with them. There are various flags that control this behavior that a
607  * client may pass, which are discussed below.
608  *
609  * When this condition is hit, MAC also returns a cookie to the client in
610  * addition to unconsumed frames. Clients can poll on that cookie and register a
611  * callback with MAC to be notified when they are no longer subject to flow
612  * control, at which point they may continue to call mac_tx(). This flow control
613  * actually manages to work itself all the way up the stack, back through dls,
614  * to ip, through the various protocols, and to sockfs.
615  *
616  * While the behavior described above is the default, this behavior can be
617  * modified. There are two alternate modes, described below, which are
618  * controlled with flags.
619  *
620  * DROP MODE
621  *
622  * This mode is controlled by having the client pass the MAC_DROP_ON_NO_DESC
623  * flag. When this is passed, if a device driver runs out of transmit
624  * descriptors, then the MAC layer will drop any unsent traffic. The client in
625  * this case will never have any frames returned to it.
626  *
627  * DON'T ENQUEUE
628  *
629  * This mode is controlled by having the client pass the MAC_TX_NO_ENQUEUE flag.
630  * If the MAC_DROP_ON_NO_DESC flag is also passed, it takes precedence. In this
631  * mode, when we hit a case where a driver runs out of transmit descriptors,
632  * then instead of enqueuing packets in a soft ring set or software ring, we
633  * instead return the mblk_t chain back to the caller and immediately put the
634  * soft ring set into flow control mode.
635  *
636  * The following series of ASCII art images describe the transmit data path that
637  * MAC clients enter into based on calling into mac_tx(). A soft ring set has a
638  * transmission function associated with it. There are seven possible
639  * transmission modes, some of which share function entry points. The one that a
640  * soft ring set gets depends on properties such as whether there are
641  * transmission rings for fanout, whether the device involves aggregations,
642  * whether any bandwidth limits exist, etc.
643  *
644  *
645  * Part 1 -- Initial checks
646  *
647  *      * . called by
648  *      |   MAC clients
649  *      v                     . . No
650  *  +--------+  +-----------+ .   +-------------------+  +====================+
651  *  | mac_tx |->| device    |-*-->| mac_protect_check |->v Is this the simple v
652  *  +--------+  | quiesced? |     +-------------------+  v case? See [1]      v
653  *              +-----------+            |               +====================+
654  *                  * . Yes              * failed                 |
655  *                  v                    | frames                 |
656  *             +--------------+          |                +-------+---------+
657  *             | freemsgchain |<---------+          Yes . *            No . *
658  *             +--------------+                           v                 v
659  *                                                  +-----------+     +--------+
660  *                                                  |   goto    |     |  goto  |
661  *                                                  |  Part 2   |     | SRS TX |
662  *                                                  | Entry [A] |     |  func  |
663  *                                                  +-----------+     +--------+
664  *                                                        |                 |
665  *                                                        |                 v
666  *                                                        |           +--------+
667  *                                                        +---------->| return |
668  *                                                                    | cookie |
669  *                                                                    +--------+
670  *
671  * [1] The simple case refers to the SRS being configured with the
672  * SRS_TX_DEFAULT transmission mode, having a single mblk_t (not a chain), their
673  * being only a single active client, and not having a backlog in the srs.
674  *
675  *
676  * Part 2 -- The SRS transmission functions
677  *
678  * This part is a bit more complicated. The different transmission paths often
679  * leverage one another. In this case, we'll draw out the more common ones
680  * before the parts that depend upon them. Here, we're going to start with the
681  * workings of mac_tx_send() a common function that most of the others end up
682  * calling.
683  *
684  *      +-------------+
685  *      | mac_tx_send |
686  *      +-------------+
687  *            |
688  *            v
689  *      +=============+    +==============+
690  *      v  more than  v--->v    check     v
691  *      v one client? v    v VLAN and add v
692  *      +=============+    v  VLAN tags   v
693  *            |            +==============+
694  *            |                  |
695  *            +------------------+
696  *            |
697  *            |                 [A]
698  *            v                  |
699  *       +============+ . No     v
700  *       v more than  v .     +==========+     +--------------------------+
701  *       v one active v-*---->v for each v---->| mac_promisc_dispatch_one |---+
702  *       v  client?   v       v mblk_t   v     +--------------------------+   |
703  *       +============+       +==========+        ^                           |
704  *            |                                   |       +==========+        |
705  *            * . Yes                             |       v hardware v<-------+
706  *            v                      +------------+       v  rings?  v
707  *       +==========+                |                    +==========+
708  *       v for each v       No . . . *                         |
709  *       v mblk_t   v       specific |                         |
710  *       +==========+       flow     |                   +-----+-----+
711  *            |                      |                   |           |
712  *            v                      |                   v           v
713  *    +-----------------+            |               +-------+  +---------+
714  *    | mac_tx_classify |------------+               | GLDv3 |  |  GLDv3  |
715  *    +-----------------+                            |TX func|  | ring tx |
716  *            |                                      +-------+  |  func   |
717  *            * Specific flow, generally                 |      +---------+
718  *            | bcast, mcast, loopback                   |           |
719  *            v                                          +-----+-----+
720  *      +==========+       +---------+                         |
721  *      v valid L2 v--*--->| freemsg |                         v
722  *      v  header  v  . No +---------+               +-------------------+
723  *      +==========+                                 | return unconsumed |
724  *            * . Yes                                |   frames to the   |
725  *            v                                      |      caller       |
726  *      +===========+                                +-------------------+
727  *      v braodcast v      +----------------+                  ^
728  *      v   flow?   v--*-->| mac_bcast_send |------------------+
729  *      +===========+  .   +----------------+                  |
730  *            |        . . Yes                                 |
731  *       No . *                                                v
732  *            |  +---------------------+  +---------------+  +----------+
733  *            +->|mac_promisc_dispatch |->| mac_fix_cksum |->|   flow   |
734  *               +---------------------+  +---------------+  | callback |
735  *                                                           +----------+
736  *
737  *
738  * In addition, many but not all of the routines, all rely on
739  * mac_tx_softring_process as an entry point.
740  *
741  *
742  *                                           . No             . No
743  * +--------------------------+   +========+ .  +===========+ .  +-------------+
744  * | mac_tx_soft_ring_process |-->v worker v-*->v out of tx v-*->|    goto     |
745  * +--------------------------+   v only?  v    v  descr.?  v    | mac_tx_send |
746  *                                +========+    +===========+    +-------------+
747  *                              Yes . *               * . Yes           |
748  *                   . No             v               |                 v
749  *     v=========+   .          +===========+ . Yes   |     Yes .  +==========+
750  *     v apppend v<--*----------v out of tx v-*-------+---------*--v returned v
751  *     v mblk_t  v              v  descr.?  v         |            v frames?  v
752  *     v chain   v              +===========+         |            +==========+
753  *     +=========+                                    |                 *. No
754  *         |                                          |                 v
755  *         v                                          v           +------------+
756  * +===================+           +----------------------+       |   done     |
757  * v worker scheduled? v           | mac_tx_sring_enqueue |       | processing |
758  * v Out of tx descr?  v           +----------------------+       +------------+
759  * +===================+                      |
760  *    |           |           . Yes           v
761  *    * Yes       * No        .         +============+
762  *    |           v         +-*---------v drop on no v
763  *    |      +========+     v           v  TX desc?  v
764  *    |      v  wake  v  +----------+   +============+
765  *    |      v worker v  | mac_pkt_ |         * . No
766  *    |      +========+  | drop     |         |         . Yes         . No
767  *    |           |      +----------+         v         .             .
768  *    |           |         v   ^     +===============+ .  +========+ .
769  *    +--+--------+---------+   |     v Don't enqueue v-*->v ring   v-*----+
770  *       |                      |     v     Set?      v    v empty? v      |
771  *       |      +---------------+     +===============+    +========+      |
772  *       |      |                            |                |            |
773  *       |      |        +-------------------+                |            |
774  *       |      *. Yes   |                          +---------+            |
775  *       |      |        v                          v                      v
776  *       |      |  +===========+               +========+      +--------------+
777  *       |      +<-v At hiwat? v               v append v      |    return    |
778  *       |         +===========+               v mblk_t v      | mblk_t chain |
779  *       |                  * No               v chain  v      |   and flow   |
780  *       |                  v                  +========+      |    control   |
781  *       |               +=========+                |          |    cookie    |
782  *       |               v  append v                v          +--------------+
783  *       |               v  mblk_t v           +========+
784  *       |               v  chain  v           v  wake  v   +------------+
785  *       |               +=========+           v worker v-->|    done    |
786  *       |                    |                +========+   | processing |
787  *       |                    v       .. Yes                +------------+
788  *       |               +=========+  .   +========+
789  *       |               v  first  v--*-->v  wake  v
790  *       |               v append? v      v worker v
791  *       |               +=========+      +========+
792  *       |                   |                |
793  *       |              No . *                |
794  *       |                   v                |
795  *       |       +--------------+             |
796  *       +------>|   Return     |             |
797  *               | flow control |<------------+
798  *               |   cookie     |
799  *               +--------------+
800  *
801  *
802  * The remaining images are all specific to each of the different transmission
803  * modes.
804  *
805  * SRS TX DEFAULT
806  *
807  *      [ From Part 1 ]
808  *             |
809  *             v
810  * +-------------------------+
811  * | mac_tx_single_ring_mode |
812  * +-------------------------+
813  *            |
814  *            |       . Yes
815  *            v       .
816  *       +==========+ .  +============+
817  *       v   SRS    v-*->v   Try to   v---->---------------------+
818  *       v backlog? v    v enqueue in v                          |
819  *       +==========+    v     SRS    v-->------+                * . . Queue too
820  *            |          +============+         * don't enqueue  |     deep or
821  *            * . No         ^     |            | flag or at     |     drop flag
822  *            |              |     v            | hiwat,         |
823  *            v              |     |            | return    +---------+
824  *     +-------------+       |     |            | cookie    | freemsg |
825  *     |    goto     |-*-----+     |            |           +---------+
826  *     | mac_tx_send | . returned  |            |                |
827  *     +-------------+   mblk_t    |            |                |
828  *            |                    |            |                |
829  *            |                    |            |                |
830  *            * . . all mblk_t     * queued,    |                |
831  *            v     consumed       | may return |                |
832  *     +-------------+             | tx cookie  |                |
833  *     | SRS TX func |<------------+------------+----------------+
834  *     |  completed  |
835  *     +-------------+
836  *
837  * SRS_TX_SERIALIZE
838  *
839  *   +------------------------+
840  *   | mac_tx_serializer_mode |
841  *   +------------------------+
842  *               |
843  *               |        . No
844  *               v        .
845  *         +============+ .  +============+    +-------------+   +============+
846  *         v srs being  v-*->v  set SRS   v--->|    goto     |-->v remove SRS v
847  *         v processed? v    v proc flags v    | mac_tx_send |   v proc flag  v
848  *         +============+    +============+    +-------------+   +============+
849  *               |                                                     |
850  *               * Yes                                                 |
851  *               v                                       . No          v
852  *      +--------------------+                           .        +==========+
853  *      | mac_tx_srs_enqueue |  +------------------------*-----<--v returned v
854  *      +--------------------+  |                                 v frames?  v
855  *               |              |   . Yes                         +==========+
856  *               |              |   .                                  |
857  *               |              |   . +=========+                      v
858  *               v              +-<-*-v queued  v     +--------------------+
859  *        +-------------+       |     v frames? v<----| mac_tx_srs_enqueue |
860  *        | SRS TX func |       |     +=========+     +--------------------+
861  *        | completed,  |<------+         * . Yes
862  *        | may return  |       |         v
863  *        |   cookie    |       |     +========+
864  *        +-------------+       +-<---v  wake  v
865  *                                    v worker v
866  *                                    +========+
867  *
868  *
869  * SRS_TX_FANOUT
870  *
871  *                                             . Yes
872  *   +--------------------+    +=============+ .   +--------------------------+
873  *   | mac_tx_fanout_mode |--->v Have fanout v-*-->|           goto           |
874  *   +--------------------+    v   hint?     v     | mac_rx_soft_ring_process |
875  *                             +=============+     +--------------------------+
876  *                                   * . No                    |
877  *                                   v                         ^
878  *                             +===========+                   |
879  *                        +--->v for each  v           +===============+
880  *                        |    v   mblk_t  v           v pick softring v
881  *                 same   *    +===========+           v   from hash   v
882  *                 hash   |          |                 +===============+
883  *                        |          v                         |
884  *                        |   +--------------+                 |
885  *                        +---| mac_pkt_hash |--->*------------+
886  *                            +--------------+    . different
887  *                                                  hash or
888  *                                                  done proc.
889  * SRS_TX_AGGR                                      chain
890  *
891  *   +------------------+    +================================+
892  *   | mac_tx_aggr_mode |--->v Use aggr capab function to     v
893  *   +------------------+    v find appropriate tx ring.      v
894  *                           v Applies hash based on aggr     v
895  *                           v policy, see mac_tx_aggr_mode() v
896  *                           +================================+
897  *                                          |
898  *                                          v
899  *                           +-------------------------------+
900  *                           |            goto               |
901  *                           |  mac_rx_srs_soft_ring_process |
902  *                           +-------------------------------+
903  *
904  *
905  * SRS_TX_BW, SRS_TX_BW_FANOUT, SRS_TX_BW_AGGR
906  *
907  * Note, all three of these tx functions start from the same place --
908  * mac_tx_bw_mode().
909  *
910  *  +----------------+
911  *  | mac_tx_bw_mode |
912  *  +----------------+
913  *         |
914  *         v          . No               . No               . Yes
915  *  +==============+  .  +============+  .  +=============+ .  +=========+
916  *  v  Out of BW?  v--*->v SRS empty? v--*->v  reset BW   v-*->v Bump BW v
917  *  +==============+     +============+     v tick count? v    v Usage   v
918  *         |                   |            +=============+    +=========+
919  *         |         +---------+                   |                |
920  *         |         |        +--------------------+                |
921  *         |         |        |              +----------------------+
922  *         v         |        v              v
923  * +===============+ |  +==========+   +==========+      +------------------+
924  * v Don't enqueue v |  v  set bw  v   v Is aggr? v--*-->|       goto       |
925  * v   flag set?   v |  v enforced v   +==========+  .   | mac_tx_aggr_mode |-+
926  * +===============+ |  +==========+         |       .   +------------------+ |
927  *   |    Yes .*     |        |         No . *       .                        |
928  *   |         |     |        |              |       . Yes                    |
929  *   * . No    |     |        v              |                                |
930  *   |  +---------+  |   +========+          v              +======+          |
931  *   |  | freemsg |  |   v append v   +============+  . Yes v pick v          |
932  *   |  +---------+  |   v mblk_t v   v Is fanout? v--*---->v ring v          |
933  *   |      |        |   v chain  v   +============+        +======+          |
934  *   +------+        |   +========+          |                  |             |
935  *          v        |        |              v                  v             |
936  *    +---------+    |        v       +-------------+ +--------------------+  |
937  *    | return  |    |   +========+   |    goto     | |       goto         |  |
938  *    |  flow   |    |   v wakeup v   | mac_tx_send | | mac_tx_fanout_mode |  |
939  *    | control |    |   v worker v   +-------------+ +--------------------+  |
940  *    | cookie  |    |   +========+          |                  |             |
941  *    +---------+    |        |              |                  +------+------+
942  *                   |        v              |                         |
943  *                   |   +---------+         |                         v
944  *                   |   | return  |   +============+           +------------+
945  *                   |   |  flow   |   v unconsumed v-------+   |   done     |
946  *                   |   | control |   v   frames?  v       |   | processing |
947  *                   |   | cookie  |   +============+       |   +------------+
948  *                   |   +---------+         |              |
949  *                   |                  Yes  *              |
950  *                   |                       |              |
951  *                   |                 +===========+        |
952  *                   |                 v subtract  v        |
953  *                   |                 v unused bw v        |
954  *                   |                 +===========+        |
955  *                   |                       |              |
956  *                   |                       v              |
957  *                   |              +--------------------+  |
958  *                   +------------->| mac_tx_srs_enqueue |  |
959  *                                  +--------------------+  |
960  *                                           |              |
961  *                                           |              |
962  *                                     +------------+       |
963  *                                     |  return fc |       |
964  *                                     | cookie and |<------+
965  *                                     |    mblk_t  |
966  *                                     +------------+
967  */
968 
969 #include <sys/types.h>
970 #include <sys/callb.h>
971 #include <sys/pattr.h>
972 #include <sys/sdt.h>
973 #include <sys/strsubr.h>
974 #include <sys/strsun.h>
975 #include <sys/vlan.h>
976 #include <sys/stack.h>
977 #include <sys/archsystm.h>
978 #include <inet/ipsec_impl.h>
979 #include <inet/ip_impl.h>
980 #include <inet/sadb.h>
981 #include <inet/ipsecesp.h>
982 #include <inet/ipsecah.h>
983 #include <inet/ip6.h>
984 
985 #include <sys/mac_impl.h>
986 #include <sys/mac_client_impl.h>
987 #include <sys/mac_client_priv.h>
988 #include <sys/mac_soft_ring.h>
989 #include <sys/mac_flow_impl.h>
990 
991 static mac_tx_cookie_t mac_tx_single_ring_mode(mac_soft_ring_set_t *, mblk_t *,
992     uintptr_t, uint16_t, mblk_t **);
993 static mac_tx_cookie_t mac_tx_serializer_mode(mac_soft_ring_set_t *, mblk_t *,
994     uintptr_t, uint16_t, mblk_t **);
995 static mac_tx_cookie_t mac_tx_fanout_mode(mac_soft_ring_set_t *, mblk_t *,
996     uintptr_t, uint16_t, mblk_t **);
997 static mac_tx_cookie_t mac_tx_bw_mode(mac_soft_ring_set_t *, mblk_t *,
998     uintptr_t, uint16_t, mblk_t **);
999 static mac_tx_cookie_t mac_tx_aggr_mode(mac_soft_ring_set_t *, mblk_t *,
1000     uintptr_t, uint16_t, mblk_t **);
1001 
1002 typedef struct mac_tx_mode_s {
1003 	mac_tx_srs_mode_t	mac_tx_mode;
1004 	mac_tx_func_t		mac_tx_func;
1005 } mac_tx_mode_t;
1006 
1007 /*
1008  * There are seven modes of operation on the Tx side. These modes get set
1009  * in mac_tx_srs_setup(). Except for the experimental TX_SERIALIZE mode,
1010  * none of the other modes are user configurable. They get selected by
1011  * the system depending upon whether the link (or flow) has multiple Tx
1012  * rings or a bandwidth configured, or if the link is an aggr, etc.
1013  *
1014  * When the Tx SRS is operating in aggr mode (st_mode) or if there are
1015  * multiple Tx rings owned by Tx SRS, then each Tx ring (pseudo or
1016  * otherwise) will have a soft ring associated with it. These soft rings
1017  * are stored in srs_tx_soft_rings[] array.
1018  *
1019  * Additionally in the case of aggr, there is the st_soft_rings[] array
1020  * in the mac_srs_tx_t structure. This array is used to store the same
1021  * set of soft rings that are present in srs_tx_soft_rings[] array but
1022  * in a different manner. The soft ring associated with the pseudo Tx
1023  * ring is saved at mr_index (of the pseudo ring) in st_soft_rings[]
1024  * array. This helps in quickly getting the soft ring associated with the
1025  * Tx ring when aggr_find_tx_ring() returns the pseudo Tx ring that is to
1026  * be used for transmit.
1027  */
1028 mac_tx_mode_t mac_tx_mode_list[] = {
1029 	{SRS_TX_DEFAULT,	mac_tx_single_ring_mode},
1030 	{SRS_TX_SERIALIZE,	mac_tx_serializer_mode},
1031 	{SRS_TX_FANOUT,		mac_tx_fanout_mode},
1032 	{SRS_TX_BW,		mac_tx_bw_mode},
1033 	{SRS_TX_BW_FANOUT,	mac_tx_bw_mode},
1034 	{SRS_TX_AGGR,		mac_tx_aggr_mode},
1035 	{SRS_TX_BW_AGGR,	mac_tx_bw_mode}
1036 };
1037 
1038 /*
1039  * Soft Ring Set (SRS) - The Run time code that deals with
1040  * dynamic polling from the hardware, bandwidth enforcement,
1041  * fanout etc.
1042  *
1043  * We try to use H/W classification on NIC and assign traffic for
1044  * a MAC address to a particular Rx ring or ring group. There is a
1045  * 1-1 mapping between a SRS and a Rx ring. The SRS dynamically
1046  * switches the underlying Rx ring between interrupt and
1047  * polling mode and enforces any specified B/W control.
1048  *
1049  * There is always a SRS created and tied to each H/W and S/W rule.
1050  * Whenever we create a H/W rule, we always add the the same rule to
1051  * S/W classifier and tie a SRS to it.
1052  *
1053  * In case a B/W control is specified, it is broken into bytes
1054  * per ticks and as soon as the quota for a tick is exhausted,
1055  * the underlying Rx ring is forced into poll mode for remainder of
1056  * the tick. The SRS poll thread only polls for bytes that are
1057  * allowed to come in the SRS. We typically let 4x the configured
1058  * B/W worth of packets to come in the SRS (to prevent unnecessary
1059  * drops due to bursts) but only process the specified amount.
1060  *
1061  * A MAC client (e.g. a VNIC or aggr) can have 1 or more
1062  * Rx rings (and corresponding SRSs) assigned to it. The SRS
1063  * in turn can have softrings to do protocol level fanout or
1064  * softrings to do S/W based fanout or both. In case the NIC
1065  * has no Rx rings, we do S/W classification to respective SRS.
1066  * The S/W classification rule is always setup and ready. This
1067  * allows the MAC layer to reassign Rx rings whenever needed
1068  * but packets still continue to flow via the default path and
1069  * getting S/W classified to correct SRS.
1070  *
1071  * The SRS's are used on both Tx and Rx side. They use the same
1072  * data structure but the processing routines have slightly different
1073  * semantics due to the fact that Rx side needs to do dynamic
1074  * polling etc.
1075  *
1076  * Dynamic Polling Notes
1077  * =====================
1078  *
1079  * Each Soft ring set is capable of switching its Rx ring between
1080  * interrupt and poll mode and actively 'polls' for packets in
1081  * poll mode. If the SRS is implementing a B/W limit, it makes
1082  * sure that only Max allowed packets are pulled in poll mode
1083  * and goes to poll mode as soon as B/W limit is exceeded. As
1084  * such, there are no overheads to implement B/W limits.
1085  *
1086  * In poll mode, its better to keep the pipeline going where the
1087  * SRS worker thread keeps processing packets and poll thread
1088  * keeps bringing more packets (specially if they get to run
1089  * on different CPUs). This also prevents the overheads associated
1090  * by excessive signalling (on NUMA machines, this can be
1091  * pretty devastating). The exception is latency optimized case
1092  * where worker thread does no work and interrupt and poll thread
1093  * are allowed to do their own drain.
1094  *
1095  * We use the following policy to control Dynamic Polling:
1096  * 1) We switch to poll mode anytime the processing
1097  *    thread causes a backlog to build up in SRS and
1098  *    its associated Soft Rings (sr_poll_pkt_cnt > 0).
1099  * 2) As long as the backlog stays under the low water
1100  *    mark (sr_lowat), we poll the H/W for more packets.
1101  * 3) If the backlog (sr_poll_pkt_cnt) exceeds low
1102  *    water mark, we stay in poll mode but don't poll
1103  *    the H/W for more packets.
1104  * 4) Anytime in polling mode, if we poll the H/W for
1105  *    packets and find nothing plus we have an existing
1106  *    backlog (sr_poll_pkt_cnt > 0), we stay in polling
1107  *    mode but don't poll the H/W for packets anymore
1108  *    (let the polling thread go to sleep).
1109  * 5) Once the backlog is relived (packets are processed)
1110  *    we reenable polling (by signalling the poll thread)
1111  *    only when the backlog dips below sr_poll_thres.
1112  * 6) sr_hiwat is used exclusively when we are not
1113  *    polling capable and is used to decide when to
1114  *    drop packets so the SRS queue length doesn't grow
1115  *    infinitely.
1116  *
1117  * NOTE: Also see the block level comment on top of mac_soft_ring.c
1118  */
1119 
1120 /*
1121  * mac_latency_optimize
1122  *
1123  * Controls whether the poll thread can process the packets inline
1124  * or let the SRS worker thread do the processing. This applies if
1125  * the SRS was not being processed. For latency sensitive traffic,
1126  * this needs to be true to allow inline processing. For throughput
1127  * under load, this should be false.
1128  *
1129  * This (and other similar) tunable should be rolled into a link
1130  * or flow specific workload hint that can be set using dladm
1131  * linkprop (instead of multiple such tunables).
1132  */
1133 boolean_t mac_latency_optimize = B_TRUE;
1134 
1135 /*
1136  * MAC_RX_SRS_ENQUEUE_CHAIN and MAC_TX_SRS_ENQUEUE_CHAIN
1137  *
1138  * queue a mp or chain in soft ring set and increment the
1139  * local count (srs_count) for the SRS and the shared counter
1140  * (srs_poll_pkt_cnt - shared between SRS and its soft rings
1141  * to track the total unprocessed packets for polling to work
1142  * correctly).
1143  *
1144  * The size (total bytes queued) counters are incremented only
1145  * if we are doing B/W control.
1146  */
1147 #define	MAC_SRS_ENQUEUE_CHAIN(mac_srs, head, tail, count, sz) {		\
1148 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1149 	if ((mac_srs)->srs_last != NULL)				\
1150 		(mac_srs)->srs_last->b_next = (head);			\
1151 	else								\
1152 		(mac_srs)->srs_first = (head);				\
1153 	(mac_srs)->srs_last = (tail);					\
1154 	(mac_srs)->srs_count += count;					\
1155 }
1156 
1157 #define	MAC_RX_SRS_ENQUEUE_CHAIN(mac_srs, head, tail, count, sz) {	\
1158 	mac_srs_rx_t	*srs_rx = &(mac_srs)->srs_rx;			\
1159 									\
1160 	MAC_SRS_ENQUEUE_CHAIN(mac_srs, head, tail, count, sz);		\
1161 	srs_rx->sr_poll_pkt_cnt += count;				\
1162 	ASSERT(srs_rx->sr_poll_pkt_cnt > 0);				\
1163 	if ((mac_srs)->srs_type & SRST_BW_CONTROL) {			\
1164 		(mac_srs)->srs_size += (sz);				\
1165 		mutex_enter(&(mac_srs)->srs_bw->mac_bw_lock);		\
1166 		(mac_srs)->srs_bw->mac_bw_sz += (sz);			\
1167 		mutex_exit(&(mac_srs)->srs_bw->mac_bw_lock);		\
1168 	}								\
1169 }
1170 
1171 #define	MAC_TX_SRS_ENQUEUE_CHAIN(mac_srs, head, tail, count, sz) {	\
1172 	mac_srs->srs_state |= SRS_ENQUEUED;				\
1173 	MAC_SRS_ENQUEUE_CHAIN(mac_srs, head, tail, count, sz);		\
1174 	if ((mac_srs)->srs_type & SRST_BW_CONTROL) {			\
1175 		(mac_srs)->srs_size += (sz);				\
1176 		(mac_srs)->srs_bw->mac_bw_sz += (sz);			\
1177 	}								\
1178 }
1179 
1180 /*
1181  * Turn polling on routines
1182  */
1183 #define	MAC_SRS_POLLING_ON(mac_srs) {					\
1184 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1185 	if (((mac_srs)->srs_state &					\
1186 	    (SRS_POLLING_CAPAB|SRS_POLLING)) == SRS_POLLING_CAPAB) {	\
1187 		(mac_srs)->srs_state |= SRS_POLLING;			\
1188 		(void) mac_hwring_disable_intr((mac_ring_handle_t)	\
1189 		    (mac_srs)->srs_ring);				\
1190 		(mac_srs)->srs_rx.sr_poll_on++;				\
1191 	}								\
1192 }
1193 
1194 #define	MAC_SRS_WORKER_POLLING_ON(mac_srs) {				\
1195 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1196 	if (((mac_srs)->srs_state &					\
1197 	    (SRS_POLLING_CAPAB|SRS_WORKER|SRS_POLLING)) ==		\
1198 	    (SRS_POLLING_CAPAB|SRS_WORKER)) {				\
1199 		(mac_srs)->srs_state |= SRS_POLLING;			\
1200 		(void) mac_hwring_disable_intr((mac_ring_handle_t)	\
1201 		    (mac_srs)->srs_ring);				\
1202 		(mac_srs)->srs_rx.sr_worker_poll_on++;			\
1203 	}								\
1204 }
1205 
1206 /*
1207  * MAC_SRS_POLL_RING
1208  *
1209  * Signal the SRS poll thread to poll the underlying H/W ring
1210  * provided it wasn't already polling (SRS_GET_PKTS was set).
1211  *
1212  * Poll thread gets to run only from mac_rx_srs_drain() and only
1213  * if the drain was being done by the worker thread.
1214  */
1215 #define	MAC_SRS_POLL_RING(mac_srs) {					\
1216 	mac_srs_rx_t	*srs_rx = &(mac_srs)->srs_rx;			\
1217 									\
1218 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1219 	srs_rx->sr_poll_thr_sig++;					\
1220 	if (((mac_srs)->srs_state &					\
1221 	    (SRS_POLLING_CAPAB|SRS_WORKER|SRS_GET_PKTS)) ==		\
1222 		(SRS_WORKER|SRS_POLLING_CAPAB)) {			\
1223 		(mac_srs)->srs_state |= SRS_GET_PKTS;			\
1224 		cv_signal(&(mac_srs)->srs_cv);				\
1225 	} else {							\
1226 		srs_rx->sr_poll_thr_busy++;				\
1227 	}								\
1228 }
1229 
1230 /*
1231  * MAC_SRS_CHECK_BW_CONTROL
1232  *
1233  * Check to see if next tick has started so we can reset the
1234  * SRS_BW_ENFORCED flag and allow more packets to come in the
1235  * system.
1236  */
1237 #define	MAC_SRS_CHECK_BW_CONTROL(mac_srs) {				\
1238 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1239 	ASSERT(((mac_srs)->srs_type & SRST_TX) ||			\
1240 	    MUTEX_HELD(&(mac_srs)->srs_bw->mac_bw_lock));		\
1241 	clock_t now = ddi_get_lbolt();					\
1242 	if ((mac_srs)->srs_bw->mac_bw_curr_time != now) {		\
1243 		(mac_srs)->srs_bw->mac_bw_curr_time = now;		\
1244 		(mac_srs)->srs_bw->mac_bw_used = 0;			\
1245 		if ((mac_srs)->srs_bw->mac_bw_state & SRS_BW_ENFORCED)	\
1246 			(mac_srs)->srs_bw->mac_bw_state &= ~SRS_BW_ENFORCED; \
1247 	}								\
1248 }
1249 
1250 /*
1251  * MAC_SRS_WORKER_WAKEUP
1252  *
1253  * Wake up the SRS worker thread to process the queue as long as
1254  * no one else is processing the queue. If we are optimizing for
1255  * latency, we wake up the worker thread immediately or else we
1256  * wait mac_srs_worker_wakeup_ticks before worker thread gets
1257  * woken up.
1258  */
1259 int mac_srs_worker_wakeup_ticks = 0;
1260 #define	MAC_SRS_WORKER_WAKEUP(mac_srs) {				\
1261 	ASSERT(MUTEX_HELD(&(mac_srs)->srs_lock));			\
1262 	if (!((mac_srs)->srs_state & SRS_PROC) &&			\
1263 		(mac_srs)->srs_tid == NULL) {				\
1264 		if (((mac_srs)->srs_state & SRS_LATENCY_OPT) ||		\
1265 			(mac_srs_worker_wakeup_ticks == 0))		\
1266 			cv_signal(&(mac_srs)->srs_async);		\
1267 		else							\
1268 			(mac_srs)->srs_tid =				\
1269 				timeout(mac_srs_fire, (mac_srs),	\
1270 					mac_srs_worker_wakeup_ticks);	\
1271 	}								\
1272 }
1273 
1274 #define	TX_BANDWIDTH_MODE(mac_srs)				\
1275 	((mac_srs)->srs_tx.st_mode == SRS_TX_BW ||		\
1276 	    (mac_srs)->srs_tx.st_mode == SRS_TX_BW_FANOUT ||	\
1277 	    (mac_srs)->srs_tx.st_mode == SRS_TX_BW_AGGR)
1278 
1279 #define	TX_SRS_TO_SOFT_RING(mac_srs, head, hint) {			\
1280 	if (tx_mode == SRS_TX_BW_FANOUT)				\
1281 		(void) mac_tx_fanout_mode(mac_srs, head, hint, 0, NULL);\
1282 	else								\
1283 		(void) mac_tx_aggr_mode(mac_srs, head, hint, 0, NULL);	\
1284 }
1285 
1286 /*
1287  * MAC_TX_SRS_BLOCK
1288  *
1289  * Always called from mac_tx_srs_drain() function. SRS_TX_BLOCKED
1290  * will be set only if srs_tx_woken_up is FALSE. If
1291  * srs_tx_woken_up is TRUE, it indicates that the wakeup arrived
1292  * before we grabbed srs_lock to set SRS_TX_BLOCKED. We need to
1293  * attempt to transmit again and not setting SRS_TX_BLOCKED does
1294  * that.
1295  */
1296 #define	MAC_TX_SRS_BLOCK(srs, mp)	{			\
1297 	ASSERT(MUTEX_HELD(&(srs)->srs_lock));			\
1298 	if ((srs)->srs_tx.st_woken_up) {			\
1299 		(srs)->srs_tx.st_woken_up = B_FALSE;		\
1300 	} else {						\
1301 		ASSERT(!((srs)->srs_state & SRS_TX_BLOCKED));	\
1302 		(srs)->srs_state |= SRS_TX_BLOCKED;		\
1303 		(srs)->srs_tx.st_stat.mts_blockcnt++;		\
1304 	}							\
1305 }
1306 
1307 /*
1308  * MAC_TX_SRS_TEST_HIWAT
1309  *
1310  * Called before queueing a packet onto Tx SRS to test and set
1311  * SRS_TX_HIWAT if srs_count exceeds srs_tx_hiwat.
1312  */
1313 #define	MAC_TX_SRS_TEST_HIWAT(srs, mp, tail, cnt, sz, cookie) {		\
1314 	boolean_t enqueue = 1;						\
1315 									\
1316 	if ((srs)->srs_count > (srs)->srs_tx.st_hiwat) {		\
1317 		/*							\
1318 		 * flow-controlled. Store srs in cookie so that it	\
1319 		 * can be returned as mac_tx_cookie_t to client		\
1320 		 */							\
1321 		(srs)->srs_state |= SRS_TX_HIWAT;			\
1322 		cookie = (mac_tx_cookie_t)srs;				\
1323 		(srs)->srs_tx.st_hiwat_cnt++;				\
1324 		if ((srs)->srs_count > (srs)->srs_tx.st_max_q_cnt) {	\
1325 			/* increment freed stats */			\
1326 			(srs)->srs_tx.st_stat.mts_sdrops += cnt;	\
1327 			/*						\
1328 			 * b_prev may be set to the fanout hint		\
1329 			 * hence can't use freemsg directly		\
1330 			 */						\
1331 			mac_drop_chain(mp_chain, "SRS Tx max queue");	\
1332 			DTRACE_PROBE1(tx_queued_hiwat,			\
1333 			    mac_soft_ring_set_t *, srs);		\
1334 			enqueue = 0;					\
1335 		}							\
1336 	}								\
1337 	if (enqueue)							\
1338 		MAC_TX_SRS_ENQUEUE_CHAIN(srs, mp, tail, cnt, sz);	\
1339 }
1340 
1341 /* Some utility macros */
1342 #define	MAC_SRS_BW_LOCK(srs)						\
1343 	if (!(srs->srs_type & SRST_TX))					\
1344 		mutex_enter(&srs->srs_bw->mac_bw_lock);
1345 
1346 #define	MAC_SRS_BW_UNLOCK(srs)						\
1347 	if (!(srs->srs_type & SRST_TX))					\
1348 		mutex_exit(&srs->srs_bw->mac_bw_lock);
1349 
1350 #define	MAC_TX_SRS_DROP_MESSAGE(srs, chain, cookie, s) {	\
1351 	mac_drop_chain((chain), (s));				\
1352 	/* increment freed stats */				\
1353 	(srs)->srs_tx.st_stat.mts_sdrops++;			\
1354 	(cookie) = (mac_tx_cookie_t)(srs);			\
1355 }
1356 
1357 #define	MAC_TX_SET_NO_ENQUEUE(srs, mp_chain, ret_mp, cookie) {		\
1358 	mac_srs->srs_state |= SRS_TX_WAKEUP_CLIENT;			\
1359 	cookie = (mac_tx_cookie_t)srs;					\
1360 	*ret_mp = mp_chain;						\
1361 }
1362 
1363 /*
1364  * MAC_RX_SRS_TOODEEP
1365  *
1366  * Macro called as part of receive-side processing to determine if handling
1367  * can occur in situ (in the interrupt thread) or if it should be left to a
1368  * worker thread.  Note that the constant used to make this determination is
1369  * not entirely made-up, and is a result of some emprical validation. That
1370  * said, the constant is left as a static variable to allow it to be
1371  * dynamically tuned in the field if and as needed.
1372  */
1373 static uintptr_t mac_rx_srs_stack_needed = 10240;
1374 static uint_t mac_rx_srs_stack_toodeep;
1375 
1376 #ifndef STACK_GROWTH_DOWN
1377 #error Downward stack growth assumed.
1378 #endif
1379 
1380 #define	MAC_RX_SRS_TOODEEP() (STACK_BIAS + (uintptr_t)getfp() - \
1381 	(uintptr_t)curthread->t_stkbase < mac_rx_srs_stack_needed && \
1382 	++mac_rx_srs_stack_toodeep)
1383 
1384 
1385 /*
1386  * Drop the rx packet and advance to the next one in the chain.
1387  */
1388 static void
1389 mac_rx_drop_pkt(mac_soft_ring_set_t *srs, mblk_t *mp)
1390 {
1391 	mac_srs_rx_t	*srs_rx = &srs->srs_rx;
1392 
1393 	ASSERT(mp->b_next == NULL);
1394 	mutex_enter(&srs->srs_lock);
1395 	MAC_UPDATE_SRS_COUNT_LOCKED(srs, 1);
1396 	MAC_UPDATE_SRS_SIZE_LOCKED(srs, msgdsize(mp));
1397 	mutex_exit(&srs->srs_lock);
1398 
1399 	srs_rx->sr_stat.mrs_sdrops++;
1400 	freemsg(mp);
1401 }
1402 
1403 /* DATAPATH RUNTIME ROUTINES */
1404 
1405 /*
1406  * mac_srs_fire
1407  *
1408  * Timer callback routine for waking up the SRS worker thread.
1409  */
1410 static void
1411 mac_srs_fire(void *arg)
1412 {
1413 	mac_soft_ring_set_t *mac_srs = (mac_soft_ring_set_t *)arg;
1414 
1415 	mutex_enter(&mac_srs->srs_lock);
1416 	if (mac_srs->srs_tid == NULL) {
1417 		mutex_exit(&mac_srs->srs_lock);
1418 		return;
1419 	}
1420 
1421 	mac_srs->srs_tid = NULL;
1422 	if (!(mac_srs->srs_state & SRS_PROC))
1423 		cv_signal(&mac_srs->srs_async);
1424 
1425 	mutex_exit(&mac_srs->srs_lock);
1426 }
1427 
1428 /*
1429  * 'hint' is fanout_hint (type of uint64_t) which is given by the TCP/IP stack,
1430  * and it is used on the TX path.
1431  */
1432 #define	HASH_HINT(hint)	\
1433 	((hint) ^ ((hint) >> 24) ^ ((hint) >> 16) ^ ((hint) >> 8))
1434 
1435 
1436 /*
1437  * hash based on the src address, dst address and the port information.
1438  */
1439 #define	HASH_ADDR(src, dst, ports)					\
1440 	(ntohl((src) + (dst)) ^ ((ports) >> 24) ^ ((ports) >> 16) ^	\
1441 	((ports) >> 8) ^ (ports))
1442 
1443 #define	COMPUTE_INDEX(key, sz)	(key % sz)
1444 
1445 #define	FANOUT_ENQUEUE_MP(head, tail, cnt, bw_ctl, sz, sz0, mp) {	\
1446 	if ((tail) != NULL) {						\
1447 		ASSERT((tail)->b_next == NULL);				\
1448 		(tail)->b_next = (mp);					\
1449 	} else {							\
1450 		ASSERT((head) == NULL);					\
1451 		(head) = (mp);						\
1452 	}								\
1453 	(tail) = (mp);							\
1454 	(cnt)++;							\
1455 	if ((bw_ctl))							\
1456 		(sz) += (sz0);						\
1457 }
1458 
1459 #define	MAC_FANOUT_DEFAULT	0
1460 #define	MAC_FANOUT_RND_ROBIN	1
1461 int mac_fanout_type = MAC_FANOUT_DEFAULT;
1462 
1463 #define	MAX_SR_TYPES	3
1464 /* fanout types for port based hashing */
1465 enum pkt_type {
1466 	V4_TCP = 0,
1467 	V4_UDP,
1468 	OTH,
1469 	UNDEF
1470 };
1471 
1472 /*
1473  * Pair of local and remote ports in the transport header
1474  */
1475 #define	PORTS_SIZE 4
1476 
1477 /*
1478  * This routine delivers packets destined for an SRS into one of the
1479  * protocol soft rings.
1480  *
1481  * Given a chain of packets we need to split it up into multiple sub
1482  * chains: TCP, UDP or OTH soft ring. Instead of entering the soft
1483  * ring one packet at a time, we want to enter it in the form of a
1484  * chain otherwise we get this start/stop behaviour where the worker
1485  * thread goes to sleep and then next packet comes in forcing it to
1486  * wake up.
1487  */
1488 static void
1489 mac_rx_srs_proto_fanout(mac_soft_ring_set_t *mac_srs, mblk_t *head)
1490 {
1491 	struct ether_header		*ehp;
1492 	struct ether_vlan_header	*evhp;
1493 	uint32_t			sap;
1494 	ipha_t				*ipha;
1495 	uint8_t				*dstaddr;
1496 	size_t				hdrsize;
1497 	mblk_t				*mp;
1498 	mblk_t				*headmp[MAX_SR_TYPES];
1499 	mblk_t				*tailmp[MAX_SR_TYPES];
1500 	int				cnt[MAX_SR_TYPES];
1501 	size_t				sz[MAX_SR_TYPES];
1502 	size_t				sz1;
1503 	boolean_t			bw_ctl;
1504 	boolean_t			hw_classified;
1505 	boolean_t			dls_bypass;
1506 	boolean_t			is_ether;
1507 	boolean_t			is_unicast;
1508 	enum pkt_type			type;
1509 	mac_client_impl_t		*mcip = mac_srs->srs_mcip;
1510 
1511 	is_ether = (mcip->mci_mip->mi_info.mi_nativemedia == DL_ETHER);
1512 	bw_ctl = ((mac_srs->srs_type & SRST_BW_CONTROL) != 0);
1513 
1514 	/*
1515 	 * If we don't have a Rx ring, S/W classification would have done
1516 	 * its job and its a packet meant for us. If we were polling on
1517 	 * the default ring (i.e. there was a ring assigned to this SRS),
1518 	 * then we need to make sure that the mac address really belongs
1519 	 * to us.
1520 	 */
1521 	hw_classified = mac_srs->srs_ring != NULL &&
1522 	    mac_srs->srs_ring->mr_classify_type == MAC_HW_CLASSIFIER;
1523 
1524 	/*
1525 	 * Some clients, such as non-ethernet, need DLS processing in
1526 	 * the Rx path. Such clients clear the SRST_DLS_BYPASS flag.
1527 	 * DLS bypass may also be disabled via the
1528 	 * MCIS_RX_BYPASS_DISABLE flag.
1529 	 */
1530 	dls_bypass = ((mac_srs->srs_type & SRST_DLS_BYPASS) != 0) &&
1531 	    ((mcip->mci_state_flags & MCIS_RX_BYPASS_DISABLE) == 0);
1532 
1533 	bzero(headmp, MAX_SR_TYPES * sizeof (mblk_t *));
1534 	bzero(tailmp, MAX_SR_TYPES * sizeof (mblk_t *));
1535 	bzero(cnt, MAX_SR_TYPES * sizeof (int));
1536 	bzero(sz, MAX_SR_TYPES * sizeof (size_t));
1537 
1538 	/*
1539 	 * We have a chain from SRS that we need to split across the
1540 	 * soft rings. The squeues for the TCP and IPv4 SAPs use their
1541 	 * own soft rings to allow polling from the squeue. The rest of
1542 	 * the packets are delivered on the OTH soft ring which cannot
1543 	 * be polled.
1544 	 */
1545 	while (head != NULL) {
1546 		mp = head;
1547 		head = head->b_next;
1548 		mp->b_next = NULL;
1549 
1550 		type = OTH;
1551 		sz1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
1552 
1553 		if (is_ether) {
1554 			/*
1555 			 * At this point we can be sure the packet at least
1556 			 * has an ether header.
1557 			 */
1558 			if (sz1 < sizeof (struct ether_header)) {
1559 				mac_rx_drop_pkt(mac_srs, mp);
1560 				continue;
1561 			}
1562 			ehp = (struct ether_header *)mp->b_rptr;
1563 
1564 			/*
1565 			 * Determine if this is a VLAN or non-VLAN packet.
1566 			 */
1567 			if ((sap = ntohs(ehp->ether_type)) == VLAN_TPID) {
1568 				evhp = (struct ether_vlan_header *)mp->b_rptr;
1569 				sap = ntohs(evhp->ether_type);
1570 				hdrsize = sizeof (struct ether_vlan_header);
1571 
1572 				/*
1573 				 * Check if the VID of the packet, if
1574 				 * any, belongs to this client.
1575 				 * Technically, if this packet came up
1576 				 * via a HW classified ring then we
1577 				 * don't need to perform this check.
1578 				 * Perhaps a future optimization.
1579 				 */
1580 				if (!mac_client_check_flow_vid(mcip,
1581 				    VLAN_ID(ntohs(evhp->ether_tci)))) {
1582 					mac_rx_drop_pkt(mac_srs, mp);
1583 					continue;
1584 				}
1585 			} else {
1586 				hdrsize = sizeof (struct ether_header);
1587 			}
1588 			is_unicast =
1589 			    ((((uint8_t *)&ehp->ether_dhost)[0] & 0x01) == 0);
1590 			dstaddr = (uint8_t *)&ehp->ether_dhost;
1591 		} else {
1592 			mac_header_info_t		mhi;
1593 
1594 			if (mac_header_info((mac_handle_t)mcip->mci_mip,
1595 			    mp, &mhi) != 0) {
1596 				mac_rx_drop_pkt(mac_srs, mp);
1597 				continue;
1598 			}
1599 			hdrsize = mhi.mhi_hdrsize;
1600 			sap = mhi.mhi_bindsap;
1601 			is_unicast = (mhi.mhi_dsttype == MAC_ADDRTYPE_UNICAST);
1602 			dstaddr = (uint8_t *)mhi.mhi_daddr;
1603 		}
1604 
1605 		if (!dls_bypass) {
1606 			FANOUT_ENQUEUE_MP(headmp[type], tailmp[type],
1607 			    cnt[type], bw_ctl, sz[type], sz1, mp);
1608 			continue;
1609 		}
1610 
1611 		if (sap == ETHERTYPE_IP) {
1612 			/*
1613 			 * If we are H/W classified, but we have promisc
1614 			 * on, then we need to check for the unicast address.
1615 			 */
1616 			if (hw_classified && mcip->mci_promisc_list != NULL) {
1617 				mac_address_t		*map;
1618 
1619 				rw_enter(&mcip->mci_rw_lock, RW_READER);
1620 				map = mcip->mci_unicast;
1621 				if (bcmp(dstaddr, map->ma_addr,
1622 				    map->ma_len) == 0)
1623 					type = UNDEF;
1624 				rw_exit(&mcip->mci_rw_lock);
1625 			} else if (is_unicast) {
1626 				type = UNDEF;
1627 			}
1628 		}
1629 
1630 		/*
1631 		 * This needs to become a contract with the driver for
1632 		 * the fast path.
1633 		 *
1634 		 * In the normal case the packet will have at least the L2
1635 		 * header and the IP + Transport header in the same mblk.
1636 		 * This is usually the case when the NIC driver sends up
1637 		 * the packet. This is also true when the stack generates
1638 		 * a packet that is looped back and when the stack uses the
1639 		 * fastpath mechanism. The normal case is optimized for
1640 		 * performance and may bypass DLS. All other cases go through
1641 		 * the 'OTH' type path without DLS bypass.
1642 		 */
1643 		ipha = (ipha_t *)(mp->b_rptr + hdrsize);
1644 		if ((type != OTH) && MBLK_RX_FANOUT_SLOWPATH(mp, ipha))
1645 			type = OTH;
1646 
1647 		if (type == OTH) {
1648 			FANOUT_ENQUEUE_MP(headmp[type], tailmp[type],
1649 			    cnt[type], bw_ctl, sz[type], sz1, mp);
1650 			continue;
1651 		}
1652 
1653 		ASSERT(type == UNDEF);
1654 
1655 		/*
1656 		 * Determine the type from the IP protocol value. If
1657 		 * classified as TCP or UDP, then update the read
1658 		 * pointer to the beginning of the IP header.
1659 		 * Otherwise leave the message as is for further
1660 		 * processing by DLS.
1661 		 */
1662 		switch (ipha->ipha_protocol) {
1663 		case IPPROTO_TCP:
1664 			type = V4_TCP;
1665 			mp->b_rptr += hdrsize;
1666 			break;
1667 		case IPPROTO_UDP:
1668 			type = V4_UDP;
1669 			mp->b_rptr += hdrsize;
1670 			break;
1671 		default:
1672 			type = OTH;
1673 			break;
1674 		}
1675 
1676 		FANOUT_ENQUEUE_MP(headmp[type], tailmp[type], cnt[type],
1677 		    bw_ctl, sz[type], sz1, mp);
1678 	}
1679 
1680 	for (type = V4_TCP; type < UNDEF; type++) {
1681 		if (headmp[type] != NULL) {
1682 			mac_soft_ring_t			*softring;
1683 
1684 			ASSERT(tailmp[type]->b_next == NULL);
1685 			switch (type) {
1686 			case V4_TCP:
1687 				softring = mac_srs->srs_tcp_soft_rings[0];
1688 				break;
1689 			case V4_UDP:
1690 				softring = mac_srs->srs_udp_soft_rings[0];
1691 				break;
1692 			case OTH:
1693 				softring = mac_srs->srs_oth_soft_rings[0];
1694 			}
1695 			mac_rx_soft_ring_process(mcip, softring,
1696 			    headmp[type], tailmp[type], cnt[type], sz[type]);
1697 		}
1698 	}
1699 }
1700 
1701 int	fanout_unaligned = 0;
1702 
1703 /*
1704  * The fanout routine for any clients with DLS bypass disabled or for
1705  * traffic classified as "other". Returns -1 on an error (drop the
1706  * packet due to a malformed packet), 0 on success, with values
1707  * written in *indx and *type.
1708  */
1709 static int
1710 mac_rx_srs_long_fanout(mac_soft_ring_set_t *mac_srs, mblk_t *mp,
1711     uint32_t sap, size_t hdrsize, enum pkt_type *type, uint_t *indx)
1712 {
1713 	ip6_t		*ip6h;
1714 	ipha_t		*ipha;
1715 	uint8_t		*whereptr;
1716 	uint_t		hash;
1717 	uint16_t	remlen;
1718 	uint8_t		nexthdr;
1719 	uint16_t	hdr_len;
1720 	uint32_t	src_val, dst_val;
1721 	boolean_t	modifiable = B_TRUE;
1722 	boolean_t	v6;
1723 
1724 	ASSERT(MBLKL(mp) >= hdrsize);
1725 
1726 	if (sap == ETHERTYPE_IPV6) {
1727 		v6 = B_TRUE;
1728 		hdr_len = IPV6_HDR_LEN;
1729 	} else if (sap == ETHERTYPE_IP) {
1730 		v6 = B_FALSE;
1731 		hdr_len = IP_SIMPLE_HDR_LENGTH;
1732 	} else {
1733 		*indx = 0;
1734 		*type = OTH;
1735 		return (0);
1736 	}
1737 
1738 	ip6h = (ip6_t *)(mp->b_rptr + hdrsize);
1739 	ipha = (ipha_t *)ip6h;
1740 
1741 	if ((uint8_t *)ip6h == mp->b_wptr) {
1742 		/*
1743 		 * The first mblk_t only includes the mac header.
1744 		 * Note that it is safe to change the mp pointer here,
1745 		 * as the subsequent operation does not assume mp
1746 		 * points to the start of the mac header.
1747 		 */
1748 		mp = mp->b_cont;
1749 
1750 		/*
1751 		 * Make sure the IP header points to an entire one.
1752 		 */
1753 		if (mp == NULL)
1754 			return (-1);
1755 
1756 		if (MBLKL(mp) < hdr_len) {
1757 			modifiable = (DB_REF(mp) == 1);
1758 
1759 			if (modifiable && !pullupmsg(mp, hdr_len))
1760 				return (-1);
1761 		}
1762 
1763 		ip6h = (ip6_t *)mp->b_rptr;
1764 		ipha = (ipha_t *)ip6h;
1765 	}
1766 
1767 	if (!modifiable || !(OK_32PTR((char *)ip6h)) ||
1768 	    ((uint8_t *)ip6h + hdr_len > mp->b_wptr)) {
1769 		/*
1770 		 * If either the IP header is not aligned, or it does not hold
1771 		 * the complete simple structure (a pullupmsg() is not an
1772 		 * option since it would result in an unaligned IP header),
1773 		 * fanout to the default ring.
1774 		 *
1775 		 * Note that this may cause packet reordering.
1776 		 */
1777 		*indx = 0;
1778 		*type = OTH;
1779 		fanout_unaligned++;
1780 		return (0);
1781 	}
1782 
1783 	/*
1784 	 * Extract next-header, full header length, and source-hash value
1785 	 * using v4/v6 specific fields.
1786 	 */
1787 	if (v6) {
1788 		remlen = ntohs(ip6h->ip6_plen);
1789 		nexthdr = ip6h->ip6_nxt;
1790 		src_val = V4_PART_OF_V6(ip6h->ip6_src);
1791 		dst_val = V4_PART_OF_V6(ip6h->ip6_dst);
1792 		/*
1793 		 * Do src based fanout if below tunable is set to B_TRUE or
1794 		 * when mac_ip_hdr_length_v6() fails because of malformed
1795 		 * packets or because mblks need to be concatenated using
1796 		 * pullupmsg().
1797 		 *
1798 		 * Perform a version check to prevent parsing weirdness...
1799 		 */
1800 		if (IPH_HDR_VERSION(ip6h) != IPV6_VERSION ||
1801 		    !mac_ip_hdr_length_v6(ip6h, mp->b_wptr, &hdr_len, &nexthdr,
1802 		    NULL)) {
1803 			goto src_dst_based_fanout;
1804 		}
1805 	} else {
1806 		hdr_len = IPH_HDR_LENGTH(ipha);
1807 		remlen = ntohs(ipha->ipha_length) - hdr_len;
1808 		nexthdr = ipha->ipha_protocol;
1809 		src_val = (uint32_t)ipha->ipha_src;
1810 		dst_val = (uint32_t)ipha->ipha_dst;
1811 		/*
1812 		 * Catch IPv4 fragment case here.  IPv6 has nexthdr == FRAG
1813 		 * for its equivalent case.
1814 		 */
1815 		if ((ntohs(ipha->ipha_fragment_offset_and_flags) &
1816 		    (IPH_MF | IPH_OFFSET)) != 0) {
1817 			goto src_dst_based_fanout;
1818 		}
1819 	}
1820 	if (remlen < MIN_EHDR_LEN)
1821 		return (-1);
1822 	whereptr = (uint8_t *)ip6h + hdr_len;
1823 
1824 	/* If the transport is one of below, we do port/SPI based fanout */
1825 	switch (nexthdr) {
1826 	case IPPROTO_TCP:
1827 	case IPPROTO_UDP:
1828 	case IPPROTO_SCTP:
1829 	case IPPROTO_ESP:
1830 		/*
1831 		 * If the ports or SPI in the transport header is not part of
1832 		 * the mblk, do src_based_fanout, instead of calling
1833 		 * pullupmsg().
1834 		 */
1835 		if (mp->b_cont == NULL || whereptr + PORTS_SIZE <= mp->b_wptr)
1836 			break;	/* out of switch... */
1837 		/* FALLTHRU */
1838 	default:
1839 		goto src_dst_based_fanout;
1840 	}
1841 
1842 	switch (nexthdr) {
1843 	case IPPROTO_TCP:
1844 		hash = HASH_ADDR(src_val, dst_val, *(uint32_t *)whereptr);
1845 		*indx = COMPUTE_INDEX(hash, mac_srs->srs_tcp_ring_count);
1846 		*type = OTH;
1847 		break;
1848 	case IPPROTO_UDP:
1849 	case IPPROTO_SCTP:
1850 	case IPPROTO_ESP:
1851 		if (mac_fanout_type == MAC_FANOUT_DEFAULT) {
1852 			hash = HASH_ADDR(src_val, dst_val,
1853 			    *(uint32_t *)whereptr);
1854 			*indx = COMPUTE_INDEX(hash,
1855 			    mac_srs->srs_udp_ring_count);
1856 		} else {
1857 			*indx = mac_srs->srs_ind % mac_srs->srs_udp_ring_count;
1858 			mac_srs->srs_ind++;
1859 		}
1860 		*type = OTH;
1861 		break;
1862 	}
1863 	return (0);
1864 
1865 src_dst_based_fanout:
1866 	hash = HASH_ADDR(src_val, dst_val, (uint32_t)0);
1867 	*indx = COMPUTE_INDEX(hash, mac_srs->srs_oth_ring_count);
1868 	*type = OTH;
1869 	return (0);
1870 }
1871 
1872 /*
1873  * This routine delivers packets destined for an SRS into a soft ring member
1874  * of the set.
1875  *
1876  * Given a chain of packets we need to split it up into multiple sub
1877  * chains: TCP, UDP or OTH soft ring. Instead of entering the soft
1878  * ring one packet at a time, we want to enter it in the form of a
1879  * chain otherwise we get this start/stop behaviour where the worker
1880  * thread goes to sleep and then next packet comes in forcing it to
1881  * wake up.
1882  *
1883  * Note:
1884  * Since we know what is the maximum fanout possible, we create a 2D array
1885  * of 'softring types * MAX_SR_FANOUT' for the head, tail, cnt and sz
1886  * variables so that we can enter the softrings with chain. We need the
1887  * MAX_SR_FANOUT so we can allocate the arrays on the stack (a kmem_alloc
1888  * for each packet would be expensive). If we ever want to have the
1889  * ability to have unlimited fanout, we should probably declare a head,
1890  * tail, cnt, sz with each soft ring (a data struct which contains a softring
1891  * along with these members) and create an array of this uber struct so we
1892  * don't have to do kmem_alloc.
1893  */
1894 int	fanout_oth1 = 0;
1895 int	fanout_oth2 = 0;
1896 int	fanout_oth3 = 0;
1897 int	fanout_oth4 = 0;
1898 int	fanout_oth5 = 0;
1899 
1900 static void
1901 mac_rx_srs_fanout(mac_soft_ring_set_t *mac_srs, mblk_t *head)
1902 {
1903 	struct ether_header		*ehp;
1904 	struct ether_vlan_header	*evhp;
1905 	uint32_t			sap;
1906 	ipha_t				*ipha;
1907 	uint8_t				*dstaddr;
1908 	uint_t				indx;
1909 	size_t				ports_offset;
1910 	size_t				ipha_len;
1911 	size_t				hdrsize;
1912 	uint_t				hash;
1913 	mblk_t				*mp;
1914 	mblk_t				*headmp[MAX_SR_TYPES][MAX_SR_FANOUT];
1915 	mblk_t				*tailmp[MAX_SR_TYPES][MAX_SR_FANOUT];
1916 	int				cnt[MAX_SR_TYPES][MAX_SR_FANOUT];
1917 	size_t				sz[MAX_SR_TYPES][MAX_SR_FANOUT];
1918 	size_t				sz1;
1919 	boolean_t			bw_ctl;
1920 	boolean_t			hw_classified;
1921 	boolean_t			dls_bypass;
1922 	boolean_t			is_ether;
1923 	boolean_t			is_unicast;
1924 	int				fanout_cnt;
1925 	enum pkt_type			type;
1926 	mac_client_impl_t		*mcip = mac_srs->srs_mcip;
1927 
1928 	is_ether = (mcip->mci_mip->mi_info.mi_nativemedia == DL_ETHER);
1929 	bw_ctl = ((mac_srs->srs_type & SRST_BW_CONTROL) != 0);
1930 
1931 	/*
1932 	 * If we don't have a Rx ring, S/W classification would have done
1933 	 * its job and its a packet meant for us. If we were polling on
1934 	 * the default ring (i.e. there was a ring assigned to this SRS),
1935 	 * then we need to make sure that the mac address really belongs
1936 	 * to us.
1937 	 */
1938 	hw_classified = mac_srs->srs_ring != NULL &&
1939 	    mac_srs->srs_ring->mr_classify_type == MAC_HW_CLASSIFIER;
1940 
1941 	/*
1942 	 * Some clients, such as non Ethernet, need DLS processing in
1943 	 * the Rx path. Such clients clear the SRST_DLS_BYPASS flag.
1944 	 * DLS bypass may also be disabled via the
1945 	 * MCIS_RX_BYPASS_DISABLE flag, but this is only consumed by
1946 	 * sun4v vsw currently.
1947 	 */
1948 	dls_bypass = ((mac_srs->srs_type & SRST_DLS_BYPASS) != 0) &&
1949 	    ((mcip->mci_state_flags & MCIS_RX_BYPASS_DISABLE) == 0);
1950 
1951 	/*
1952 	 * Since the softrings are never destroyed and we always
1953 	 * create equal number of softrings for TCP, UDP and rest,
1954 	 * its OK to check one of them for count and use it without
1955 	 * any lock. In future, if soft rings get destroyed because
1956 	 * of reduction in fanout, we will need to ensure that happens
1957 	 * behind the SRS_PROC.
1958 	 */
1959 	fanout_cnt = mac_srs->srs_tcp_ring_count;
1960 
1961 	bzero(headmp, MAX_SR_TYPES * MAX_SR_FANOUT * sizeof (mblk_t *));
1962 	bzero(tailmp, MAX_SR_TYPES * MAX_SR_FANOUT * sizeof (mblk_t *));
1963 	bzero(cnt, MAX_SR_TYPES * MAX_SR_FANOUT * sizeof (int));
1964 	bzero(sz, MAX_SR_TYPES * MAX_SR_FANOUT * sizeof (size_t));
1965 
1966 	/*
1967 	 * We got a chain from SRS that we need to send to the soft rings.
1968 	 * Since squeues for TCP & IPv4 SAP poll their soft rings (for
1969 	 * performance reasons), we need to separate out v4_tcp, v4_udp
1970 	 * and the rest goes in other.
1971 	 */
1972 	while (head != NULL) {
1973 		mp = head;
1974 		head = head->b_next;
1975 		mp->b_next = NULL;
1976 
1977 		type = OTH;
1978 		sz1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
1979 
1980 		if (is_ether) {
1981 			/*
1982 			 * At this point we can be sure the packet at least
1983 			 * has an ether header.
1984 			 */
1985 			if (sz1 < sizeof (struct ether_header)) {
1986 				mac_rx_drop_pkt(mac_srs, mp);
1987 				continue;
1988 			}
1989 			ehp = (struct ether_header *)mp->b_rptr;
1990 
1991 			/*
1992 			 * Determine if this is a VLAN or non-VLAN packet.
1993 			 */
1994 			if ((sap = ntohs(ehp->ether_type)) == VLAN_TPID) {
1995 				evhp = (struct ether_vlan_header *)mp->b_rptr;
1996 				sap = ntohs(evhp->ether_type);
1997 				hdrsize = sizeof (struct ether_vlan_header);
1998 
1999 				/*
2000 				 * Check if the VID of the packet, if
2001 				 * any, belongs to this client.
2002 				 * Technically, if this packet came up
2003 				 * via a HW classified ring then we
2004 				 * don't need to perform this check.
2005 				 * Perhaps a future optimization.
2006 				 */
2007 				if (!mac_client_check_flow_vid(mcip,
2008 				    VLAN_ID(ntohs(evhp->ether_tci)))) {
2009 					mac_rx_drop_pkt(mac_srs, mp);
2010 					continue;
2011 				}
2012 			} else {
2013 				hdrsize = sizeof (struct ether_header);
2014 			}
2015 			is_unicast =
2016 			    ((((uint8_t *)&ehp->ether_dhost)[0] & 0x01) == 0);
2017 			dstaddr = (uint8_t *)&ehp->ether_dhost;
2018 		} else {
2019 			mac_header_info_t		mhi;
2020 
2021 			if (mac_header_info((mac_handle_t)mcip->mci_mip,
2022 			    mp, &mhi) != 0) {
2023 				mac_rx_drop_pkt(mac_srs, mp);
2024 				continue;
2025 			}
2026 			hdrsize = mhi.mhi_hdrsize;
2027 			sap = mhi.mhi_bindsap;
2028 			is_unicast = (mhi.mhi_dsttype == MAC_ADDRTYPE_UNICAST);
2029 			dstaddr = (uint8_t *)mhi.mhi_daddr;
2030 		}
2031 
2032 		if (!dls_bypass) {
2033 			if (mac_rx_srs_long_fanout(mac_srs, mp, sap,
2034 			    hdrsize, &type, &indx) == -1) {
2035 				mac_rx_drop_pkt(mac_srs, mp);
2036 				continue;
2037 			}
2038 
2039 			FANOUT_ENQUEUE_MP(headmp[type][indx],
2040 			    tailmp[type][indx], cnt[type][indx], bw_ctl,
2041 			    sz[type][indx], sz1, mp);
2042 			continue;
2043 		}
2044 
2045 		/*
2046 		 * If we are using the default Rx ring where H/W or S/W
2047 		 * classification has not happened, we need to verify if
2048 		 * this unicast packet really belongs to us.
2049 		 */
2050 		if (sap == ETHERTYPE_IP) {
2051 			/*
2052 			 * If we are H/W classified, but we have promisc
2053 			 * on, then we need to check for the unicast address.
2054 			 */
2055 			if (hw_classified && mcip->mci_promisc_list != NULL) {
2056 				mac_address_t		*map;
2057 
2058 				rw_enter(&mcip->mci_rw_lock, RW_READER);
2059 				map = mcip->mci_unicast;
2060 				if (bcmp(dstaddr, map->ma_addr,
2061 				    map->ma_len) == 0)
2062 					type = UNDEF;
2063 				rw_exit(&mcip->mci_rw_lock);
2064 			} else if (is_unicast) {
2065 				type = UNDEF;
2066 			}
2067 		}
2068 
2069 		/*
2070 		 * This needs to become a contract with the driver for
2071 		 * the fast path.
2072 		 */
2073 
2074 		ipha = (ipha_t *)(mp->b_rptr + hdrsize);
2075 		if ((type != OTH) && MBLK_RX_FANOUT_SLOWPATH(mp, ipha)) {
2076 			type = OTH;
2077 			fanout_oth1++;
2078 		}
2079 
2080 		if (type != OTH) {
2081 			uint16_t	frag_offset_flags;
2082 
2083 			switch (ipha->ipha_protocol) {
2084 			case IPPROTO_TCP:
2085 			case IPPROTO_UDP:
2086 			case IPPROTO_SCTP:
2087 			case IPPROTO_ESP:
2088 				ipha_len = IPH_HDR_LENGTH(ipha);
2089 				if ((uchar_t *)ipha + ipha_len + PORTS_SIZE >
2090 				    mp->b_wptr) {
2091 					type = OTH;
2092 					break;
2093 				}
2094 				frag_offset_flags =
2095 				    ntohs(ipha->ipha_fragment_offset_and_flags);
2096 				if ((frag_offset_flags &
2097 				    (IPH_MF | IPH_OFFSET)) != 0) {
2098 					type = OTH;
2099 					fanout_oth3++;
2100 					break;
2101 				}
2102 				ports_offset = hdrsize + ipha_len;
2103 				break;
2104 			default:
2105 				type = OTH;
2106 				fanout_oth4++;
2107 				break;
2108 			}
2109 		}
2110 
2111 		if (type == OTH) {
2112 			if (mac_rx_srs_long_fanout(mac_srs, mp, sap,
2113 			    hdrsize, &type, &indx) == -1) {
2114 				mac_rx_drop_pkt(mac_srs, mp);
2115 				continue;
2116 			}
2117 
2118 			FANOUT_ENQUEUE_MP(headmp[type][indx],
2119 			    tailmp[type][indx], cnt[type][indx], bw_ctl,
2120 			    sz[type][indx], sz1, mp);
2121 			continue;
2122 		}
2123 
2124 		ASSERT(type == UNDEF);
2125 
2126 		/*
2127 		 * XXX-Sunay: We should hold srs_lock since ring_count
2128 		 * below can change. But if we are always called from
2129 		 * mac_rx_srs_drain and SRS_PROC is set, then we can
2130 		 * enforce that ring_count can't be changed i.e.
2131 		 * to change fanout type or ring count, the calling
2132 		 * thread needs to be behind SRS_PROC.
2133 		 */
2134 		switch (ipha->ipha_protocol) {
2135 		case IPPROTO_TCP:
2136 			/*
2137 			 * Note that for ESP, we fanout on SPI and it is at the
2138 			 * same offset as the 2x16-bit ports. So it is clumped
2139 			 * along with TCP, UDP and SCTP.
2140 			 */
2141 			hash = HASH_ADDR(ipha->ipha_src, ipha->ipha_dst,
2142 			    *(uint32_t *)(mp->b_rptr + ports_offset));
2143 			indx = COMPUTE_INDEX(hash, mac_srs->srs_tcp_ring_count);
2144 			type = V4_TCP;
2145 			mp->b_rptr += hdrsize;
2146 			break;
2147 		case IPPROTO_UDP:
2148 		case IPPROTO_SCTP:
2149 		case IPPROTO_ESP:
2150 			if (mac_fanout_type == MAC_FANOUT_DEFAULT) {
2151 				hash = HASH_ADDR(ipha->ipha_src, ipha->ipha_dst,
2152 				    *(uint32_t *)(mp->b_rptr + ports_offset));
2153 				indx = COMPUTE_INDEX(hash,
2154 				    mac_srs->srs_udp_ring_count);
2155 			} else {
2156 				indx = mac_srs->srs_ind %
2157 				    mac_srs->srs_udp_ring_count;
2158 				mac_srs->srs_ind++;
2159 			}
2160 			type = V4_UDP;
2161 			mp->b_rptr += hdrsize;
2162 			break;
2163 		default:
2164 			indx = 0;
2165 			type = OTH;
2166 		}
2167 
2168 		FANOUT_ENQUEUE_MP(headmp[type][indx], tailmp[type][indx],
2169 		    cnt[type][indx], bw_ctl, sz[type][indx], sz1, mp);
2170 	}
2171 
2172 	for (type = V4_TCP; type < UNDEF; type++) {
2173 		int	i;
2174 
2175 		for (i = 0; i < fanout_cnt; i++) {
2176 			if (headmp[type][i] != NULL) {
2177 				mac_soft_ring_t	*softring;
2178 
2179 				ASSERT(tailmp[type][i]->b_next == NULL);
2180 				switch (type) {
2181 				case V4_TCP:
2182 					softring =
2183 					    mac_srs->srs_tcp_soft_rings[i];
2184 					break;
2185 				case V4_UDP:
2186 					softring =
2187 					    mac_srs->srs_udp_soft_rings[i];
2188 					break;
2189 				case OTH:
2190 					softring =
2191 					    mac_srs->srs_oth_soft_rings[i];
2192 					break;
2193 				}
2194 				mac_rx_soft_ring_process(mcip,
2195 				    softring, headmp[type][i], tailmp[type][i],
2196 				    cnt[type][i], sz[type][i]);
2197 			}
2198 		}
2199 	}
2200 }
2201 
2202 #define	SRS_BYTES_TO_PICKUP	150000
2203 ssize_t	max_bytes_to_pickup = SRS_BYTES_TO_PICKUP;
2204 
2205 /*
2206  * mac_rx_srs_poll_ring
2207  *
2208  * This SRS Poll thread uses this routine to poll the underlying hardware
2209  * Rx ring to get a chain of packets. It can inline process that chain
2210  * if mac_latency_optimize is set (default) or signal the SRS worker thread
2211  * to do the remaining processing.
2212  *
2213  * Since packets come in the system via interrupt or poll path, we also
2214  * update the stats and deal with promiscous clients here.
2215  */
2216 void
2217 mac_rx_srs_poll_ring(mac_soft_ring_set_t *mac_srs)
2218 {
2219 	kmutex_t		*lock = &mac_srs->srs_lock;
2220 	kcondvar_t		*async = &mac_srs->srs_cv;
2221 	mac_srs_rx_t		*srs_rx = &mac_srs->srs_rx;
2222 	mblk_t			*head, *tail, *mp;
2223 	callb_cpr_t		cprinfo;
2224 	ssize_t			bytes_to_pickup;
2225 	size_t			sz;
2226 	int			count;
2227 	mac_client_impl_t	*smcip;
2228 
2229 	CALLB_CPR_INIT(&cprinfo, lock, callb_generic_cpr, "mac_srs_poll");
2230 	mutex_enter(lock);
2231 
2232 start:
2233 	for (;;) {
2234 		if (mac_srs->srs_state & SRS_PAUSE)
2235 			goto done;
2236 
2237 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
2238 		cv_wait(async, lock);
2239 		CALLB_CPR_SAFE_END(&cprinfo, lock);
2240 
2241 		if (mac_srs->srs_state & SRS_PAUSE)
2242 			goto done;
2243 
2244 check_again:
2245 		if (mac_srs->srs_type & SRST_BW_CONTROL) {
2246 			/*
2247 			 * We pick as many bytes as we are allowed to queue.
2248 			 * Its possible that we will exceed the total
2249 			 * packets queued in case this SRS is part of the
2250 			 * Rx ring group since > 1 poll thread can be pulling
2251 			 * upto the max allowed packets at the same time
2252 			 * but that should be OK.
2253 			 */
2254 			mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2255 			bytes_to_pickup =
2256 			    mac_srs->srs_bw->mac_bw_drop_threshold -
2257 			    mac_srs->srs_bw->mac_bw_sz;
2258 			/*
2259 			 * We shouldn't have been signalled if we
2260 			 * have 0 or less bytes to pick but since
2261 			 * some of the bytes accounting is driver
2262 			 * dependant, we do the safety check.
2263 			 */
2264 			if (bytes_to_pickup < 0)
2265 				bytes_to_pickup = 0;
2266 			mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2267 		} else {
2268 			/*
2269 			 * ToDO: Need to change the polling API
2270 			 * to add a packet count and a flag which
2271 			 * tells the driver whether we want packets
2272 			 * based on a count, or bytes, or all the
2273 			 * packets queued in the driver/HW. This
2274 			 * way, we never have to check the limits
2275 			 * on poll path. We truly let only as many
2276 			 * packets enter the system as we are willing
2277 			 * to process or queue.
2278 			 *
2279 			 * Something along the lines of
2280 			 * pkts_to_pickup = mac_soft_ring_max_q_cnt -
2281 			 *	mac_srs->srs_poll_pkt_cnt
2282 			 */
2283 
2284 			/*
2285 			 * Since we are not doing B/W control, pick
2286 			 * as many packets as allowed.
2287 			 */
2288 			bytes_to_pickup = max_bytes_to_pickup;
2289 		}
2290 
2291 		/* Poll the underlying Hardware */
2292 		mutex_exit(lock);
2293 		head = MAC_HWRING_POLL(mac_srs->srs_ring, (int)bytes_to_pickup);
2294 		mutex_enter(lock);
2295 
2296 		ASSERT((mac_srs->srs_state & SRS_POLL_THR_OWNER) ==
2297 		    SRS_POLL_THR_OWNER);
2298 
2299 		mp = tail = head;
2300 		count = 0;
2301 		sz = 0;
2302 		while (mp != NULL) {
2303 			tail = mp;
2304 			sz += msgdsize(mp);
2305 			mp = mp->b_next;
2306 			count++;
2307 		}
2308 
2309 		if (head != NULL) {
2310 			tail->b_next = NULL;
2311 			smcip = mac_srs->srs_mcip;
2312 
2313 			SRS_RX_STAT_UPDATE(mac_srs, pollbytes, sz);
2314 			SRS_RX_STAT_UPDATE(mac_srs, pollcnt, count);
2315 
2316 			/*
2317 			 * If there are any promiscuous mode callbacks
2318 			 * defined for this MAC client, pass them a copy
2319 			 * if appropriate and also update the counters.
2320 			 */
2321 			if (smcip != NULL) {
2322 				if (smcip->mci_mip->mi_promisc_list != NULL) {
2323 					mutex_exit(lock);
2324 					mac_promisc_dispatch(smcip->mci_mip,
2325 					    head, NULL, B_FALSE);
2326 					mutex_enter(lock);
2327 				}
2328 			}
2329 			if (mac_srs->srs_type & SRST_BW_CONTROL) {
2330 				mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2331 				mac_srs->srs_bw->mac_bw_polled += sz;
2332 				mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2333 			}
2334 			MAC_RX_SRS_ENQUEUE_CHAIN(mac_srs, head, tail,
2335 			    count, sz);
2336 			if (count <= 10)
2337 				srs_rx->sr_stat.mrs_chaincntundr10++;
2338 			else if (count > 10 && count <= 50)
2339 				srs_rx->sr_stat.mrs_chaincnt10to50++;
2340 			else
2341 				srs_rx->sr_stat.mrs_chaincntover50++;
2342 		}
2343 
2344 		/*
2345 		 * We are guaranteed that SRS_PROC will be set if we
2346 		 * are here. Also, poll thread gets to run only if
2347 		 * the drain was being done by a worker thread although
2348 		 * its possible that worker thread is still running
2349 		 * and poll thread was sent down to keep the pipeline
2350 		 * going instead of doing a complete drain and then
2351 		 * trying to poll the NIC.
2352 		 *
2353 		 * So we need to check SRS_WORKER flag to make sure
2354 		 * that the worker thread is not processing the queue
2355 		 * in parallel to us. The flags and conditions are
2356 		 * protected by the srs_lock to prevent any race. We
2357 		 * ensure that we don't drop the srs_lock from now
2358 		 * till the end and similarly we don't drop the srs_lock
2359 		 * in mac_rx_srs_drain() till similar condition check
2360 		 * are complete. The mac_rx_srs_drain() needs to ensure
2361 		 * that SRS_WORKER flag remains set as long as its
2362 		 * processing the queue.
2363 		 */
2364 		if (!(mac_srs->srs_state & SRS_WORKER) &&
2365 		    (mac_srs->srs_first != NULL)) {
2366 			/*
2367 			 * We have packets to process and worker thread
2368 			 * is not running. Check to see if poll thread is
2369 			 * allowed to process.
2370 			 */
2371 			if (mac_srs->srs_state & SRS_LATENCY_OPT) {
2372 				mac_srs->srs_drain_func(mac_srs, SRS_POLL_PROC);
2373 				if (!(mac_srs->srs_state & SRS_PAUSE) &&
2374 				    srs_rx->sr_poll_pkt_cnt <=
2375 				    srs_rx->sr_lowat) {
2376 					srs_rx->sr_poll_again++;
2377 					goto check_again;
2378 				}
2379 				/*
2380 				 * We are already above low water mark
2381 				 * so stay in the polling mode but no
2382 				 * need to poll. Once we dip below
2383 				 * the polling threshold, the processing
2384 				 * thread (soft ring) will signal us
2385 				 * to poll again (MAC_UPDATE_SRS_COUNT)
2386 				 */
2387 				srs_rx->sr_poll_drain_no_poll++;
2388 				mac_srs->srs_state &= ~(SRS_PROC|SRS_GET_PKTS);
2389 				/*
2390 				 * In B/W control case, its possible
2391 				 * that the backlog built up due to
2392 				 * B/W limit being reached and packets
2393 				 * are queued only in SRS. In this case,
2394 				 * we should schedule worker thread
2395 				 * since no one else will wake us up.
2396 				 */
2397 				if ((mac_srs->srs_type & SRST_BW_CONTROL) &&
2398 				    (mac_srs->srs_tid == NULL)) {
2399 					mac_srs->srs_tid =
2400 					    timeout(mac_srs_fire, mac_srs, 1);
2401 					srs_rx->sr_poll_worker_wakeup++;
2402 				}
2403 			} else {
2404 				/*
2405 				 * Wakeup the worker thread for more processing.
2406 				 * We optimize for throughput in this case.
2407 				 */
2408 				mac_srs->srs_state &= ~(SRS_PROC|SRS_GET_PKTS);
2409 				MAC_SRS_WORKER_WAKEUP(mac_srs);
2410 				srs_rx->sr_poll_sig_worker++;
2411 			}
2412 		} else if ((mac_srs->srs_first == NULL) &&
2413 		    !(mac_srs->srs_state & SRS_WORKER)) {
2414 			/*
2415 			 * There is nothing queued in SRS and
2416 			 * no worker thread running. Plus we
2417 			 * didn't get anything from the H/W
2418 			 * as well (head == NULL);
2419 			 */
2420 			ASSERT(head == NULL);
2421 			mac_srs->srs_state &=
2422 			    ~(SRS_PROC|SRS_GET_PKTS);
2423 
2424 			/*
2425 			 * If we have a packets in soft ring, don't allow
2426 			 * more packets to come into this SRS by keeping the
2427 			 * interrupts off but not polling the H/W. The
2428 			 * poll thread will get signaled as soon as
2429 			 * srs_poll_pkt_cnt dips below poll threshold.
2430 			 */
2431 			if (srs_rx->sr_poll_pkt_cnt == 0) {
2432 				srs_rx->sr_poll_intr_enable++;
2433 				MAC_SRS_POLLING_OFF(mac_srs);
2434 			} else {
2435 				/*
2436 				 * We know nothing is queued in SRS
2437 				 * since we are here after checking
2438 				 * srs_first is NULL. The backlog
2439 				 * is entirely due to packets queued
2440 				 * in Soft ring which will wake us up
2441 				 * and get the interface out of polling
2442 				 * mode once the backlog dips below
2443 				 * sr_poll_thres.
2444 				 */
2445 				srs_rx->sr_poll_no_poll++;
2446 			}
2447 		} else {
2448 			/*
2449 			 * Worker thread is already running.
2450 			 * Nothing much to do. If the polling
2451 			 * was enabled, worker thread will deal
2452 			 * with that.
2453 			 */
2454 			mac_srs->srs_state &= ~SRS_GET_PKTS;
2455 			srs_rx->sr_poll_goto_sleep++;
2456 		}
2457 	}
2458 done:
2459 	mac_srs->srs_state |= SRS_POLL_THR_QUIESCED;
2460 	cv_signal(&mac_srs->srs_async);
2461 	/*
2462 	 * If this is a temporary quiesce then wait for the restart signal
2463 	 * from the srs worker. Then clear the flags and signal the srs worker
2464 	 * to ensure a positive handshake and go back to start.
2465 	 */
2466 	while (!(mac_srs->srs_state & (SRS_CONDEMNED | SRS_POLL_THR_RESTART)))
2467 		cv_wait(async, lock);
2468 	if (mac_srs->srs_state & SRS_POLL_THR_RESTART) {
2469 		ASSERT(!(mac_srs->srs_state & SRS_CONDEMNED));
2470 		mac_srs->srs_state &=
2471 		    ~(SRS_POLL_THR_QUIESCED | SRS_POLL_THR_RESTART);
2472 		cv_signal(&mac_srs->srs_async);
2473 		goto start;
2474 	} else {
2475 		mac_srs->srs_state |= SRS_POLL_THR_EXITED;
2476 		cv_signal(&mac_srs->srs_async);
2477 		CALLB_CPR_EXIT(&cprinfo);
2478 		thread_exit();
2479 	}
2480 }
2481 
2482 /*
2483  * mac_srs_pick_chain
2484  *
2485  * In Bandwidth control case, checks how many packets can be processed
2486  * and return them in a sub chain.
2487  */
2488 static mblk_t *
2489 mac_srs_pick_chain(mac_soft_ring_set_t *mac_srs, mblk_t **chain_tail,
2490     size_t *chain_sz, int *chain_cnt)
2491 {
2492 	mblk_t			*head = NULL;
2493 	mblk_t			*tail = NULL;
2494 	size_t			sz;
2495 	size_t			tsz = 0;
2496 	int			cnt = 0;
2497 	mblk_t			*mp;
2498 
2499 	ASSERT(MUTEX_HELD(&mac_srs->srs_lock));
2500 	mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2501 	if (((mac_srs->srs_bw->mac_bw_used + mac_srs->srs_size) <=
2502 	    mac_srs->srs_bw->mac_bw_limit) ||
2503 	    (mac_srs->srs_bw->mac_bw_limit == 0)) {
2504 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2505 		head = mac_srs->srs_first;
2506 		mac_srs->srs_first = NULL;
2507 		*chain_tail = mac_srs->srs_last;
2508 		mac_srs->srs_last = NULL;
2509 		*chain_sz = mac_srs->srs_size;
2510 		*chain_cnt = mac_srs->srs_count;
2511 		mac_srs->srs_count = 0;
2512 		mac_srs->srs_size = 0;
2513 		return (head);
2514 	}
2515 
2516 	/*
2517 	 * Can't clear the entire backlog.
2518 	 * Need to find how many packets to pick
2519 	 */
2520 	ASSERT(MUTEX_HELD(&mac_srs->srs_bw->mac_bw_lock));
2521 	while ((mp = mac_srs->srs_first) != NULL) {
2522 		sz = msgdsize(mp);
2523 		if ((tsz + sz + mac_srs->srs_bw->mac_bw_used) >
2524 		    mac_srs->srs_bw->mac_bw_limit) {
2525 			if (!(mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED))
2526 				mac_srs->srs_bw->mac_bw_state |=
2527 				    SRS_BW_ENFORCED;
2528 			break;
2529 		}
2530 
2531 		/*
2532 		 * The _size & cnt is  decremented from the softrings
2533 		 * when they send up the packet for polling to work
2534 		 * properly.
2535 		 */
2536 		tsz += sz;
2537 		cnt++;
2538 		mac_srs->srs_count--;
2539 		mac_srs->srs_size -= sz;
2540 		if (tail != NULL)
2541 			tail->b_next = mp;
2542 		else
2543 			head = mp;
2544 		tail = mp;
2545 		mac_srs->srs_first = mac_srs->srs_first->b_next;
2546 	}
2547 	mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2548 	if (mac_srs->srs_first == NULL)
2549 		mac_srs->srs_last = NULL;
2550 
2551 	if (tail != NULL)
2552 		tail->b_next = NULL;
2553 	*chain_tail = tail;
2554 	*chain_cnt = cnt;
2555 	*chain_sz = tsz;
2556 
2557 	return (head);
2558 }
2559 
2560 /*
2561  * mac_rx_srs_drain
2562  *
2563  * The SRS drain routine. Gets to run to clear the queue. Any thread
2564  * (worker, interrupt, poll) can call this based on processing model.
2565  * The first thing we do is disable interrupts if possible and then
2566  * drain the queue. we also try to poll the underlying hardware if
2567  * there is a dedicated hardware Rx ring assigned to this SRS.
2568  *
2569  * There is a equivalent drain routine in bandwidth control mode
2570  * mac_rx_srs_drain_bw. There is some code duplication between the two
2571  * routines but they are highly performance sensitive and are easier
2572  * to read/debug if they stay separate. Any code changes here might
2573  * also apply to mac_rx_srs_drain_bw as well.
2574  */
2575 void
2576 mac_rx_srs_drain(mac_soft_ring_set_t *mac_srs, uint_t proc_type)
2577 {
2578 	mblk_t			*head;
2579 	mblk_t			*tail;
2580 	timeout_id_t		tid;
2581 	int			cnt = 0;
2582 	mac_client_impl_t	*mcip = mac_srs->srs_mcip;
2583 	mac_srs_rx_t		*srs_rx = &mac_srs->srs_rx;
2584 
2585 	ASSERT(MUTEX_HELD(&mac_srs->srs_lock));
2586 	ASSERT(!(mac_srs->srs_type & SRST_BW_CONTROL));
2587 
2588 	/* If we are blanked i.e. can't do upcalls, then we are done */
2589 	if (mac_srs->srs_state & (SRS_BLANK | SRS_PAUSE)) {
2590 		ASSERT((mac_srs->srs_type & SRST_NO_SOFT_RINGS) ||
2591 		    (mac_srs->srs_state & SRS_PAUSE));
2592 		goto out;
2593 	}
2594 
2595 	if (mac_srs->srs_first == NULL)
2596 		goto out;
2597 
2598 	if (!(mac_srs->srs_state & SRS_LATENCY_OPT) &&
2599 	    (srs_rx->sr_poll_pkt_cnt <= srs_rx->sr_lowat)) {
2600 		/*
2601 		 * In the normal case, the SRS worker thread does no
2602 		 * work and we wait for a backlog to build up before
2603 		 * we switch into polling mode. In case we are
2604 		 * optimizing for throughput, we use the worker thread
2605 		 * as well. The goal is to let worker thread process
2606 		 * the queue and poll thread to feed packets into
2607 		 * the queue. As such, we should signal the poll
2608 		 * thread to try and get more packets.
2609 		 *
2610 		 * We could have pulled this check in the POLL_RING
2611 		 * macro itself but keeping it explicit here makes
2612 		 * the architecture more human understandable.
2613 		 */
2614 		MAC_SRS_POLL_RING(mac_srs);
2615 	}
2616 
2617 again:
2618 	head = mac_srs->srs_first;
2619 	mac_srs->srs_first = NULL;
2620 	tail = mac_srs->srs_last;
2621 	mac_srs->srs_last = NULL;
2622 	cnt = mac_srs->srs_count;
2623 	mac_srs->srs_count = 0;
2624 
2625 	ASSERT(head != NULL);
2626 	ASSERT(tail != NULL);
2627 
2628 	if ((tid = mac_srs->srs_tid) != NULL)
2629 		mac_srs->srs_tid = NULL;
2630 
2631 	mac_srs->srs_state |= (SRS_PROC|proc_type);
2632 
2633 	/*
2634 	 * mcip is NULL for broadcast and multicast flows. The promisc
2635 	 * callbacks for broadcast and multicast packets are delivered from
2636 	 * mac_rx() and we don't need to worry about that case in this path
2637 	 */
2638 	if (mcip != NULL) {
2639 		if (mcip->mci_promisc_list != NULL) {
2640 			mutex_exit(&mac_srs->srs_lock);
2641 			mac_promisc_client_dispatch(mcip, head);
2642 			mutex_enter(&mac_srs->srs_lock);
2643 		}
2644 		if (MAC_PROTECT_ENABLED(mcip, MPT_IPNOSPOOF)) {
2645 			mutex_exit(&mac_srs->srs_lock);
2646 			mac_protect_intercept_dynamic(mcip, head);
2647 			mutex_enter(&mac_srs->srs_lock);
2648 		}
2649 	}
2650 
2651 	/*
2652 	 * Check if SRS itself is doing the processing. This direct
2653 	 * path applies only when subflows are present.
2654 	 */
2655 	if (mac_srs->srs_type & SRST_NO_SOFT_RINGS) {
2656 		mac_direct_rx_t		proc;
2657 		void			*arg1;
2658 		mac_resource_handle_t	arg2;
2659 
2660 		/*
2661 		 * This is the case when a Rx is directly
2662 		 * assigned and we have a fully classified
2663 		 * protocol chain. We can deal with it in
2664 		 * one shot.
2665 		 */
2666 		proc = srs_rx->sr_func;
2667 		arg1 = srs_rx->sr_arg1;
2668 		arg2 = srs_rx->sr_arg2;
2669 
2670 		mac_srs->srs_state |= SRS_CLIENT_PROC;
2671 		mutex_exit(&mac_srs->srs_lock);
2672 		if (tid != NULL) {
2673 			(void) untimeout(tid);
2674 			tid = NULL;
2675 		}
2676 
2677 		proc(arg1, arg2, head, NULL);
2678 		/*
2679 		 * Decrement the size and count here itelf
2680 		 * since the packet has been processed.
2681 		 */
2682 		mutex_enter(&mac_srs->srs_lock);
2683 		MAC_UPDATE_SRS_COUNT_LOCKED(mac_srs, cnt);
2684 		if (mac_srs->srs_state & SRS_CLIENT_WAIT)
2685 			cv_signal(&mac_srs->srs_client_cv);
2686 		mac_srs->srs_state &= ~SRS_CLIENT_PROC;
2687 	} else {
2688 		/* Some kind of softrings based fanout is required */
2689 		mutex_exit(&mac_srs->srs_lock);
2690 		if (tid != NULL) {
2691 			(void) untimeout(tid);
2692 			tid = NULL;
2693 		}
2694 
2695 		/*
2696 		 * Since the fanout routines can deal with chains,
2697 		 * shoot the entire chain up.
2698 		 */
2699 		if (mac_srs->srs_type & SRST_FANOUT_SRC_IP)
2700 			mac_rx_srs_fanout(mac_srs, head);
2701 		else
2702 			mac_rx_srs_proto_fanout(mac_srs, head);
2703 		mutex_enter(&mac_srs->srs_lock);
2704 	}
2705 
2706 	if (!(mac_srs->srs_state & (SRS_BLANK|SRS_PAUSE)) &&
2707 	    (mac_srs->srs_first != NULL)) {
2708 		/*
2709 		 * More packets arrived while we were clearing the
2710 		 * SRS. This can be possible because of one of
2711 		 * three conditions below:
2712 		 * 1) The driver is using multiple worker threads
2713 		 *    to send the packets to us.
2714 		 * 2) The driver has a race in switching
2715 		 *    between interrupt and polling mode or
2716 		 * 3) Packets are arriving in this SRS via the
2717 		 *    S/W classification as well.
2718 		 *
2719 		 * We should switch to polling mode and see if we
2720 		 * need to send the poll thread down. Also, signal
2721 		 * the worker thread to process whats just arrived.
2722 		 */
2723 		MAC_SRS_POLLING_ON(mac_srs);
2724 		if (srs_rx->sr_poll_pkt_cnt <= srs_rx->sr_lowat) {
2725 			srs_rx->sr_drain_poll_sig++;
2726 			MAC_SRS_POLL_RING(mac_srs);
2727 		}
2728 
2729 		/*
2730 		 * If we didn't signal the poll thread, we need
2731 		 * to deal with the pending packets ourselves.
2732 		 */
2733 		if (proc_type == SRS_WORKER) {
2734 			srs_rx->sr_drain_again++;
2735 			goto again;
2736 		} else {
2737 			srs_rx->sr_drain_worker_sig++;
2738 			cv_signal(&mac_srs->srs_async);
2739 		}
2740 	}
2741 
2742 out:
2743 	if (mac_srs->srs_state & SRS_GET_PKTS) {
2744 		/*
2745 		 * Poll thread is already running. Leave the
2746 		 * SRS_RPOC set and hand over the control to
2747 		 * poll thread.
2748 		 */
2749 		mac_srs->srs_state &= ~proc_type;
2750 		srs_rx->sr_drain_poll_running++;
2751 		return;
2752 	}
2753 
2754 	/*
2755 	 * Even if there are no packets queued in SRS, we
2756 	 * need to make sure that the shared counter is
2757 	 * clear and any associated softrings have cleared
2758 	 * all the backlog. Otherwise, leave the interface
2759 	 * in polling mode and the poll thread will get
2760 	 * signalled once the count goes down to zero.
2761 	 *
2762 	 * If someone is already draining the queue (SRS_PROC is
2763 	 * set) when the srs_poll_pkt_cnt goes down to zero,
2764 	 * then it means that drain is already running and we
2765 	 * will turn off polling at that time if there is
2766 	 * no backlog.
2767 	 *
2768 	 * As long as there are packets queued either
2769 	 * in soft ring set or its soft rings, we will leave
2770 	 * the interface in polling mode (even if the drain
2771 	 * was done being the interrupt thread). We signal
2772 	 * the poll thread as well if we have dipped below
2773 	 * low water mark.
2774 	 *
2775 	 * NOTE: We can't use the MAC_SRS_POLLING_ON macro
2776 	 * since that turn polling on only for worker thread.
2777 	 * Its not worth turning polling on for interrupt
2778 	 * thread (since NIC will not issue another interrupt)
2779 	 * unless a backlog builds up.
2780 	 */
2781 	if ((srs_rx->sr_poll_pkt_cnt > 0) &&
2782 	    (mac_srs->srs_state & SRS_POLLING_CAPAB)) {
2783 		mac_srs->srs_state &= ~(SRS_PROC|proc_type);
2784 		srs_rx->sr_drain_keep_polling++;
2785 		MAC_SRS_POLLING_ON(mac_srs);
2786 		if (srs_rx->sr_poll_pkt_cnt <= srs_rx->sr_lowat)
2787 			MAC_SRS_POLL_RING(mac_srs);
2788 		return;
2789 	}
2790 
2791 	/* Nothing else to do. Get out of poll mode */
2792 	MAC_SRS_POLLING_OFF(mac_srs);
2793 	mac_srs->srs_state &= ~(SRS_PROC|proc_type);
2794 	srs_rx->sr_drain_finish_intr++;
2795 }
2796 
2797 /*
2798  * mac_rx_srs_drain_bw
2799  *
2800  * The SRS BW drain routine. Gets to run to clear the queue. Any thread
2801  * (worker, interrupt, poll) can call this based on processing model.
2802  * The first thing we do is disable interrupts if possible and then
2803  * drain the queue. we also try to poll the underlying hardware if
2804  * there is a dedicated hardware Rx ring assigned to this SRS.
2805  *
2806  * There is a equivalent drain routine in non bandwidth control mode
2807  * mac_rx_srs_drain. There is some code duplication between the two
2808  * routines but they are highly performance sensitive and are easier
2809  * to read/debug if they stay separate. Any code changes here might
2810  * also apply to mac_rx_srs_drain as well.
2811  */
2812 void
2813 mac_rx_srs_drain_bw(mac_soft_ring_set_t *mac_srs, uint_t proc_type)
2814 {
2815 	mblk_t			*head;
2816 	mblk_t			*tail;
2817 	timeout_id_t		tid;
2818 	size_t			sz = 0;
2819 	int			cnt = 0;
2820 	mac_client_impl_t	*mcip = mac_srs->srs_mcip;
2821 	mac_srs_rx_t		*srs_rx = &mac_srs->srs_rx;
2822 	clock_t			now;
2823 
2824 	ASSERT(MUTEX_HELD(&mac_srs->srs_lock));
2825 	ASSERT(mac_srs->srs_type & SRST_BW_CONTROL);
2826 again:
2827 	/* Check if we are doing B/W control */
2828 	mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2829 	now = ddi_get_lbolt();
2830 	if (mac_srs->srs_bw->mac_bw_curr_time != now) {
2831 		mac_srs->srs_bw->mac_bw_curr_time = now;
2832 		mac_srs->srs_bw->mac_bw_used = 0;
2833 		if (mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED)
2834 			mac_srs->srs_bw->mac_bw_state &= ~SRS_BW_ENFORCED;
2835 	} else if (mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED) {
2836 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2837 		goto done;
2838 	} else if (mac_srs->srs_bw->mac_bw_used >
2839 	    mac_srs->srs_bw->mac_bw_limit) {
2840 		mac_srs->srs_bw->mac_bw_state |= SRS_BW_ENFORCED;
2841 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2842 		goto done;
2843 	}
2844 	mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2845 
2846 	/* If we are blanked i.e. can't do upcalls, then we are done */
2847 	if (mac_srs->srs_state & (SRS_BLANK | SRS_PAUSE)) {
2848 		ASSERT((mac_srs->srs_type & SRST_NO_SOFT_RINGS) ||
2849 		    (mac_srs->srs_state & SRS_PAUSE));
2850 		goto done;
2851 	}
2852 
2853 	sz = 0;
2854 	cnt = 0;
2855 	if ((head = mac_srs_pick_chain(mac_srs, &tail, &sz, &cnt)) == NULL) {
2856 		/*
2857 		 * We couldn't pick up a single packet.
2858 		 */
2859 		mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2860 		if ((mac_srs->srs_bw->mac_bw_used == 0) &&
2861 		    (mac_srs->srs_size != 0) &&
2862 		    !(mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED)) {
2863 			/*
2864 			 * Seems like configured B/W doesn't
2865 			 * even allow processing of 1 packet
2866 			 * per tick.
2867 			 *
2868 			 * XXX: raise the limit to processing
2869 			 * at least 1 packet per tick.
2870 			 */
2871 			mac_srs->srs_bw->mac_bw_limit +=
2872 			    mac_srs->srs_bw->mac_bw_limit;
2873 			mac_srs->srs_bw->mac_bw_drop_threshold +=
2874 			    mac_srs->srs_bw->mac_bw_drop_threshold;
2875 			cmn_err(CE_NOTE, "mac_rx_srs_drain: srs(%p) "
2876 			    "raised B/W limit to %d since not even a "
2877 			    "single packet can be processed per "
2878 			    "tick %d\n", (void *)mac_srs,
2879 			    (int)mac_srs->srs_bw->mac_bw_limit,
2880 			    (int)msgdsize(mac_srs->srs_first));
2881 		}
2882 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2883 		goto done;
2884 	}
2885 
2886 	ASSERT(head != NULL);
2887 	ASSERT(tail != NULL);
2888 
2889 	/* zero bandwidth: drop all and return to interrupt mode */
2890 	mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
2891 	if (mac_srs->srs_bw->mac_bw_limit == 0) {
2892 		srs_rx->sr_stat.mrs_sdrops += cnt;
2893 		ASSERT(mac_srs->srs_bw->mac_bw_sz >= sz);
2894 		mac_srs->srs_bw->mac_bw_sz -= sz;
2895 		mac_srs->srs_bw->mac_bw_drop_bytes += sz;
2896 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2897 		mac_drop_chain(head, "Rx no bandwidth");
2898 		goto leave_poll;
2899 	} else {
2900 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
2901 	}
2902 
2903 	if ((tid = mac_srs->srs_tid) != NULL)
2904 		mac_srs->srs_tid = NULL;
2905 
2906 	mac_srs->srs_state |= (SRS_PROC|proc_type);
2907 	MAC_SRS_WORKER_POLLING_ON(mac_srs);
2908 
2909 	/*
2910 	 * mcip is NULL for broadcast and multicast flows. The promisc
2911 	 * callbacks for broadcast and multicast packets are delivered from
2912 	 * mac_rx() and we don't need to worry about that case in this path
2913 	 */
2914 	if (mcip != NULL) {
2915 		if (mcip->mci_promisc_list != NULL) {
2916 			mutex_exit(&mac_srs->srs_lock);
2917 			mac_promisc_client_dispatch(mcip, head);
2918 			mutex_enter(&mac_srs->srs_lock);
2919 		}
2920 		if (MAC_PROTECT_ENABLED(mcip, MPT_IPNOSPOOF)) {
2921 			mutex_exit(&mac_srs->srs_lock);
2922 			mac_protect_intercept_dynamic(mcip, head);
2923 			mutex_enter(&mac_srs->srs_lock);
2924 		}
2925 	}
2926 
2927 	/*
2928 	 * Check if SRS itself is doing the processing
2929 	 * This direct path does not apply when subflows are present. In this
2930 	 * case, packets need to be dispatched to a soft ring according to the
2931 	 * flow's bandwidth and other resources contraints.
2932 	 */
2933 	if (mac_srs->srs_type & SRST_NO_SOFT_RINGS) {
2934 		mac_direct_rx_t		proc;
2935 		void			*arg1;
2936 		mac_resource_handle_t	arg2;
2937 
2938 		/*
2939 		 * This is the case when a Rx is directly
2940 		 * assigned and we have a fully classified
2941 		 * protocol chain. We can deal with it in
2942 		 * one shot.
2943 		 */
2944 		proc = srs_rx->sr_func;
2945 		arg1 = srs_rx->sr_arg1;
2946 		arg2 = srs_rx->sr_arg2;
2947 
2948 		mac_srs->srs_state |= SRS_CLIENT_PROC;
2949 		mutex_exit(&mac_srs->srs_lock);
2950 		if (tid != NULL) {
2951 			(void) untimeout(tid);
2952 			tid = NULL;
2953 		}
2954 
2955 		proc(arg1, arg2, head, NULL);
2956 		/*
2957 		 * Decrement the size and count here itelf
2958 		 * since the packet has been processed.
2959 		 */
2960 		mutex_enter(&mac_srs->srs_lock);
2961 		MAC_UPDATE_SRS_COUNT_LOCKED(mac_srs, cnt);
2962 		MAC_UPDATE_SRS_SIZE_LOCKED(mac_srs, sz);
2963 
2964 		if (mac_srs->srs_state & SRS_CLIENT_WAIT)
2965 			cv_signal(&mac_srs->srs_client_cv);
2966 		mac_srs->srs_state &= ~SRS_CLIENT_PROC;
2967 	} else {
2968 		/* Some kind of softrings based fanout is required */
2969 		mutex_exit(&mac_srs->srs_lock);
2970 		if (tid != NULL) {
2971 			(void) untimeout(tid);
2972 			tid = NULL;
2973 		}
2974 
2975 		/*
2976 		 * Since the fanout routines can deal with chains,
2977 		 * shoot the entire chain up.
2978 		 */
2979 		if (mac_srs->srs_type & SRST_FANOUT_SRC_IP)
2980 			mac_rx_srs_fanout(mac_srs, head);
2981 		else
2982 			mac_rx_srs_proto_fanout(mac_srs, head);
2983 		mutex_enter(&mac_srs->srs_lock);
2984 	}
2985 
2986 	/*
2987 	 * Send the poll thread to pick up any packets arrived
2988 	 * so far. This also serves as the last check in case
2989 	 * nothing else is queued in the SRS. The poll thread
2990 	 * is signalled only in the case the drain was done
2991 	 * by the worker thread and SRS_WORKER is set. The
2992 	 * worker thread can run in parallel as long as the
2993 	 * SRS_WORKER flag is set. We we have nothing else to
2994 	 * process, we can exit while leaving SRS_PROC set
2995 	 * which gives the poll thread control to process and
2996 	 * cleanup once it returns from the NIC.
2997 	 *
2998 	 * If we have nothing else to process, we need to
2999 	 * ensure that we keep holding the srs_lock till
3000 	 * all the checks below are done and control is
3001 	 * handed to the poll thread if it was running.
3002 	 */
3003 	mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
3004 	if (!(mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED)) {
3005 		if (mac_srs->srs_first != NULL) {
3006 			if (proc_type == SRS_WORKER) {
3007 				mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
3008 				if (srs_rx->sr_poll_pkt_cnt <=
3009 				    srs_rx->sr_lowat)
3010 					MAC_SRS_POLL_RING(mac_srs);
3011 				goto again;
3012 			} else {
3013 				cv_signal(&mac_srs->srs_async);
3014 			}
3015 		}
3016 	}
3017 	mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
3018 
3019 done:
3020 
3021 	if (mac_srs->srs_state & SRS_GET_PKTS) {
3022 		/*
3023 		 * Poll thread is already running. Leave the
3024 		 * SRS_RPOC set and hand over the control to
3025 		 * poll thread.
3026 		 */
3027 		mac_srs->srs_state &= ~proc_type;
3028 		return;
3029 	}
3030 
3031 	/*
3032 	 * If we can't process packets because we have exceeded
3033 	 * B/W limit for this tick, just set the timeout
3034 	 * and leave.
3035 	 *
3036 	 * Even if there are no packets queued in SRS, we
3037 	 * need to make sure that the shared counter is
3038 	 * clear and any associated softrings have cleared
3039 	 * all the backlog. Otherwise, leave the interface
3040 	 * in polling mode and the poll thread will get
3041 	 * signalled once the count goes down to zero.
3042 	 *
3043 	 * If someone is already draining the queue (SRS_PROC is
3044 	 * set) when the srs_poll_pkt_cnt goes down to zero,
3045 	 * then it means that drain is already running and we
3046 	 * will turn off polling at that time if there is
3047 	 * no backlog. As long as there are packets queued either
3048 	 * is soft ring set or its soft rings, we will leave
3049 	 * the interface in polling mode.
3050 	 */
3051 	mutex_enter(&mac_srs->srs_bw->mac_bw_lock);
3052 	if ((mac_srs->srs_state & SRS_POLLING_CAPAB) &&
3053 	    ((mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED) ||
3054 	    (srs_rx->sr_poll_pkt_cnt > 0))) {
3055 		MAC_SRS_POLLING_ON(mac_srs);
3056 		mac_srs->srs_state &= ~(SRS_PROC|proc_type);
3057 		if ((mac_srs->srs_first != NULL) &&
3058 		    (mac_srs->srs_tid == NULL))
3059 			mac_srs->srs_tid = timeout(mac_srs_fire,
3060 			    mac_srs, 1);
3061 		mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
3062 		return;
3063 	}
3064 	mutex_exit(&mac_srs->srs_bw->mac_bw_lock);
3065 
3066 leave_poll:
3067 
3068 	/* Nothing else to do. Get out of poll mode */
3069 	MAC_SRS_POLLING_OFF(mac_srs);
3070 	mac_srs->srs_state &= ~(SRS_PROC|proc_type);
3071 }
3072 
3073 /*
3074  * mac_srs_worker
3075  *
3076  * The SRS worker routine. Drains the queue when no one else is
3077  * processing it.
3078  */
3079 void
3080 mac_srs_worker(mac_soft_ring_set_t *mac_srs)
3081 {
3082 	kmutex_t		*lock = &mac_srs->srs_lock;
3083 	kcondvar_t		*async = &mac_srs->srs_async;
3084 	callb_cpr_t		cprinfo;
3085 	boolean_t		bw_ctl_flag;
3086 
3087 	CALLB_CPR_INIT(&cprinfo, lock, callb_generic_cpr, "srs_worker");
3088 	mutex_enter(lock);
3089 
3090 start:
3091 	for (;;) {
3092 		bw_ctl_flag = B_FALSE;
3093 		if (mac_srs->srs_type & SRST_BW_CONTROL) {
3094 			MAC_SRS_BW_LOCK(mac_srs);
3095 			MAC_SRS_CHECK_BW_CONTROL(mac_srs);
3096 			if (mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED)
3097 				bw_ctl_flag = B_TRUE;
3098 			MAC_SRS_BW_UNLOCK(mac_srs);
3099 		}
3100 		/*
3101 		 * The SRS_BW_ENFORCED flag may change since we have dropped
3102 		 * the mac_bw_lock. However the drain function can handle both
3103 		 * a drainable SRS or a bandwidth controlled SRS, and the
3104 		 * effect of scheduling a timeout is to wakeup the worker
3105 		 * thread which in turn will call the drain function. Since
3106 		 * we release the srs_lock atomically only in the cv_wait there
3107 		 * isn't a fear of waiting for ever.
3108 		 */
3109 		while (((mac_srs->srs_state & SRS_PROC) ||
3110 		    (mac_srs->srs_first == NULL) || bw_ctl_flag ||
3111 		    (mac_srs->srs_state & SRS_TX_BLOCKED)) &&
3112 		    !(mac_srs->srs_state & SRS_PAUSE)) {
3113 			/*
3114 			 * If we have packets queued and we are here
3115 			 * because B/W control is in place, we better
3116 			 * schedule the worker wakeup after 1 tick
3117 			 * to see if bandwidth control can be relaxed.
3118 			 */
3119 			if (bw_ctl_flag && mac_srs->srs_tid == NULL) {
3120 				/*
3121 				 * We need to ensure that a timer  is already
3122 				 * scheduled or we force  schedule one for
3123 				 * later so that we can continue processing
3124 				 * after this  quanta is over.
3125 				 */
3126 				mac_srs->srs_tid = timeout(mac_srs_fire,
3127 				    mac_srs, 1);
3128 			}
3129 wait:
3130 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
3131 			cv_wait(async, lock);
3132 			CALLB_CPR_SAFE_END(&cprinfo, lock);
3133 
3134 			if (mac_srs->srs_state & SRS_PAUSE)
3135 				goto done;
3136 			if (mac_srs->srs_state & SRS_PROC)
3137 				goto wait;
3138 
3139 			if (mac_srs->srs_first != NULL &&
3140 			    mac_srs->srs_type & SRST_BW_CONTROL) {
3141 				MAC_SRS_BW_LOCK(mac_srs);
3142 				if (mac_srs->srs_bw->mac_bw_state &
3143 				    SRS_BW_ENFORCED) {
3144 					MAC_SRS_CHECK_BW_CONTROL(mac_srs);
3145 				}
3146 				bw_ctl_flag = mac_srs->srs_bw->mac_bw_state &
3147 				    SRS_BW_ENFORCED;
3148 				MAC_SRS_BW_UNLOCK(mac_srs);
3149 			}
3150 		}
3151 
3152 		if (mac_srs->srs_state & SRS_PAUSE)
3153 			goto done;
3154 		mac_srs->srs_drain_func(mac_srs, SRS_WORKER);
3155 	}
3156 done:
3157 	/*
3158 	 * The Rx SRS quiesce logic first cuts off packet supply to the SRS
3159 	 * from both hard and soft classifications and waits for such threads
3160 	 * to finish before signaling the worker. So at this point the only
3161 	 * thread left that could be competing with the worker is the poll
3162 	 * thread. In the case of Tx, there shouldn't be any thread holding
3163 	 * SRS_PROC at this point.
3164 	 */
3165 	if (!(mac_srs->srs_state & SRS_PROC)) {
3166 		mac_srs->srs_state |= SRS_PROC;
3167 	} else {
3168 		ASSERT((mac_srs->srs_type & SRST_TX) == 0);
3169 		/*
3170 		 * Poll thread still owns the SRS and is still running
3171 		 */
3172 		ASSERT((mac_srs->srs_poll_thr == NULL) ||
3173 		    ((mac_srs->srs_state & SRS_POLL_THR_OWNER) ==
3174 		    SRS_POLL_THR_OWNER));
3175 	}
3176 	mac_srs_worker_quiesce(mac_srs);
3177 	/*
3178 	 * Wait for the SRS_RESTART or SRS_CONDEMNED signal from the initiator
3179 	 * of the quiesce operation
3180 	 */
3181 	while (!(mac_srs->srs_state & (SRS_CONDEMNED | SRS_RESTART)))
3182 		cv_wait(&mac_srs->srs_async, &mac_srs->srs_lock);
3183 
3184 	if (mac_srs->srs_state & SRS_RESTART) {
3185 		ASSERT(!(mac_srs->srs_state & SRS_CONDEMNED));
3186 		mac_srs_worker_restart(mac_srs);
3187 		mac_srs->srs_state &= ~SRS_PROC;
3188 		goto start;
3189 	}
3190 
3191 	if (!(mac_srs->srs_state & SRS_CONDEMNED_DONE))
3192 		mac_srs_worker_quiesce(mac_srs);
3193 
3194 	mac_srs->srs_state &= ~SRS_PROC;
3195 	/* The macro drops the srs_lock */
3196 	CALLB_CPR_EXIT(&cprinfo);
3197 	thread_exit();
3198 }
3199 
3200 /*
3201  * mac_rx_srs_subflow_process
3202  *
3203  * Receive side routine called from interrupt path when there are
3204  * sub flows present on this SRS.
3205  */
3206 /* ARGSUSED */
3207 void
3208 mac_rx_srs_subflow_process(void *arg, mac_resource_handle_t srs,
3209     mblk_t *mp_chain, boolean_t loopback)
3210 {
3211 	flow_entry_t		*flent = NULL;
3212 	flow_entry_t		*prev_flent = NULL;
3213 	mblk_t			*mp = NULL;
3214 	mblk_t			*tail = NULL;
3215 	mac_soft_ring_set_t	*mac_srs = (mac_soft_ring_set_t *)srs;
3216 	mac_client_impl_t	*mcip;
3217 
3218 	mcip = mac_srs->srs_mcip;
3219 	ASSERT(mcip != NULL);
3220 
3221 	/*
3222 	 * We need to determine the SRS for every packet
3223 	 * by walking the flow table, if we don't get any,
3224 	 * then we proceed using the SRS we came with.
3225 	 */
3226 	mp = tail = mp_chain;
3227 	while (mp != NULL) {
3228 
3229 		/*
3230 		 * We will increment the stats for the mactching subflow.
3231 		 * when we get the bytes/pkt count for the classified packets
3232 		 * later in mac_rx_srs_process.
3233 		 */
3234 		(void) mac_flow_lookup(mcip->mci_subflow_tab, mp,
3235 		    FLOW_INBOUND, &flent);
3236 
3237 		if (mp == mp_chain || flent == prev_flent) {
3238 			if (prev_flent != NULL)
3239 				FLOW_REFRELE(prev_flent);
3240 			prev_flent = flent;
3241 			flent = NULL;
3242 			tail = mp;
3243 			mp = mp->b_next;
3244 			continue;
3245 		}
3246 		tail->b_next = NULL;
3247 		/*
3248 		 * A null indicates, this is for the mac_srs itself.
3249 		 * XXX-venu : probably assert for fe_rx_srs_cnt == 0.
3250 		 */
3251 		if (prev_flent == NULL || prev_flent->fe_rx_srs_cnt == 0) {
3252 			mac_rx_srs_process(arg,
3253 			    (mac_resource_handle_t)mac_srs, mp_chain,
3254 			    loopback);
3255 		} else {
3256 			(prev_flent->fe_cb_fn)(prev_flent->fe_cb_arg1,
3257 			    prev_flent->fe_cb_arg2, mp_chain, loopback);
3258 			FLOW_REFRELE(prev_flent);
3259 		}
3260 		prev_flent = flent;
3261 		flent = NULL;
3262 		mp_chain = mp;
3263 		tail = mp;
3264 		mp = mp->b_next;
3265 	}
3266 	/* Last chain */
3267 	ASSERT(mp_chain != NULL);
3268 	if (prev_flent == NULL || prev_flent->fe_rx_srs_cnt == 0) {
3269 		mac_rx_srs_process(arg,
3270 		    (mac_resource_handle_t)mac_srs, mp_chain, loopback);
3271 	} else {
3272 		(prev_flent->fe_cb_fn)(prev_flent->fe_cb_arg1,
3273 		    prev_flent->fe_cb_arg2, mp_chain, loopback);
3274 		FLOW_REFRELE(prev_flent);
3275 	}
3276 }
3277 
3278 /*
3279  * MAC SRS receive side routine. If the data is coming from the
3280  * network (i.e. from a NIC) then this is called in interrupt context.
3281  * If the data is coming from a local sender (e.g. mac_tx_send() or
3282  * bridge_forward()) then this is not called in interrupt context.
3283  *
3284  * loopback is set to force a context switch on the loopback
3285  * path between MAC clients.
3286  */
3287 /* ARGSUSED */
3288 void
3289 mac_rx_srs_process(void *arg, mac_resource_handle_t srs, mblk_t *mp_chain,
3290     boolean_t loopback)
3291 {
3292 	mac_soft_ring_set_t	*mac_srs = (mac_soft_ring_set_t *)srs;
3293 	mblk_t			*mp, *tail, *head;
3294 	int			count = 0;
3295 	int			count1;
3296 	size_t			sz = 0;
3297 	size_t			chain_sz, sz1;
3298 	mac_bw_ctl_t		*mac_bw;
3299 	mac_srs_rx_t		*srs_rx = &mac_srs->srs_rx;
3300 
3301 	/*
3302 	 * Set the tail, count and sz. We set the sz irrespective
3303 	 * of whether we are doing B/W control or not for the
3304 	 * purpose of updating the stats.
3305 	 */
3306 	mp = tail = mp_chain;
3307 	while (mp != NULL) {
3308 		tail = mp;
3309 		count++;
3310 		sz += msgdsize(mp);
3311 		mp = mp->b_next;
3312 	}
3313 
3314 	mutex_enter(&mac_srs->srs_lock);
3315 
3316 	if (loopback) {
3317 		SRS_RX_STAT_UPDATE(mac_srs, lclbytes, sz);
3318 		SRS_RX_STAT_UPDATE(mac_srs, lclcnt, count);
3319 
3320 	} else {
3321 		SRS_RX_STAT_UPDATE(mac_srs, intrbytes, sz);
3322 		SRS_RX_STAT_UPDATE(mac_srs, intrcnt, count);
3323 	}
3324 
3325 	/*
3326 	 * If the SRS in already being processed; has been blanked;
3327 	 * can be processed by worker thread only; or the B/W limit
3328 	 * has been reached, then queue the chain and check if
3329 	 * worker thread needs to be awakend.
3330 	 */
3331 	if (mac_srs->srs_type & SRST_BW_CONTROL) {
3332 		mac_bw = mac_srs->srs_bw;
3333 		ASSERT(mac_bw != NULL);
3334 		mutex_enter(&mac_bw->mac_bw_lock);
3335 		mac_bw->mac_bw_intr += sz;
3336 		if (mac_bw->mac_bw_limit == 0) {
3337 			/* zero bandwidth: drop all */
3338 			srs_rx->sr_stat.mrs_sdrops += count;
3339 			mac_bw->mac_bw_drop_bytes += sz;
3340 			mutex_exit(&mac_bw->mac_bw_lock);
3341 			mutex_exit(&mac_srs->srs_lock);
3342 			mac_drop_chain(mp_chain, "Rx no bandwidth");
3343 			return;
3344 		} else {
3345 			if ((mac_bw->mac_bw_sz + sz) <=
3346 			    mac_bw->mac_bw_drop_threshold) {
3347 				mutex_exit(&mac_bw->mac_bw_lock);
3348 				MAC_RX_SRS_ENQUEUE_CHAIN(mac_srs, mp_chain,
3349 				    tail, count, sz);
3350 			} else {
3351 				mp = mp_chain;
3352 				chain_sz = 0;
3353 				count1 = 0;
3354 				tail = NULL;
3355 				head = NULL;
3356 				while (mp != NULL) {
3357 					sz1 = msgdsize(mp);
3358 					if (mac_bw->mac_bw_sz + chain_sz + sz1 >
3359 					    mac_bw->mac_bw_drop_threshold)
3360 						break;
3361 					chain_sz += sz1;
3362 					count1++;
3363 					tail = mp;
3364 					mp = mp->b_next;
3365 				}
3366 				mutex_exit(&mac_bw->mac_bw_lock);
3367 				if (tail != NULL) {
3368 					head = tail->b_next;
3369 					tail->b_next = NULL;
3370 					MAC_RX_SRS_ENQUEUE_CHAIN(mac_srs,
3371 					    mp_chain, tail, count1, chain_sz);
3372 					sz -= chain_sz;
3373 					count -= count1;
3374 				} else {
3375 					/* Can't pick up any */
3376 					head = mp_chain;
3377 				}
3378 				if (head != NULL) {
3379 					/* Drop any packet over the threshold */
3380 					srs_rx->sr_stat.mrs_sdrops += count;
3381 					mutex_enter(&mac_bw->mac_bw_lock);
3382 					mac_bw->mac_bw_drop_bytes += sz;
3383 					mutex_exit(&mac_bw->mac_bw_lock);
3384 					freemsgchain(head);
3385 				}
3386 			}
3387 			MAC_SRS_WORKER_WAKEUP(mac_srs);
3388 			mutex_exit(&mac_srs->srs_lock);
3389 			return;
3390 		}
3391 	}
3392 
3393 	/*
3394 	 * If the total number of packets queued in the SRS and
3395 	 * its associated soft rings exceeds the max allowed,
3396 	 * then drop the chain. If we are polling capable, this
3397 	 * shouldn't be happening.
3398 	 */
3399 	if (!(mac_srs->srs_type & SRST_BW_CONTROL) &&
3400 	    (srs_rx->sr_poll_pkt_cnt > srs_rx->sr_hiwat)) {
3401 		mac_bw = mac_srs->srs_bw;
3402 		srs_rx->sr_stat.mrs_sdrops += count;
3403 		mutex_enter(&mac_bw->mac_bw_lock);
3404 		mac_bw->mac_bw_drop_bytes += sz;
3405 		mutex_exit(&mac_bw->mac_bw_lock);
3406 		freemsgchain(mp_chain);
3407 		mutex_exit(&mac_srs->srs_lock);
3408 		return;
3409 	}
3410 
3411 	MAC_RX_SRS_ENQUEUE_CHAIN(mac_srs, mp_chain, tail, count, sz);
3412 
3413 	if (!(mac_srs->srs_state & SRS_PROC)) {
3414 		/*
3415 		 * If we are coming via loopback, if we are not optimizing for
3416 		 * latency, or if our stack is running deep, we should signal
3417 		 * the worker thread.
3418 		 */
3419 		if (loopback || !(mac_srs->srs_state & SRS_LATENCY_OPT) ||
3420 		    MAC_RX_SRS_TOODEEP()) {
3421 			/*
3422 			 * For loopback, We need to let the worker take
3423 			 * over as we don't want to continue in the same
3424 			 * thread even if we can. This could lead to stack
3425 			 * overflows and may also end up using
3426 			 * resources (cpu) incorrectly.
3427 			 */
3428 			cv_signal(&mac_srs->srs_async);
3429 		} else {
3430 			/*
3431 			 * Seems like no one is processing the SRS and
3432 			 * there is no backlog. We also inline process
3433 			 * our packet if its a single packet in non
3434 			 * latency optimized case (in latency optimized
3435 			 * case, we inline process chains of any size).
3436 			 */
3437 			mac_srs->srs_drain_func(mac_srs, SRS_PROC_FAST);
3438 		}
3439 	}
3440 	mutex_exit(&mac_srs->srs_lock);
3441 }
3442 
3443 /* TX SIDE ROUTINES (RUNTIME) */
3444 
3445 /*
3446  * mac_tx_srs_no_desc
3447  *
3448  * This routine is called by Tx single ring default mode
3449  * when Tx ring runs out of descs.
3450  */
3451 mac_tx_cookie_t
3452 mac_tx_srs_no_desc(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3453     uint16_t flag, mblk_t **ret_mp)
3454 {
3455 	mac_tx_cookie_t cookie = 0;
3456 	mac_srs_tx_t *srs_tx = &mac_srs->srs_tx;
3457 	boolean_t wakeup_worker = B_TRUE;
3458 	uint32_t tx_mode = srs_tx->st_mode;
3459 	int cnt, sz;
3460 	mblk_t *tail;
3461 
3462 	ASSERT(tx_mode == SRS_TX_DEFAULT || tx_mode == SRS_TX_BW);
3463 	if (flag & MAC_DROP_ON_NO_DESC) {
3464 		MAC_TX_SRS_DROP_MESSAGE(mac_srs, mp_chain, cookie,
3465 		    "Tx no desc");
3466 	} else {
3467 		if (mac_srs->srs_first != NULL)
3468 			wakeup_worker = B_FALSE;
3469 		MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
3470 		if (flag & MAC_TX_NO_ENQUEUE) {
3471 			/*
3472 			 * If TX_QUEUED is not set, queue the
3473 			 * packet and let mac_tx_srs_drain()
3474 			 * set the TX_BLOCKED bit for the
3475 			 * reasons explained above. Otherwise,
3476 			 * return the mblks.
3477 			 */
3478 			if (wakeup_worker) {
3479 				MAC_TX_SRS_ENQUEUE_CHAIN(mac_srs,
3480 				    mp_chain, tail, cnt, sz);
3481 			} else {
3482 				MAC_TX_SET_NO_ENQUEUE(mac_srs,
3483 				    mp_chain, ret_mp, cookie);
3484 			}
3485 		} else {
3486 			MAC_TX_SRS_TEST_HIWAT(mac_srs, mp_chain,
3487 			    tail, cnt, sz, cookie);
3488 		}
3489 		if (wakeup_worker)
3490 			cv_signal(&mac_srs->srs_async);
3491 	}
3492 	return (cookie);
3493 }
3494 
3495 /*
3496  * mac_tx_srs_enqueue
3497  *
3498  * This routine is called when Tx SRS is operating in either serializer
3499  * or bandwidth mode. In serializer mode, a packet will get enqueued
3500  * when a thread cannot enter SRS exclusively. In bandwidth mode,
3501  * packets gets queued if allowed byte-count limit for a tick is
3502  * exceeded. The action that gets taken when MAC_DROP_ON_NO_DESC and
3503  * MAC_TX_NO_ENQUEUE is set is different than when operaing in either
3504  * the default mode or fanout mode. Here packets get dropped or
3505  * returned back to the caller only after hi-watermark worth of data
3506  * is queued.
3507  */
3508 static mac_tx_cookie_t
3509 mac_tx_srs_enqueue(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3510     uint16_t flag, uintptr_t fanout_hint, mblk_t **ret_mp)
3511 {
3512 	mac_tx_cookie_t cookie = 0;
3513 	int cnt, sz;
3514 	mblk_t *tail;
3515 	boolean_t wakeup_worker = B_TRUE;
3516 
3517 	/*
3518 	 * Ignore fanout hint if we don't have multiple tx rings.
3519 	 */
3520 	if (!MAC_TX_SOFT_RINGS(mac_srs))
3521 		fanout_hint = 0;
3522 
3523 	if (mac_srs->srs_first != NULL)
3524 		wakeup_worker = B_FALSE;
3525 	MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
3526 	if (flag & MAC_DROP_ON_NO_DESC) {
3527 		if (mac_srs->srs_count > mac_srs->srs_tx.st_hiwat) {
3528 			MAC_TX_SRS_DROP_MESSAGE(mac_srs, mp_chain, cookie,
3529 			    "Tx SRS hiwat");
3530 		} else {
3531 			MAC_TX_SRS_ENQUEUE_CHAIN(mac_srs,
3532 			    mp_chain, tail, cnt, sz);
3533 		}
3534 	} else if (flag & MAC_TX_NO_ENQUEUE) {
3535 		if ((mac_srs->srs_count > mac_srs->srs_tx.st_hiwat) ||
3536 		    (mac_srs->srs_state & SRS_TX_WAKEUP_CLIENT)) {
3537 			MAC_TX_SET_NO_ENQUEUE(mac_srs, mp_chain,
3538 			    ret_mp, cookie);
3539 		} else {
3540 			mp_chain->b_prev = (mblk_t *)fanout_hint;
3541 			MAC_TX_SRS_ENQUEUE_CHAIN(mac_srs,
3542 			    mp_chain, tail, cnt, sz);
3543 		}
3544 	} else {
3545 		/*
3546 		 * If you are BW_ENFORCED, just enqueue the
3547 		 * packet. srs_worker will drain it at the
3548 		 * prescribed rate. Before enqueueing, save
3549 		 * the fanout hint.
3550 		 */
3551 		mp_chain->b_prev = (mblk_t *)fanout_hint;
3552 		MAC_TX_SRS_TEST_HIWAT(mac_srs, mp_chain,
3553 		    tail, cnt, sz, cookie);
3554 	}
3555 	if (wakeup_worker)
3556 		cv_signal(&mac_srs->srs_async);
3557 	return (cookie);
3558 }
3559 
3560 /*
3561  * There are seven tx modes:
3562  *
3563  * 1) Default mode (SRS_TX_DEFAULT)
3564  * 2) Serialization mode (SRS_TX_SERIALIZE)
3565  * 3) Fanout mode (SRS_TX_FANOUT)
3566  * 4) Bandwdith mode (SRS_TX_BW)
3567  * 5) Fanout and Bandwidth mode (SRS_TX_BW_FANOUT)
3568  * 6) aggr Tx mode (SRS_TX_AGGR)
3569  * 7) aggr Tx bw mode (SRS_TX_BW_AGGR)
3570  *
3571  * The tx mode in which an SRS operates is decided in mac_tx_srs_setup()
3572  * based on the number of Tx rings requested for an SRS and whether
3573  * bandwidth control is requested or not.
3574  *
3575  * The default mode (i.e., no fanout/no bandwidth) is used when the
3576  * underlying NIC does not have Tx rings or just one Tx ring. In this mode,
3577  * the SRS acts as a pass-thru. Packets will go directly to mac_tx_send().
3578  * When the underlying Tx ring runs out of Tx descs, it starts queueing up
3579  * packets in SRS. When flow-control is relieved, the srs_worker drains
3580  * the queued packets and informs blocked clients to restart sending
3581  * packets.
3582  *
3583  * In the SRS_TX_SERIALIZE mode, all calls to mac_tx() are serialized. This
3584  * mode is used when the link has no Tx rings or only one Tx ring.
3585  *
3586  * In the SRS_TX_FANOUT mode, packets will be fanned out to multiple
3587  * Tx rings. Each Tx ring will have a soft ring associated with it.
3588  * These soft rings will be hung off the Tx SRS. Queueing if it happens
3589  * due to lack of Tx desc will be in individual soft ring (and not srs)
3590  * associated with Tx ring.
3591  *
3592  * In the TX_BW mode, tx srs will allow packets to go down to Tx ring
3593  * only if bw is available. Otherwise the packets will be queued in
3594  * SRS. If fanout to multiple Tx rings is configured, the packets will
3595  * be fanned out among the soft rings associated with the Tx rings.
3596  *
3597  * In SRS_TX_AGGR mode, mac_tx_aggr_mode() routine is called. This routine
3598  * invokes an aggr function, aggr_find_tx_ring(), to find a pseudo Tx ring
3599  * belonging to a port on which the packet has to be sent. Aggr will
3600  * always have a pseudo Tx ring associated with it even when it is an
3601  * aggregation over a single NIC that has no Tx rings. Even in such a
3602  * case, the single pseudo Tx ring will have a soft ring associated with
3603  * it and the soft ring will hang off the SRS.
3604  *
3605  * If a bandwidth is specified for an aggr, SRS_TX_BW_AGGR mode is used.
3606  * In this mode, the bandwidth is first applied on the outgoing packets
3607  * and later mac_tx_addr_mode() function is called to send the packet out
3608  * of one of the pseudo Tx rings.
3609  *
3610  * Four flags are used in srs_state for indicating flow control
3611  * conditions : SRS_TX_BLOCKED, SRS_TX_HIWAT, SRS_TX_WAKEUP_CLIENT.
3612  * SRS_TX_BLOCKED indicates out of Tx descs. SRS expects a wakeup from the
3613  * driver below.
3614  * SRS_TX_HIWAT indicates packet count enqueued in Tx SRS exceeded Tx hiwat
3615  * and flow-control pressure is applied back to clients. The clients expect
3616  * wakeup when flow-control is relieved.
3617  * SRS_TX_WAKEUP_CLIENT get set when (flag == MAC_TX_NO_ENQUEUE) and mblk
3618  * got returned back to client either due to lack of Tx descs or due to bw
3619  * control reasons. The clients expect a wakeup when condition is relieved.
3620  *
3621  * The fourth argument to mac_tx() is the flag. Normally it will be 0 but
3622  * some clients set the following values too: MAC_DROP_ON_NO_DESC,
3623  * MAC_TX_NO_ENQUEUE
3624  * Mac clients that do not want packets to be enqueued in the mac layer set
3625  * MAC_DROP_ON_NO_DESC value. The packets won't be queued in the Tx SRS or
3626  * Tx soft rings but instead get dropped when the NIC runs out of desc. The
3627  * behaviour of this flag is different when the Tx is running in serializer
3628  * or bandwidth mode. Under these (Serializer, bandwidth) modes, the packet
3629  * get dropped when Tx high watermark is reached.
3630  * There are some mac clients like vsw, aggr that want the mblks to be
3631  * returned back to clients instead of being queued in Tx SRS (or Tx soft
3632  * rings) under flow-control (i.e., out of desc or exceeding bw limits)
3633  * conditions. These clients call mac_tx() with MAC_TX_NO_ENQUEUE flag set.
3634  * In the default and Tx fanout mode, the un-transmitted mblks will be
3635  * returned back to the clients when the driver runs out of Tx descs.
3636  * SRS_TX_WAKEUP_CLIENT (or S_RING_WAKEUP_CLIENT) will be set in SRS (or
3637  * soft ring) so that the clients can be woken up when Tx desc become
3638  * available. When running in serializer or bandwidth mode mode,
3639  * SRS_TX_WAKEUP_CLIENT will be set when tx hi-watermark is reached.
3640  */
3641 
3642 mac_tx_func_t
3643 mac_tx_get_func(uint32_t mode)
3644 {
3645 	return (mac_tx_mode_list[mode].mac_tx_func);
3646 }
3647 
3648 /* ARGSUSED */
3649 static mac_tx_cookie_t
3650 mac_tx_single_ring_mode(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3651     uintptr_t fanout_hint, uint16_t flag, mblk_t **ret_mp)
3652 {
3653 	mac_srs_tx_t		*srs_tx = &mac_srs->srs_tx;
3654 	mac_tx_stats_t		stats;
3655 	mac_tx_cookie_t		cookie = 0;
3656 
3657 	ASSERT(srs_tx->st_mode == SRS_TX_DEFAULT);
3658 
3659 	/* Regular case with a single Tx ring */
3660 	/*
3661 	 * SRS_TX_BLOCKED is set when underlying NIC runs
3662 	 * out of Tx descs and messages start getting
3663 	 * queued. It won't get reset until
3664 	 * tx_srs_drain() completely drains out the
3665 	 * messages.
3666 	 */
3667 	if ((mac_srs->srs_state & SRS_ENQUEUED) != 0) {
3668 		/* Tx descs/resources not available */
3669 		mutex_enter(&mac_srs->srs_lock);
3670 		if ((mac_srs->srs_state & SRS_ENQUEUED) != 0) {
3671 			cookie = mac_tx_srs_no_desc(mac_srs, mp_chain,
3672 			    flag, ret_mp);
3673 			mutex_exit(&mac_srs->srs_lock);
3674 			return (cookie);
3675 		}
3676 		/*
3677 		 * While we were computing mblk count, the
3678 		 * flow control condition got relieved.
3679 		 * Continue with the transmission.
3680 		 */
3681 		mutex_exit(&mac_srs->srs_lock);
3682 	}
3683 
3684 	mp_chain = mac_tx_send(srs_tx->st_arg1, srs_tx->st_arg2,
3685 	    mp_chain, &stats);
3686 
3687 	/*
3688 	 * Multiple threads could be here sending packets.
3689 	 * Under such conditions, it is not possible to
3690 	 * automically set SRS_TX_BLOCKED bit to indicate
3691 	 * out of tx desc condition. To atomically set
3692 	 * this, we queue the returned packet and do
3693 	 * the setting of SRS_TX_BLOCKED in
3694 	 * mac_tx_srs_drain().
3695 	 */
3696 	if (mp_chain != NULL) {
3697 		mutex_enter(&mac_srs->srs_lock);
3698 		cookie = mac_tx_srs_no_desc(mac_srs, mp_chain, flag, ret_mp);
3699 		mutex_exit(&mac_srs->srs_lock);
3700 		return (cookie);
3701 	}
3702 	SRS_TX_STATS_UPDATE(mac_srs, &stats);
3703 
3704 	return (0);
3705 }
3706 
3707 /*
3708  * mac_tx_serialize_mode
3709  *
3710  * This is an experimental mode implemented as per the request of PAE.
3711  * In this mode, all callers attempting to send a packet to the NIC
3712  * will get serialized. Only one thread at any time will access the
3713  * NIC to send the packet out.
3714  */
3715 /* ARGSUSED */
3716 static mac_tx_cookie_t
3717 mac_tx_serializer_mode(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3718     uintptr_t fanout_hint, uint16_t flag, mblk_t **ret_mp)
3719 {
3720 	mac_tx_stats_t		stats;
3721 	mac_tx_cookie_t		cookie = 0;
3722 	mac_srs_tx_t		*srs_tx = &mac_srs->srs_tx;
3723 
3724 	/* Single ring, serialize below */
3725 	ASSERT(srs_tx->st_mode == SRS_TX_SERIALIZE);
3726 	mutex_enter(&mac_srs->srs_lock);
3727 	if ((mac_srs->srs_first != NULL) ||
3728 	    (mac_srs->srs_state & SRS_PROC)) {
3729 		/*
3730 		 * In serialization mode, queue all packets until
3731 		 * TX_HIWAT is set.
3732 		 * If drop bit is set, drop if TX_HIWAT is set.
3733 		 * If no_enqueue is set, still enqueue until hiwat
3734 		 * is set and return mblks after TX_HIWAT is set.
3735 		 */
3736 		cookie = mac_tx_srs_enqueue(mac_srs, mp_chain,
3737 		    flag, 0, ret_mp);
3738 		mutex_exit(&mac_srs->srs_lock);
3739 		return (cookie);
3740 	}
3741 	/*
3742 	 * No packets queued, nothing on proc and no flow
3743 	 * control condition. Fast-path, ok. Do inline
3744 	 * processing.
3745 	 */
3746 	mac_srs->srs_state |= SRS_PROC;
3747 	mutex_exit(&mac_srs->srs_lock);
3748 
3749 	mp_chain = mac_tx_send(srs_tx->st_arg1, srs_tx->st_arg2,
3750 	    mp_chain, &stats);
3751 
3752 	mutex_enter(&mac_srs->srs_lock);
3753 	mac_srs->srs_state &= ~SRS_PROC;
3754 	if (mp_chain != NULL) {
3755 		cookie = mac_tx_srs_enqueue(mac_srs,
3756 		    mp_chain, flag, 0, ret_mp);
3757 	}
3758 	if (mac_srs->srs_first != NULL) {
3759 		/*
3760 		 * We processed inline our packet and a new
3761 		 * packet/s got queued while we were
3762 		 * processing. Wakeup srs worker
3763 		 */
3764 		cv_signal(&mac_srs->srs_async);
3765 	}
3766 	mutex_exit(&mac_srs->srs_lock);
3767 
3768 	if (cookie == 0)
3769 		SRS_TX_STATS_UPDATE(mac_srs, &stats);
3770 
3771 	return (cookie);
3772 }
3773 
3774 /*
3775  * mac_tx_fanout_mode
3776  *
3777  * In this mode, the SRS will have access to multiple Tx rings to send
3778  * the packet out. The fanout hint that is passed as an argument is
3779  * used to find an appropriate ring to fanout the traffic. Each Tx
3780  * ring, in turn,  will have a soft ring associated with it. If a Tx
3781  * ring runs out of Tx desc's the returned packet will be queued in
3782  * the soft ring associated with that Tx ring. The srs itself will not
3783  * queue any packets.
3784  */
3785 
3786 #define	MAC_TX_SOFT_RING_PROCESS(chain) {				\
3787 	index = COMPUTE_INDEX(hash, mac_srs->srs_tx_ring_count),	\
3788 	softring = mac_srs->srs_tx_soft_rings[index];			\
3789 	cookie = mac_tx_soft_ring_process(softring, chain, flag, ret_mp); \
3790 	DTRACE_PROBE2(tx__fanout, uint64_t, hash, uint_t, index);	\
3791 }
3792 
3793 static mac_tx_cookie_t
3794 mac_tx_fanout_mode(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3795     uintptr_t fanout_hint, uint16_t flag, mblk_t **ret_mp)
3796 {
3797 	mac_soft_ring_t		*softring;
3798 	uint64_t		hash;
3799 	uint_t			index;
3800 	mac_tx_cookie_t		cookie = 0;
3801 
3802 	ASSERT(mac_srs->srs_tx.st_mode == SRS_TX_FANOUT ||
3803 	    mac_srs->srs_tx.st_mode == SRS_TX_BW_FANOUT);
3804 	if (fanout_hint != 0) {
3805 		/*
3806 		 * The hint is specified by the caller, simply pass the
3807 		 * whole chain to the soft ring.
3808 		 */
3809 		hash = HASH_HINT(fanout_hint);
3810 		MAC_TX_SOFT_RING_PROCESS(mp_chain);
3811 	} else {
3812 		mblk_t *last_mp, *cur_mp, *sub_chain;
3813 		uint64_t last_hash = 0;
3814 		uint_t media = mac_srs->srs_mcip->mci_mip->mi_info.mi_media;
3815 
3816 		/*
3817 		 * Compute the hash from the contents (headers) of the
3818 		 * packets of the mblk chain. Split the chains into
3819 		 * subchains of the same conversation.
3820 		 *
3821 		 * Since there may be more than one ring used for
3822 		 * sub-chains of the same call, and since the caller
3823 		 * does not maintain per conversation state since it
3824 		 * passed a zero hint, unsent subchains will be
3825 		 * dropped.
3826 		 */
3827 
3828 		flag |= MAC_DROP_ON_NO_DESC;
3829 		ret_mp = NULL;
3830 
3831 		ASSERT(ret_mp == NULL);
3832 
3833 		sub_chain = NULL;
3834 		last_mp = NULL;
3835 
3836 		for (cur_mp = mp_chain; cur_mp != NULL;
3837 		    cur_mp = cur_mp->b_next) {
3838 			hash = mac_pkt_hash(media, cur_mp, MAC_PKT_HASH_L4,
3839 			    B_TRUE);
3840 			if (last_hash != 0 && hash != last_hash) {
3841 				/*
3842 				 * Starting a different subchain, send current
3843 				 * chain out.
3844 				 */
3845 				ASSERT(last_mp != NULL);
3846 				last_mp->b_next = NULL;
3847 				MAC_TX_SOFT_RING_PROCESS(sub_chain);
3848 				sub_chain = NULL;
3849 			}
3850 
3851 			/* add packet to subchain */
3852 			if (sub_chain == NULL)
3853 				sub_chain = cur_mp;
3854 			last_mp = cur_mp;
3855 			last_hash = hash;
3856 		}
3857 
3858 		if (sub_chain != NULL) {
3859 			/* send last subchain */
3860 			ASSERT(last_mp != NULL);
3861 			last_mp->b_next = NULL;
3862 			MAC_TX_SOFT_RING_PROCESS(sub_chain);
3863 		}
3864 
3865 		cookie = 0;
3866 	}
3867 
3868 	return (cookie);
3869 }
3870 
3871 /*
3872  * mac_tx_bw_mode
3873  *
3874  * In the bandwidth mode, Tx srs will allow packets to go down to Tx ring
3875  * only if bw is available. Otherwise the packets will be queued in
3876  * SRS. If the SRS has multiple Tx rings, then packets will get fanned
3877  * out to a Tx rings.
3878  */
3879 static mac_tx_cookie_t
3880 mac_tx_bw_mode(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
3881     uintptr_t fanout_hint, uint16_t flag, mblk_t **ret_mp)
3882 {
3883 	int			cnt, sz;
3884 	mblk_t			*tail;
3885 	mac_tx_cookie_t		cookie = 0;
3886 	mac_srs_tx_t		*srs_tx = &mac_srs->srs_tx;
3887 	clock_t			now;
3888 
3889 	ASSERT(TX_BANDWIDTH_MODE(mac_srs));
3890 	ASSERT(mac_srs->srs_type & SRST_BW_CONTROL);
3891 	mutex_enter(&mac_srs->srs_lock);
3892 	if (mac_srs->srs_bw->mac_bw_limit == 0) {
3893 		/*
3894 		 * zero bandwidth, no traffic is sent: drop the packets,
3895 		 * or return the whole chain if the caller requests all
3896 		 * unsent packets back.
3897 		 */
3898 		if (flag & MAC_TX_NO_ENQUEUE) {
3899 			cookie = (mac_tx_cookie_t)mac_srs;
3900 			*ret_mp = mp_chain;
3901 		} else {
3902 			MAC_TX_SRS_DROP_MESSAGE(mac_srs, mp_chain, cookie,
3903 			    "Tx no bandwidth");
3904 		}
3905 		mutex_exit(&mac_srs->srs_lock);
3906 		return (cookie);
3907 	} else if ((mac_srs->srs_first != NULL) ||
3908 	    (mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED)) {
3909 		cookie = mac_tx_srs_enqueue(mac_srs, mp_chain, flag,
3910 		    fanout_hint, ret_mp);
3911 		mutex_exit(&mac_srs->srs_lock);
3912 		return (cookie);
3913 	}
3914 	MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
3915 	now = ddi_get_lbolt();
3916 	if (mac_srs->srs_bw->mac_bw_curr_time != now) {
3917 		mac_srs->srs_bw->mac_bw_curr_time = now;
3918 		mac_srs->srs_bw->mac_bw_used = 0;
3919 	} else if (mac_srs->srs_bw->mac_bw_used >
3920 	    mac_srs->srs_bw->mac_bw_limit) {
3921 		mac_srs->srs_bw->mac_bw_state |= SRS_BW_ENFORCED;
3922 		MAC_TX_SRS_ENQUEUE_CHAIN(mac_srs,
3923 		    mp_chain, tail, cnt, sz);
3924 		/*
3925 		 * Wakeup worker thread. Note that worker
3926 		 * thread has to be woken up so that it
3927 		 * can fire up the timer to be woken up
3928 		 * on the next tick. Also once
3929 		 * BW_ENFORCED is set, it can only be
3930 		 * reset by srs_worker thread. Until then
3931 		 * all packets will get queued up in SRS
3932 		 * and hence this this code path won't be
3933 		 * entered until BW_ENFORCED is reset.
3934 		 */
3935 		cv_signal(&mac_srs->srs_async);
3936 		mutex_exit(&mac_srs->srs_lock);
3937 		return (cookie);
3938 	}
3939 
3940 	mac_srs->srs_bw->mac_bw_used += sz;
3941 	mutex_exit(&mac_srs->srs_lock);
3942 
3943 	if (srs_tx->st_mode == SRS_TX_BW_FANOUT) {
3944 		mac_soft_ring_t *softring;
3945 		uint_t indx, hash;
3946 
3947 		hash = HASH_HINT(fanout_hint);
3948 		indx = COMPUTE_INDEX(hash,
3949 		    mac_srs->srs_tx_ring_count);
3950 		softring = mac_srs->srs_tx_soft_rings[indx];
3951 		return (mac_tx_soft_ring_process(softring, mp_chain, flag,
3952 		    ret_mp));
3953 	} else if (srs_tx->st_mode == SRS_TX_BW_AGGR) {
3954 		return (mac_tx_aggr_mode(mac_srs, mp_chain,
3955 		    fanout_hint, flag, ret_mp));
3956 	} else {
3957 		mac_tx_stats_t		stats;
3958 
3959 		mp_chain = mac_tx_send(srs_tx->st_arg1, srs_tx->st_arg2,
3960 		    mp_chain, &stats);
3961 
3962 		if (mp_chain != NULL) {
3963 			mutex_enter(&mac_srs->srs_lock);
3964 			MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
3965 			if (mac_srs->srs_bw->mac_bw_used > sz)
3966 				mac_srs->srs_bw->mac_bw_used -= sz;
3967 			else
3968 				mac_srs->srs_bw->mac_bw_used = 0;
3969 			cookie = mac_tx_srs_enqueue(mac_srs, mp_chain, flag,
3970 			    fanout_hint, ret_mp);
3971 			mutex_exit(&mac_srs->srs_lock);
3972 			return (cookie);
3973 		}
3974 		SRS_TX_STATS_UPDATE(mac_srs, &stats);
3975 
3976 		return (0);
3977 	}
3978 }
3979 
3980 /*
3981  * mac_tx_aggr_mode
3982  *
3983  * This routine invokes an aggr function, aggr_find_tx_ring(), to find
3984  * a (pseudo) Tx ring belonging to a port on which the packet has to
3985  * be sent. aggr_find_tx_ring() first finds the outgoing port based on
3986  * L2/L3/L4 policy and then uses the fanout_hint passed to it to pick
3987  * a Tx ring from the selected port.
3988  *
3989  * Note that a port can be deleted from the aggregation. In such a case,
3990  * the aggregation layer first separates the port from the rest of the
3991  * ports making sure that port (and thus any Tx rings associated with
3992  * it) won't get selected in the call to aggr_find_tx_ring() function.
3993  * Later calls are made to mac_group_rem_ring() passing pseudo Tx ring
3994  * handles one by one which in turn will quiesce the Tx SRS and remove
3995  * the soft ring associated with the pseudo Tx ring. Unlike Rx side
3996  * where a cookie is used to protect against mac_rx_ring() calls on
3997  * rings that have been removed, no such cookie is needed on the Tx
3998  * side as the pseudo Tx ring won't be available anymore to
3999  * aggr_find_tx_ring() once the port has been removed.
4000  */
4001 static mac_tx_cookie_t
4002 mac_tx_aggr_mode(mac_soft_ring_set_t *mac_srs, mblk_t *mp_chain,
4003     uintptr_t fanout_hint, uint16_t flag, mblk_t **ret_mp)
4004 {
4005 	mac_srs_tx_t		*srs_tx = &mac_srs->srs_tx;
4006 	mac_tx_ring_fn_t	find_tx_ring_fn;
4007 	mac_ring_handle_t	ring = NULL;
4008 	void			*arg;
4009 	mac_soft_ring_t		*sringp;
4010 
4011 	find_tx_ring_fn = srs_tx->st_capab_aggr.mca_find_tx_ring_fn;
4012 	arg = srs_tx->st_capab_aggr.mca_arg;
4013 	if (find_tx_ring_fn(arg, mp_chain, fanout_hint, &ring) == NULL)
4014 		return (0);
4015 	sringp = srs_tx->st_soft_rings[((mac_ring_t *)ring)->mr_index];
4016 	return (mac_tx_soft_ring_process(sringp, mp_chain, flag, ret_mp));
4017 }
4018 
4019 void
4020 mac_tx_invoke_callbacks(mac_client_impl_t *mcip, mac_tx_cookie_t cookie)
4021 {
4022 	mac_cb_t *mcb;
4023 	mac_tx_notify_cb_t *mtnfp;
4024 
4025 	/* Wakeup callback registered clients */
4026 	MAC_CALLBACK_WALKER_INC(&mcip->mci_tx_notify_cb_info);
4027 	for (mcb = mcip->mci_tx_notify_cb_list; mcb != NULL;
4028 	    mcb = mcb->mcb_nextp) {
4029 		mtnfp = (mac_tx_notify_cb_t *)mcb->mcb_objp;
4030 		mtnfp->mtnf_fn(mtnfp->mtnf_arg, cookie);
4031 	}
4032 	MAC_CALLBACK_WALKER_DCR(&mcip->mci_tx_notify_cb_info,
4033 	    &mcip->mci_tx_notify_cb_list);
4034 }
4035 
4036 /* ARGSUSED */
4037 void
4038 mac_tx_srs_drain(mac_soft_ring_set_t *mac_srs, uint_t proc_type)
4039 {
4040 	mblk_t			*head, *tail;
4041 	size_t			sz;
4042 	uint32_t		tx_mode;
4043 	uint_t			saved_pkt_count;
4044 	mac_tx_stats_t		stats;
4045 	mac_srs_tx_t		*srs_tx = &mac_srs->srs_tx;
4046 	clock_t			now;
4047 
4048 	saved_pkt_count = 0;
4049 	ASSERT(mutex_owned(&mac_srs->srs_lock));
4050 	ASSERT(!(mac_srs->srs_state & SRS_PROC));
4051 
4052 	mac_srs->srs_state |= SRS_PROC;
4053 
4054 	tx_mode = srs_tx->st_mode;
4055 	if (tx_mode == SRS_TX_DEFAULT || tx_mode == SRS_TX_SERIALIZE) {
4056 		if (mac_srs->srs_first != NULL) {
4057 			head = mac_srs->srs_first;
4058 			tail = mac_srs->srs_last;
4059 			saved_pkt_count = mac_srs->srs_count;
4060 			mac_srs->srs_first = NULL;
4061 			mac_srs->srs_last = NULL;
4062 			mac_srs->srs_count = 0;
4063 			mutex_exit(&mac_srs->srs_lock);
4064 
4065 			head = mac_tx_send(srs_tx->st_arg1, srs_tx->st_arg2,
4066 			    head, &stats);
4067 
4068 			mutex_enter(&mac_srs->srs_lock);
4069 			if (head != NULL) {
4070 				/* Device out of tx desc, set block */
4071 				if (head->b_next == NULL)
4072 					VERIFY(head == tail);
4073 				tail->b_next = mac_srs->srs_first;
4074 				mac_srs->srs_first = head;
4075 				mac_srs->srs_count +=
4076 				    (saved_pkt_count - stats.mts_opackets);
4077 				if (mac_srs->srs_last == NULL)
4078 					mac_srs->srs_last = tail;
4079 				MAC_TX_SRS_BLOCK(mac_srs, head);
4080 			} else {
4081 				srs_tx->st_woken_up = B_FALSE;
4082 				SRS_TX_STATS_UPDATE(mac_srs, &stats);
4083 			}
4084 		}
4085 	} else if (tx_mode == SRS_TX_BW) {
4086 		/*
4087 		 * We are here because the timer fired and we have some data
4088 		 * to tranmit. Also mac_tx_srs_worker should have reset
4089 		 * SRS_BW_ENFORCED flag
4090 		 */
4091 		ASSERT(!(mac_srs->srs_bw->mac_bw_state & SRS_BW_ENFORCED));
4092 		head = tail = mac_srs->srs_first;
4093 		while (mac_srs->srs_first != NULL) {
4094 			tail = mac_srs->srs_first;
4095 			tail->b_prev = NULL;
4096 			mac_srs->srs_first = tail->b_next;
4097 			if (mac_srs->srs_first == NULL)
4098 				mac_srs->srs_last = NULL;
4099 			mac_srs->srs_count--;
4100 			sz = msgdsize(tail);
4101 			mac_srs->srs_size -= sz;
4102 			saved_pkt_count++;
4103 			MAC_TX_UPDATE_BW_INFO(mac_srs, sz);
4104 
4105 			if (mac_srs->srs_bw->mac_bw_used <
4106 			    mac_srs->srs_bw->mac_bw_limit)
4107 				continue;
4108 
4109 			now = ddi_get_lbolt();
4110 			if (mac_srs->srs_bw->mac_bw_curr_time != now) {
4111 				mac_srs->srs_bw->mac_bw_curr_time = now;
4112 				mac_srs->srs_bw->mac_bw_used = sz;
4113 				continue;
4114 			}
4115 			mac_srs->srs_bw->mac_bw_state |= SRS_BW_ENFORCED;
4116 			break;
4117 		}
4118 
4119 		ASSERT((head == NULL && tail == NULL) ||
4120 		    (head != NULL && tail != NULL));
4121 		if (tail != NULL) {
4122 			tail->b_next = NULL;
4123 			mutex_exit(&mac_srs->srs_lock);
4124 
4125 			head = mac_tx_send(srs_tx->st_arg1, srs_tx->st_arg2,
4126 			    head, &stats);
4127 
4128 			mutex_enter(&mac_srs->srs_lock);
4129 			if (head != NULL) {
4130 				uint_t size_sent;
4131 
4132 				/* Device out of tx desc, set block */
4133 				if (head->b_next == NULL)
4134 					VERIFY(head == tail);
4135 				tail->b_next = mac_srs->srs_first;
4136 				mac_srs->srs_first = head;
4137 				mac_srs->srs_count +=
4138 				    (saved_pkt_count - stats.mts_opackets);
4139 				if (mac_srs->srs_last == NULL)
4140 					mac_srs->srs_last = tail;
4141 				size_sent = sz - stats.mts_obytes;
4142 				mac_srs->srs_size += size_sent;
4143 				mac_srs->srs_bw->mac_bw_sz += size_sent;
4144 				if (mac_srs->srs_bw->mac_bw_used > size_sent) {
4145 					mac_srs->srs_bw->mac_bw_used -=
4146 					    size_sent;
4147 				} else {
4148 					mac_srs->srs_bw->mac_bw_used = 0;
4149 				}
4150 				MAC_TX_SRS_BLOCK(mac_srs, head);
4151 			} else {
4152 				srs_tx->st_woken_up = B_FALSE;
4153 				SRS_TX_STATS_UPDATE(mac_srs, &stats);
4154 			}
4155 		}
4156 	} else if (tx_mode == SRS_TX_BW_FANOUT || tx_mode == SRS_TX_BW_AGGR) {
4157 		mblk_t *prev;
4158 		uint64_t hint;
4159 
4160 		/*
4161 		 * We are here because the timer fired and we
4162 		 * have some quota to tranmit.
4163 		 */
4164 		prev = NULL;
4165 		head = tail = mac_srs->srs_first;
4166 		while (mac_srs->srs_first != NULL) {
4167 			tail = mac_srs->srs_first;
4168 			mac_srs->srs_first = tail->b_next;
4169 			if (mac_srs->srs_first == NULL)
4170 				mac_srs->srs_last = NULL;
4171 			mac_srs->srs_count--;
4172 			sz = msgdsize(tail);
4173 			mac_srs->srs_size -= sz;
4174 			mac_srs->srs_bw->mac_bw_used += sz;
4175 			if (prev == NULL)
4176 				hint = (ulong_t)tail->b_prev;
4177 			if (hint != (ulong_t)tail->b_prev) {
4178 				prev->b_next = NULL;
4179 				mutex_exit(&mac_srs->srs_lock);
4180 				TX_SRS_TO_SOFT_RING(mac_srs, head, hint);
4181 				head = tail;
4182 				hint = (ulong_t)tail->b_prev;
4183 				mutex_enter(&mac_srs->srs_lock);
4184 			}
4185 
4186 			prev = tail;
4187 			tail->b_prev = NULL;
4188 			if (mac_srs->srs_bw->mac_bw_used <
4189 			    mac_srs->srs_bw->mac_bw_limit)
4190 				continue;
4191 
4192 			now = ddi_get_lbolt();
4193 			if (mac_srs->srs_bw->mac_bw_curr_time != now) {
4194 				mac_srs->srs_bw->mac_bw_curr_time = now;
4195 				mac_srs->srs_bw->mac_bw_used = 0;
4196 				continue;
4197 			}
4198 			mac_srs->srs_bw->mac_bw_state |= SRS_BW_ENFORCED;
4199 			break;
4200 		}
4201 		ASSERT((head == NULL && tail == NULL) ||
4202 		    (head != NULL && tail != NULL));
4203 		if (tail != NULL) {
4204 			tail->b_next = NULL;
4205 			mutex_exit(&mac_srs->srs_lock);
4206 			TX_SRS_TO_SOFT_RING(mac_srs, head, hint);
4207 			mutex_enter(&mac_srs->srs_lock);
4208 		}
4209 	}
4210 	/*
4211 	 * SRS_TX_FANOUT case not considered here because packets
4212 	 * won't be queued in the SRS for this case. Packets will
4213 	 * be sent directly to soft rings underneath and if there
4214 	 * is any queueing at all, it would be in Tx side soft
4215 	 * rings.
4216 	 */
4217 
4218 	/*
4219 	 * When srs_count becomes 0, reset SRS_TX_HIWAT and
4220 	 * SRS_TX_WAKEUP_CLIENT and wakeup registered clients.
4221 	 */
4222 	if (mac_srs->srs_count == 0 && (mac_srs->srs_state &
4223 	    (SRS_TX_HIWAT | SRS_TX_WAKEUP_CLIENT | SRS_ENQUEUED))) {
4224 		mac_client_impl_t *mcip = mac_srs->srs_mcip;
4225 		boolean_t wakeup_required = B_FALSE;
4226 
4227 		if (mac_srs->srs_state &
4228 		    (SRS_TX_HIWAT|SRS_TX_WAKEUP_CLIENT)) {
4229 			wakeup_required = B_TRUE;
4230 		}
4231 		mac_srs->srs_state &= ~(SRS_TX_HIWAT |
4232 		    SRS_TX_WAKEUP_CLIENT | SRS_ENQUEUED);
4233 		mutex_exit(&mac_srs->srs_lock);
4234 		if (wakeup_required) {
4235 			mac_tx_invoke_callbacks(mcip, (mac_tx_cookie_t)mac_srs);
4236 			/*
4237 			 * If the client is not the primary MAC client, then we
4238 			 * need to send the notification to the clients upper
4239 			 * MAC, i.e. mci_upper_mip.
4240 			 */
4241 			mac_tx_notify(mcip->mci_upper_mip != NULL ?
4242 			    mcip->mci_upper_mip : mcip->mci_mip);
4243 		}
4244 		mutex_enter(&mac_srs->srs_lock);
4245 	}
4246 	mac_srs->srs_state &= ~SRS_PROC;
4247 }
4248 
4249 /*
4250  * Given a packet, get the flow_entry that identifies the flow
4251  * to which that packet belongs. The flow_entry will contain
4252  * the transmit function to be used to send the packet. If the
4253  * function returns NULL, the packet should be sent using the
4254  * underlying NIC.
4255  */
4256 static flow_entry_t *
4257 mac_tx_classify(mac_impl_t *mip, mblk_t *mp)
4258 {
4259 	flow_entry_t		*flent = NULL;
4260 	mac_client_impl_t	*mcip;
4261 	int	err;
4262 
4263 	/*
4264 	 * Do classification on the packet.
4265 	 */
4266 	err = mac_flow_lookup(mip->mi_flow_tab, mp, FLOW_OUTBOUND, &flent);
4267 	if (err != 0)
4268 		return (NULL);
4269 
4270 	/*
4271 	 * This flent might just be an additional one on the MAC client,
4272 	 * i.e. for classification purposes (different fdesc), however
4273 	 * the resources, SRS et. al., are in the mci_flent, so if
4274 	 * this isn't the mci_flent, we need to get it.
4275 	 */
4276 	if ((mcip = flent->fe_mcip) != NULL && mcip->mci_flent != flent) {
4277 		FLOW_REFRELE(flent);
4278 		flent = mcip->mci_flent;
4279 		FLOW_TRY_REFHOLD(flent, err);
4280 		if (err != 0)
4281 			return (NULL);
4282 	}
4283 
4284 	return (flent);
4285 }
4286 
4287 /*
4288  * This macro is only meant to be used by mac_tx_send().
4289  */
4290 #define	CHECK_VID_AND_ADD_TAG(mp) {			\
4291 	if (vid_check) {				\
4292 		int err = 0;				\
4293 							\
4294 		MAC_VID_CHECK(src_mcip, (mp), err);	\
4295 		if (err != 0) {				\
4296 			freemsg((mp));			\
4297 			(mp) = next;			\
4298 			oerrors++;			\
4299 			continue;			\
4300 		}					\
4301 	}						\
4302 	if (add_tag) {					\
4303 		(mp) = mac_add_vlan_tag((mp), 0, vid);	\
4304 		if ((mp) == NULL) {			\
4305 			(mp) = next;			\
4306 			oerrors++;			\
4307 			continue;			\
4308 		}					\
4309 	}						\
4310 }
4311 
4312 mblk_t *
4313 mac_tx_send(mac_client_handle_t mch, mac_ring_handle_t ring, mblk_t *mp_chain,
4314     mac_tx_stats_t *stats)
4315 {
4316 	mac_client_impl_t *src_mcip = (mac_client_impl_t *)mch;
4317 	mac_impl_t *mip = src_mcip->mci_mip;
4318 	uint_t obytes = 0, opackets = 0, oerrors = 0;
4319 	mblk_t *mp = NULL, *next;
4320 	boolean_t vid_check, add_tag;
4321 	uint16_t vid = 0;
4322 
4323 	if (mip->mi_nclients > 1) {
4324 		vid_check = MAC_VID_CHECK_NEEDED(src_mcip);
4325 		add_tag = MAC_TAG_NEEDED(src_mcip);
4326 		if (add_tag)
4327 			vid = mac_client_vid(mch);
4328 	} else {
4329 		ASSERT(mip->mi_nclients == 1);
4330 		vid_check = add_tag = B_FALSE;
4331 	}
4332 
4333 	/*
4334 	 * Fastpath: if there's only one client, we simply send
4335 	 * the packet down to the underlying NIC.
4336 	 */
4337 	if (mip->mi_nactiveclients == 1) {
4338 		DTRACE_PROBE2(fastpath,
4339 		    mac_client_impl_t *, src_mcip, mblk_t *, mp_chain);
4340 
4341 		mp = mp_chain;
4342 		while (mp != NULL) {
4343 			next = mp->b_next;
4344 			mp->b_next = NULL;
4345 			opackets++;
4346 			obytes += (mp->b_cont == NULL ? MBLKL(mp) :
4347 			    msgdsize(mp));
4348 
4349 			CHECK_VID_AND_ADD_TAG(mp);
4350 			mp = mac_provider_tx(mip, ring, mp, src_mcip);
4351 
4352 			/*
4353 			 * If the driver is out of descriptors and does a
4354 			 * partial send it will return a chain of unsent
4355 			 * mblks. Adjust the accounting stats.
4356 			 */
4357 			if (mp != NULL) {
4358 				opackets--;
4359 				obytes -= msgdsize(mp);
4360 				mp->b_next = next;
4361 				break;
4362 			}
4363 			mp = next;
4364 		}
4365 		goto done;
4366 	}
4367 
4368 	/*
4369 	 * No fastpath, we either have more than one MAC client
4370 	 * defined on top of the same MAC, or one or more MAC
4371 	 * client promiscuous callbacks.
4372 	 */
4373 	DTRACE_PROBE3(slowpath, mac_client_impl_t *,
4374 	    src_mcip, int, mip->mi_nclients, mblk_t *, mp_chain);
4375 
4376 	mp = mp_chain;
4377 	while (mp != NULL) {
4378 		flow_entry_t *dst_flow_ent;
4379 		void *flow_cookie;
4380 		size_t	pkt_size;
4381 
4382 		next = mp->b_next;
4383 		mp->b_next = NULL;
4384 		opackets++;
4385 		pkt_size = (mp->b_cont == NULL ? MBLKL(mp) : msgdsize(mp));
4386 		obytes += pkt_size;
4387 		CHECK_VID_AND_ADD_TAG(mp);
4388 
4389 		/*
4390 		 * Find the destination.
4391 		 */
4392 		dst_flow_ent = mac_tx_classify(mip, mp);
4393 
4394 		if (dst_flow_ent != NULL) {
4395 			/*
4396 			 * Got a matching flow. It's either another
4397 			 * MAC client, or a broadcast/multicast flow.
4398 			 */
4399 			flow_cookie = mac_flow_get_client_cookie(dst_flow_ent);
4400 
4401 			if (flow_cookie != NULL) {
4402 				/*
4403 				 * The vnic_bcast_send function expects
4404 				 * to receive the sender MAC client
4405 				 * as value for arg2.
4406 				 */
4407 				mac_bcast_send(flow_cookie, src_mcip, mp,
4408 				    B_TRUE);
4409 			} else {
4410 				/*
4411 				 * loopback the packet to a local MAC
4412 				 * client. We force a context switch
4413 				 * if both source and destination MAC
4414 				 * clients are used by IP, i.e.
4415 				 * bypass is set.
4416 				 */
4417 				boolean_t do_switch;
4418 
4419 				mac_client_impl_t *dst_mcip =
4420 				    dst_flow_ent->fe_mcip;
4421 
4422 				/*
4423 				 * Check if there are promiscuous mode
4424 				 * callbacks defined. This check is
4425 				 * done here in the 'else' case and
4426 				 * not in other cases because this
4427 				 * path is for local loopback
4428 				 * communication which does not go
4429 				 * through MAC_TX(). For paths that go
4430 				 * through MAC_TX(), the promisc_list
4431 				 * check is done inside the MAC_TX()
4432 				 * macro.
4433 				 */
4434 				if (mip->mi_promisc_list != NULL) {
4435 					mac_promisc_dispatch(mip, mp, src_mcip,
4436 					    B_TRUE);
4437 				}
4438 
4439 				do_switch = ((src_mcip->mci_state_flags &
4440 				    dst_mcip->mci_state_flags &
4441 				    MCIS_CLIENT_POLL_CAPABLE) != 0);
4442 
4443 				mac_hw_emul(&mp, NULL, NULL, MAC_ALL_EMULS);
4444 				if (mp != NULL) {
4445 					(dst_flow_ent->fe_cb_fn)(
4446 					    dst_flow_ent->fe_cb_arg1,
4447 					    dst_flow_ent->fe_cb_arg2,
4448 					    mp, do_switch);
4449 				}
4450 
4451 			}
4452 			FLOW_REFRELE(dst_flow_ent);
4453 		} else {
4454 			/*
4455 			 * Unknown destination, send via the underlying
4456 			 * NIC.
4457 			 */
4458 			mp = mac_provider_tx(mip, ring, mp, src_mcip);
4459 			if (mp != NULL) {
4460 				/*
4461 				 * Adjust for the last packet that
4462 				 * could not be transmitted
4463 				 */
4464 				opackets--;
4465 				obytes -= pkt_size;
4466 				mp->b_next = next;
4467 				break;
4468 			}
4469 		}
4470 		mp = next;
4471 	}
4472 
4473 done:
4474 	stats->mts_obytes = obytes;
4475 	stats->mts_opackets = opackets;
4476 	stats->mts_oerrors = oerrors;
4477 	return (mp);
4478 }
4479 
4480 /*
4481  * mac_tx_srs_ring_present
4482  *
4483  * Returns whether the specified ring is part of the specified SRS.
4484  */
4485 boolean_t
4486 mac_tx_srs_ring_present(mac_soft_ring_set_t *srs, mac_ring_t *tx_ring)
4487 {
4488 	int i;
4489 	mac_soft_ring_t *soft_ring;
4490 
4491 	if (srs->srs_tx.st_arg2 == tx_ring)
4492 		return (B_TRUE);
4493 
4494 	for (i = 0; i < srs->srs_tx_ring_count; i++) {
4495 		soft_ring =  srs->srs_tx_soft_rings[i];
4496 		if (soft_ring->s_ring_tx_arg2 == tx_ring)
4497 			return (B_TRUE);
4498 	}
4499 
4500 	return (B_FALSE);
4501 }
4502 
4503 /*
4504  * mac_tx_srs_get_soft_ring
4505  *
4506  * Returns the TX soft ring associated with the given ring, if present.
4507  */
4508 mac_soft_ring_t *
4509 mac_tx_srs_get_soft_ring(mac_soft_ring_set_t *srs, mac_ring_t *tx_ring)
4510 {
4511 	int		i;
4512 	mac_soft_ring_t	*soft_ring;
4513 
4514 	if (srs->srs_tx.st_arg2 == tx_ring)
4515 		return (NULL);
4516 
4517 	for (i = 0; i < srs->srs_tx_ring_count; i++) {
4518 		soft_ring =  srs->srs_tx_soft_rings[i];
4519 		if (soft_ring->s_ring_tx_arg2 == tx_ring)
4520 			return (soft_ring);
4521 	}
4522 
4523 	return (NULL);
4524 }
4525 
4526 /*
4527  * mac_tx_srs_wakeup
4528  *
4529  * Called when Tx desc become available. Wakeup the appropriate worker
4530  * thread after resetting the SRS_TX_BLOCKED/S_RING_BLOCK bit in the
4531  * state field.
4532  */
4533 void
4534 mac_tx_srs_wakeup(mac_soft_ring_set_t *mac_srs, mac_ring_handle_t ring)
4535 {
4536 	int i;
4537 	mac_soft_ring_t *sringp;
4538 	mac_srs_tx_t *srs_tx = &mac_srs->srs_tx;
4539 
4540 	mutex_enter(&mac_srs->srs_lock);
4541 	/*
4542 	 * srs_tx_ring_count == 0 is the single ring mode case. In
4543 	 * this mode, there will not be Tx soft rings associated
4544 	 * with the SRS.
4545 	 */
4546 	if (!MAC_TX_SOFT_RINGS(mac_srs)) {
4547 		if (srs_tx->st_arg2 == ring &&
4548 		    mac_srs->srs_state & SRS_TX_BLOCKED) {
4549 			mac_srs->srs_state &= ~SRS_TX_BLOCKED;
4550 			srs_tx->st_stat.mts_unblockcnt++;
4551 			cv_signal(&mac_srs->srs_async);
4552 		}
4553 		/*
4554 		 * A wakeup can come before tx_srs_drain() could
4555 		 * grab srs lock and set SRS_TX_BLOCKED. So
4556 		 * always set woken_up flag when we come here.
4557 		 */
4558 		srs_tx->st_woken_up = B_TRUE;
4559 		mutex_exit(&mac_srs->srs_lock);
4560 		return;
4561 	}
4562 
4563 	/*
4564 	 * If you are here, it is for FANOUT, BW_FANOUT,
4565 	 * AGGR_MODE or AGGR_BW_MODE case
4566 	 */
4567 	for (i = 0; i < mac_srs->srs_tx_ring_count; i++) {
4568 		sringp = mac_srs->srs_tx_soft_rings[i];
4569 		mutex_enter(&sringp->s_ring_lock);
4570 		if (sringp->s_ring_tx_arg2 == ring) {
4571 			if (sringp->s_ring_state & S_RING_BLOCK) {
4572 				sringp->s_ring_state &= ~S_RING_BLOCK;
4573 				sringp->s_st_stat.mts_unblockcnt++;
4574 				cv_signal(&sringp->s_ring_async);
4575 			}
4576 			sringp->s_ring_tx_woken_up = B_TRUE;
4577 		}
4578 		mutex_exit(&sringp->s_ring_lock);
4579 	}
4580 	mutex_exit(&mac_srs->srs_lock);
4581 }
4582 
4583 /*
4584  * Once the driver is done draining, send a MAC_NOTE_TX notification to unleash
4585  * the blocked clients again.
4586  */
4587 void
4588 mac_tx_notify(mac_impl_t *mip)
4589 {
4590 	i_mac_notify(mip, MAC_NOTE_TX);
4591 }
4592 
4593 /*
4594  * RX SOFTRING RELATED FUNCTIONS
4595  *
4596  * These functions really belong in mac_soft_ring.c and here for
4597  * a short period.
4598  */
4599 
4600 #define	SOFT_RING_ENQUEUE_CHAIN(ringp, mp, tail, cnt, sz) {		\
4601 	/*								\
4602 	 * Enqueue our mblk chain.					\
4603 	 */								\
4604 	ASSERT(MUTEX_HELD(&(ringp)->s_ring_lock));			\
4605 									\
4606 	if ((ringp)->s_ring_last != NULL)				\
4607 		(ringp)->s_ring_last->b_next = (mp);			\
4608 	else								\
4609 		(ringp)->s_ring_first = (mp);				\
4610 	(ringp)->s_ring_last = (tail);					\
4611 	(ringp)->s_ring_count += (cnt);					\
4612 	ASSERT((ringp)->s_ring_count > 0);				\
4613 	if ((ringp)->s_ring_type & ST_RING_BW_CTL) {			\
4614 		(ringp)->s_ring_size += sz;				\
4615 	}								\
4616 }
4617 
4618 /*
4619  * Default entry point to deliver a packet chain to a MAC client.
4620  * If the MAC client has flows, do the classification with these
4621  * flows as well.
4622  */
4623 /* ARGSUSED */
4624 void
4625 mac_rx_deliver(void *arg1, mac_resource_handle_t mrh, mblk_t *mp_chain,
4626     mac_header_info_t *arg3)
4627 {
4628 	mac_client_impl_t *mcip = arg1;
4629 
4630 	if (mcip->mci_nvids == 1 &&
4631 	    !(mcip->mci_state_flags & MCIS_STRIP_DISABLE)) {
4632 		/*
4633 		 * If the client has exactly one VID associated with it
4634 		 * and striping of VLAN header is not disabled,
4635 		 * remove the VLAN tag from the packet before
4636 		 * passing it on to the client's receive callback.
4637 		 * Note that this needs to be done after we dispatch
4638 		 * the packet to the promiscuous listeners of the
4639 		 * client, since they expect to see the whole
4640 		 * frame including the VLAN headers.
4641 		 *
4642 		 * The MCIS_STRIP_DISABLE is only issued when sun4v
4643 		 * vsw is in play.
4644 		 */
4645 		mp_chain = mac_strip_vlan_tag_chain(mp_chain);
4646 	}
4647 
4648 	mcip->mci_rx_fn(mcip->mci_rx_arg, mrh, mp_chain, B_FALSE);
4649 }
4650 
4651 /*
4652  * Process a chain for a given soft ring. If the number of packets
4653  * queued in the SRS and its associated soft rings (including this
4654  * one) is very small (tracked by srs_poll_pkt_cnt) then allow the
4655  * entering thread (interrupt or poll thread) to process the chain
4656  * inline. This is meant to reduce latency under low load.
4657  *
4658  * The proc and arg for each mblk is already stored in the mblk in
4659  * appropriate places.
4660  */
4661 /* ARGSUSED */
4662 void
4663 mac_rx_soft_ring_process(mac_client_impl_t *mcip, mac_soft_ring_t *ringp,
4664     mblk_t *mp_chain, mblk_t *tail, int cnt, size_t sz)
4665 {
4666 	mac_direct_rx_t		proc;
4667 	void			*arg1;
4668 	mac_resource_handle_t	arg2;
4669 	mac_soft_ring_set_t	*mac_srs = ringp->s_ring_set;
4670 
4671 	ASSERT(ringp != NULL);
4672 	ASSERT(mp_chain != NULL);
4673 	ASSERT(tail != NULL);
4674 	ASSERT(MUTEX_NOT_HELD(&ringp->s_ring_lock));
4675 
4676 	mutex_enter(&ringp->s_ring_lock);
4677 	ringp->s_ring_total_inpkt += cnt;
4678 	ringp->s_ring_total_rbytes += sz;
4679 	if ((mac_srs->srs_rx.sr_poll_pkt_cnt <= 1) &&
4680 	    !(ringp->s_ring_type & ST_RING_WORKER_ONLY)) {
4681 		/* If on processor or blanking on, then enqueue and return */
4682 		if (ringp->s_ring_state & S_RING_BLANK ||
4683 		    ringp->s_ring_state & S_RING_PROC) {
4684 			SOFT_RING_ENQUEUE_CHAIN(ringp, mp_chain, tail, cnt, sz);
4685 			mutex_exit(&ringp->s_ring_lock);
4686 			return;
4687 		}
4688 		proc = ringp->s_ring_rx_func;
4689 		arg1 = ringp->s_ring_rx_arg1;
4690 		arg2 = ringp->s_ring_rx_arg2;
4691 		/*
4692 		 * See if anything is already queued. If we are the
4693 		 * first packet, do inline processing else queue the
4694 		 * packet and do the drain.
4695 		 */
4696 		if (ringp->s_ring_first == NULL) {
4697 			/*
4698 			 * Fast-path, ok to process and nothing queued.
4699 			 */
4700 			ringp->s_ring_run = curthread;
4701 			ringp->s_ring_state |= (S_RING_PROC);
4702 
4703 			mutex_exit(&ringp->s_ring_lock);
4704 
4705 			/*
4706 			 * We are the chain of 1 packet so
4707 			 * go through this fast path.
4708 			 */
4709 			ASSERT(mp_chain->b_next == NULL);
4710 
4711 			(*proc)(arg1, arg2, mp_chain, NULL);
4712 
4713 			ASSERT(MUTEX_NOT_HELD(&ringp->s_ring_lock));
4714 			/*
4715 			 * If we have an SRS performing bandwidth
4716 			 * control then we need to decrement the size
4717 			 * and count so the SRS has an accurate count
4718 			 * of the data queued between the SRS and its
4719 			 * soft rings. We decrement the counters only
4720 			 * when the packet is processed by both the
4721 			 * SRS and the soft ring.
4722 			 */
4723 			mutex_enter(&mac_srs->srs_lock);
4724 			MAC_UPDATE_SRS_COUNT_LOCKED(mac_srs, cnt);
4725 			MAC_UPDATE_SRS_SIZE_LOCKED(mac_srs, sz);
4726 			mutex_exit(&mac_srs->srs_lock);
4727 
4728 			mutex_enter(&ringp->s_ring_lock);
4729 			ringp->s_ring_run = NULL;
4730 			ringp->s_ring_state &= ~S_RING_PROC;
4731 			if (ringp->s_ring_state & S_RING_CLIENT_WAIT)
4732 				cv_signal(&ringp->s_ring_client_cv);
4733 
4734 			if ((ringp->s_ring_first == NULL) ||
4735 			    (ringp->s_ring_state & S_RING_BLANK)) {
4736 				/*
4737 				 * We processed a single packet inline
4738 				 * and nothing new has arrived or our
4739 				 * receiver doesn't want to receive
4740 				 * any packets. We are done.
4741 				 */
4742 				mutex_exit(&ringp->s_ring_lock);
4743 				return;
4744 			}
4745 		} else {
4746 			SOFT_RING_ENQUEUE_CHAIN(ringp,
4747 			    mp_chain, tail, cnt, sz);
4748 		}
4749 
4750 		/*
4751 		 * We are here because either we couldn't do inline
4752 		 * processing (because something was already
4753 		 * queued), or we had a chain of more than one
4754 		 * packet, or something else arrived after we were
4755 		 * done with inline processing.
4756 		 */
4757 		ASSERT(MUTEX_HELD(&ringp->s_ring_lock));
4758 		ASSERT(ringp->s_ring_first != NULL);
4759 
4760 		ringp->s_ring_drain_func(ringp);
4761 		mutex_exit(&ringp->s_ring_lock);
4762 		return;
4763 	} else {
4764 		/* ST_RING_WORKER_ONLY case */
4765 		SOFT_RING_ENQUEUE_CHAIN(ringp, mp_chain, tail, cnt, sz);
4766 		mac_soft_ring_worker_wakeup(ringp);
4767 		mutex_exit(&ringp->s_ring_lock);
4768 	}
4769 }
4770 
4771 /*
4772  * TX SOFTRING RELATED FUNCTIONS
4773  *
4774  * These functions really belong in mac_soft_ring.c and here for
4775  * a short period.
4776  */
4777 
4778 #define	TX_SOFT_RING_ENQUEUE_CHAIN(ringp, mp, tail, cnt, sz) {		\
4779 	ASSERT(MUTEX_HELD(&ringp->s_ring_lock));			\
4780 	ringp->s_ring_state |= S_RING_ENQUEUED;				\
4781 	SOFT_RING_ENQUEUE_CHAIN(ringp, mp_chain, tail, cnt, sz);	\
4782 }
4783 
4784 /*
4785  * mac_tx_sring_queued
4786  *
4787  * When we are out of transmit descriptors and we already have a
4788  * queue that exceeds hiwat (or the client called us with
4789  * MAC_TX_NO_ENQUEUE or MAC_DROP_ON_NO_DESC flag), return the
4790  * soft ring pointer as the opaque cookie for the client enable
4791  * flow control.
4792  */
4793 static mac_tx_cookie_t
4794 mac_tx_sring_enqueue(mac_soft_ring_t *ringp, mblk_t *mp_chain, uint16_t flag,
4795     mblk_t **ret_mp)
4796 {
4797 	int cnt;
4798 	size_t sz;
4799 	mblk_t *tail;
4800 	mac_soft_ring_set_t *mac_srs = ringp->s_ring_set;
4801 	mac_tx_cookie_t cookie = 0;
4802 	boolean_t wakeup_worker = B_TRUE;
4803 
4804 	ASSERT(MUTEX_HELD(&ringp->s_ring_lock));
4805 	MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
4806 	if (flag & MAC_DROP_ON_NO_DESC) {
4807 		mac_drop_chain(mp_chain, "Tx softring no desc");
4808 		/* increment freed stats */
4809 		ringp->s_ring_drops += cnt;
4810 		cookie = (mac_tx_cookie_t)ringp;
4811 	} else {
4812 		if (ringp->s_ring_first != NULL)
4813 			wakeup_worker = B_FALSE;
4814 
4815 		if (flag & MAC_TX_NO_ENQUEUE) {
4816 			/*
4817 			 * If QUEUED is not set, queue the packet
4818 			 * and let mac_tx_soft_ring_drain() set
4819 			 * the TX_BLOCKED bit for the reasons
4820 			 * explained above. Otherwise, return the
4821 			 * mblks.
4822 			 */
4823 			if (wakeup_worker) {
4824 				TX_SOFT_RING_ENQUEUE_CHAIN(ringp,
4825 				    mp_chain, tail, cnt, sz);
4826 			} else {
4827 				ringp->s_ring_state |= S_RING_WAKEUP_CLIENT;
4828 				cookie = (mac_tx_cookie_t)ringp;
4829 				*ret_mp = mp_chain;
4830 			}
4831 		} else {
4832 			boolean_t enqueue = B_TRUE;
4833 
4834 			if (ringp->s_ring_count > ringp->s_ring_tx_hiwat) {
4835 				/*
4836 				 * flow-controlled. Store ringp in cookie
4837 				 * so that it can be returned as
4838 				 * mac_tx_cookie_t to client
4839 				 */
4840 				ringp->s_ring_state |= S_RING_TX_HIWAT;
4841 				cookie = (mac_tx_cookie_t)ringp;
4842 				ringp->s_ring_hiwat_cnt++;
4843 				if (ringp->s_ring_count >
4844 				    ringp->s_ring_tx_max_q_cnt) {
4845 					/* increment freed stats */
4846 					ringp->s_ring_drops += cnt;
4847 					/*
4848 					 * b_prev may be set to the fanout hint
4849 					 * hence can't use freemsg directly
4850 					 */
4851 					mac_drop_chain(mp_chain,
4852 					    "Tx softring max queue");
4853 					DTRACE_PROBE1(tx_queued_hiwat,
4854 					    mac_soft_ring_t *, ringp);
4855 					enqueue = B_FALSE;
4856 				}
4857 			}
4858 			if (enqueue) {
4859 				TX_SOFT_RING_ENQUEUE_CHAIN(ringp, mp_chain,
4860 				    tail, cnt, sz);
4861 			}
4862 		}
4863 		if (wakeup_worker)
4864 			cv_signal(&ringp->s_ring_async);
4865 	}
4866 	return (cookie);
4867 }
4868 
4869 
4870 /*
4871  * mac_tx_soft_ring_process
4872  *
4873  * This routine is called when fanning out outgoing traffic among
4874  * multipe Tx rings.
4875  * Note that a soft ring is associated with a h/w Tx ring.
4876  */
4877 mac_tx_cookie_t
4878 mac_tx_soft_ring_process(mac_soft_ring_t *ringp, mblk_t *mp_chain,
4879     uint16_t flag, mblk_t **ret_mp)
4880 {
4881 	mac_soft_ring_set_t *mac_srs = ringp->s_ring_set;
4882 	int	cnt;
4883 	size_t	sz;
4884 	mblk_t	*tail;
4885 	mac_tx_cookie_t cookie = 0;
4886 
4887 	ASSERT(ringp != NULL);
4888 	ASSERT(mp_chain != NULL);
4889 	ASSERT(MUTEX_NOT_HELD(&ringp->s_ring_lock));
4890 	/*
4891 	 * The following modes can come here: SRS_TX_BW_FANOUT,
4892 	 * SRS_TX_FANOUT, SRS_TX_AGGR, SRS_TX_BW_AGGR.
4893 	 */
4894 	ASSERT(MAC_TX_SOFT_RINGS(mac_srs));
4895 	ASSERT(mac_srs->srs_tx.st_mode == SRS_TX_FANOUT ||
4896 	    mac_srs->srs_tx.st_mode == SRS_TX_BW_FANOUT ||
4897 	    mac_srs->srs_tx.st_mode == SRS_TX_AGGR ||
4898 	    mac_srs->srs_tx.st_mode == SRS_TX_BW_AGGR);
4899 
4900 	if (ringp->s_ring_type & ST_RING_WORKER_ONLY) {
4901 		/* Serialization mode */
4902 
4903 		mutex_enter(&ringp->s_ring_lock);
4904 		if (ringp->s_ring_count > ringp->s_ring_tx_hiwat) {
4905 			cookie = mac_tx_sring_enqueue(ringp, mp_chain,
4906 			    flag, ret_mp);
4907 			mutex_exit(&ringp->s_ring_lock);
4908 			return (cookie);
4909 		}
4910 		MAC_COUNT_CHAIN(mac_srs, mp_chain, tail, cnt, sz);
4911 		TX_SOFT_RING_ENQUEUE_CHAIN(ringp, mp_chain, tail, cnt, sz);
4912 		if (ringp->s_ring_state & (S_RING_BLOCK | S_RING_PROC)) {
4913 			/*
4914 			 * If ring is blocked due to lack of Tx
4915 			 * descs, just return. Worker thread
4916 			 * will get scheduled when Tx desc's
4917 			 * become available.
4918 			 */
4919 			mutex_exit(&ringp->s_ring_lock);
4920 			return (cookie);
4921 		}
4922 		mac_soft_ring_worker_wakeup(ringp);
4923 		mutex_exit(&ringp->s_ring_lock);
4924 		return (cookie);
4925 	} else {
4926 		/* Default fanout mode */
4927 		/*
4928 		 * S_RING_BLOCKED is set when underlying NIC runs
4929 		 * out of Tx descs and messages start getting
4930 		 * queued. It won't get reset until
4931 		 * tx_srs_drain() completely drains out the
4932 		 * messages.
4933 		 */
4934 		mac_tx_stats_t		stats;
4935 
4936 		if (ringp->s_ring_state & S_RING_ENQUEUED) {
4937 			/* Tx descs/resources not available */
4938 			mutex_enter(&ringp->s_ring_lock);
4939 			if (ringp->s_ring_state & S_RING_ENQUEUED) {
4940 				cookie = mac_tx_sring_enqueue(ringp, mp_chain,
4941 				    flag, ret_mp);
4942 				mutex_exit(&ringp->s_ring_lock);
4943 				return (cookie);
4944 			}
4945 			/*
4946 			 * While we were computing mblk count, the
4947 			 * flow control condition got relieved.
4948 			 * Continue with the transmission.
4949 			 */
4950 			mutex_exit(&ringp->s_ring_lock);
4951 		}
4952 
4953 		mp_chain = mac_tx_send(ringp->s_ring_tx_arg1,
4954 		    ringp->s_ring_tx_arg2, mp_chain, &stats);
4955 
4956 		/*
4957 		 * Multiple threads could be here sending packets.
4958 		 * Under such conditions, it is not possible to
4959 		 * automically set S_RING_BLOCKED bit to indicate
4960 		 * out of tx desc condition. To atomically set
4961 		 * this, we queue the returned packet and do
4962 		 * the setting of S_RING_BLOCKED in
4963 		 * mac_tx_soft_ring_drain().
4964 		 */
4965 		if (mp_chain != NULL) {
4966 			mutex_enter(&ringp->s_ring_lock);
4967 			cookie =
4968 			    mac_tx_sring_enqueue(ringp, mp_chain, flag, ret_mp);
4969 			mutex_exit(&ringp->s_ring_lock);
4970 			return (cookie);
4971 		}
4972 		SRS_TX_STATS_UPDATE(mac_srs, &stats);
4973 		SOFTRING_TX_STATS_UPDATE(ringp, &stats);
4974 
4975 		return (0);
4976 	}
4977 }
4978