xref: /titanic_41/usr/src/uts/common/io/mac/mac.c (revision 8f588c8376a0fa02470fc4554ec83442b305020f)
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 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * MAC Services Module
29  *
30  * The GLDv3 framework locking -  The MAC layer
31  * --------------------------------------------
32  *
33  * The MAC layer is central to the GLD framework and can provide the locking
34  * framework needed for itself and for the use of MAC clients. MAC end points
35  * are fairly disjoint and don't share a lot of state. So a coarse grained
36  * multi-threading scheme is to single thread all create/modify/delete or set
37  * type of control operations on a per mac end point while allowing data threads
38  * concurrently.
39  *
40  * Control operations (set) that modify a mac end point are always serialized on
41  * a per mac end point basis, We have at most 1 such thread per mac end point
42  * at a time.
43  *
44  * All other operations that are not serialized are essentially multi-threaded.
45  * For example a control operation (get) like getting statistics which may not
46  * care about reading values atomically or data threads sending or receiving
47  * data. Mostly these type of operations don't modify the control state. Any
48  * state these operations care about are protected using traditional locks.
49  *
50  * The perimeter only serializes serial operations. It does not imply there
51  * aren't any other concurrent operations. However a serialized operation may
52  * sometimes need to make sure it is the only thread. In this case it needs
53  * to use reference counting mechanisms to cv_wait until any current data
54  * threads are done.
55  *
56  * The mac layer itself does not hold any locks across a call to another layer.
57  * The perimeter is however held across a down call to the driver to make the
58  * whole control operation atomic with respect to other control operations.
59  * Also the data path and get type control operations may proceed concurrently.
60  * These operations synchronize with the single serial operation on a given mac
61  * end point using regular locks. The perimeter ensures that conflicting
62  * operations like say a mac_multicast_add and a mac_multicast_remove on the
63  * same mac end point don't interfere with each other and also ensures that the
64  * changes in the mac layer and the call to the underlying driver to say add a
65  * multicast address are done atomically without interference from a thread
66  * trying to delete the same address.
67  *
68  * For example, consider
69  * mac_multicst_add()
70  * {
71  *	mac_perimeter_enter();	serialize all control operations
72  *
73  *	grab list lock		protect against access by data threads
74  *	add to list
75  *	drop list lock
76  *
77  *	call driver's mi_multicst
78  *
79  *	mac_perimeter_exit();
80  * }
81  *
82  * To lessen the number of serialization locks and simplify the lock hierarchy,
83  * we serialize all the control operations on a per mac end point by using a
84  * single serialization lock called the perimeter. We allow recursive entry into
85  * the perimeter to facilitate use of this mechanism by both the mac client and
86  * the MAC layer itself.
87  *
88  * MAC client means an entity that does an operation on a mac handle
89  * obtained from a mac_open/mac_client_open. Similarly MAC driver means
90  * an entity that does an operation on a mac handle obtained from a
91  * mac_register. An entity could be both client and driver but on different
92  * handles eg. aggr. and should only make the corresponding mac interface calls
93  * i.e. mac driver interface or mac client interface as appropriate for that
94  * mac handle.
95  *
96  * General rules.
97  * -------------
98  *
99  * R1. The lock order of upcall threads is natually opposite to downcall
100  * threads. Hence upcalls must not hold any locks across layers for fear of
101  * recursive lock enter and lock order violation. This applies to all layers.
102  *
103  * R2. The perimeter is just another lock. Since it is held in the down
104  * direction, acquiring the perimeter in an upcall is prohibited as it would
105  * cause a deadlock. This applies to all layers.
106  *
107  * Note that upcalls that need to grab the mac perimeter (for example
108  * mac_notify upcalls) can still achieve that by posting the request to a
109  * thread, which can then grab all the required perimeters and locks in the
110  * right global order. Note that in the above example the mac layer iself
111  * won't grab the mac perimeter in the mac_notify upcall, instead the upcall
112  * to the client must do that. Please see the aggr code for an example.
113  *
114  * MAC client rules
115  * ----------------
116  *
117  * R3. A MAC client may use the MAC provided perimeter facility to serialize
118  * control operations on a per mac end point. It does this by by acquring
119  * and holding the perimeter across a sequence of calls to the mac layer.
120  * This ensures atomicity across the entire block of mac calls. In this
121  * model the MAC client must not hold any client locks across the calls to
122  * the mac layer. This model is the preferred solution.
123  *
124  * R4. However if a MAC client has a lot of global state across all mac end
125  * points the per mac end point serialization may not be sufficient. In this
126  * case the client may choose to use global locks or use its own serialization.
127  * To avoid deadlocks, these client layer locks held across the mac calls
128  * in the control path must never be acquired by the data path for the reason
129  * mentioned below.
130  *
131  * (Assume that a control operation that holds a client lock blocks in the
132  * mac layer waiting for upcall reference counts to drop to zero. If an upcall
133  * data thread that holds this reference count, tries to acquire the same
134  * client lock subsequently it will deadlock).
135  *
136  * A MAC client may follow either the R3 model or the R4 model, but can't
137  * mix both. In the former, the hierarchy is Perim -> client locks, but in
138  * the latter it is client locks -> Perim.
139  *
140  * R5. MAC clients must make MAC calls (excluding data calls) in a cv_wait'able
141  * context since they may block while trying to acquire the perimeter.
142  * In addition some calls may block waiting for upcall refcnts to come down to
143  * zero.
144  *
145  * R6. MAC clients must make sure that they are single threaded and all threads
146  * from the top (in particular data threads) have finished before calling
147  * mac_client_close. The MAC framework does not track the number of client
148  * threads using the mac client handle. Also mac clients must make sure
149  * they have undone all the control operations before calling mac_client_close.
150  * For example mac_unicast_remove/mac_multicast_remove to undo the corresponding
151  * mac_unicast_add/mac_multicast_add.
152  *
153  * MAC framework rules
154  * -------------------
155  *
156  * R7. The mac layer itself must not hold any mac layer locks (except the mac
157  * perimeter) across a call to any other layer from the mac layer. The call to
158  * any other layer could be via mi_* entry points, classifier entry points into
159  * the driver or via upcall pointers into layers above. The mac perimeter may
160  * be acquired or held only in the down direction, for e.g. when calling into
161  * a mi_* driver enty point to provide atomicity of the operation.
162  *
163  * R8. Since it is not guaranteed (see R14) that drivers won't hold locks across
164  * mac driver interfaces, the MAC layer must provide a cut out for control
165  * interfaces like upcall notifications and start them in a separate thread.
166  *
167  * R9. Note that locking order also implies a plumbing order. For example
168  * VNICs are allowed to be created over aggrs, but not vice-versa. An attempt
169  * to plumb in any other order must be failed at mac_open time, otherwise it
170  * could lead to deadlocks due to inverse locking order.
171  *
172  * R10. MAC driver interfaces must not block since the driver could call them
173  * in interrupt context.
174  *
175  * R11. Walkers must preferably not hold any locks while calling walker
176  * callbacks. Instead these can operate on reference counts. In simple
177  * callbacks it may be ok to hold a lock and call the callbacks, but this is
178  * harder to maintain in the general case of arbitrary callbacks.
179  *
180  * R12. The MAC layer must protect upcall notification callbacks using reference
181  * counts rather than holding locks across the callbacks.
182  *
183  * R13. Given the variety of drivers, it is preferable if the MAC layer can make
184  * sure that any pointers (such as mac ring pointers) it passes to the driver
185  * remain valid until mac unregister time. Currently the mac layer achieves
186  * this by using generation numbers for rings and freeing the mac rings only
187  * at unregister time.  The MAC layer must provide a layer of indirection and
188  * must not expose underlying driver rings or driver data structures/pointers
189  * directly to MAC clients.
190  *
191  * MAC driver rules
192  * ----------------
193  *
194  * R14. It would be preferable if MAC drivers don't hold any locks across any
195  * mac call. However at a minimum they must not hold any locks across data
196  * upcalls. They must also make sure that all references to mac data structures
197  * are cleaned up and that it is single threaded at mac_unregister time.
198  *
199  * R15. MAC driver interfaces don't block and so the action may be done
200  * asynchronously in a separate thread as for example handling notifications.
201  * The driver must not assume that the action is complete when the call
202  * returns.
203  *
204  * R16. Drivers must maintain a generation number per Rx ring, and pass it
205  * back to mac_rx_ring(); They are expected to increment the generation
206  * number whenever the ring's stop routine is invoked.
207  * See comments in mac_rx_ring();
208  *
209  * R17 Similarly mi_stop is another synchronization point and the driver must
210  * ensure that all upcalls are done and there won't be any future upcall
211  * before returning from mi_stop.
212  *
213  * R18. The driver may assume that all set/modify control operations via
214  * the mi_* entry points are single threaded on a per mac end point.
215  *
216  * Lock and Perimeter hierarchy scenarios
217  * ---------------------------------------
218  *
219  * i_mac_impl_lock -> mi_rw_lock -> srs_lock -> s_ring_lock[i_mac_tx_srs_notify]
220  *
221  * ft_lock -> fe_lock [mac_flow_lookup]
222  *
223  * mi_rw_lock -> fe_lock [mac_bcast_send]
224  *
225  * srs_lock -> mac_bw_lock [mac_rx_srs_drain_bw]
226  *
227  * cpu_lock -> mac_srs_g_lock -> srs_lock -> s_ring_lock [mac_walk_srs_and_bind]
228  *
229  * i_dls_devnet_lock -> mac layer locks [dls_devnet_rename]
230  *
231  * Perimeters are ordered P1 -> P2 -> P3 from top to bottom in order of mac
232  * client to driver. In the case of clients that explictly use the mac provided
233  * perimeter mechanism for its serialization, the hierarchy is
234  * Perimeter -> mac layer locks, since the client never holds any locks across
235  * the mac calls. In the case of clients that use its own locks the hierarchy
236  * is Client locks -> Mac Perim -> Mac layer locks. The client never explicitly
237  * calls mac_perim_enter/exit in this case.
238  *
239  * Subflow creation rules
240  * ---------------------------
241  * o In case of a user specified cpulist present on underlying link and flows,
242  * the flows cpulist must be a subset of the underlying link.
243  * o In case of a user specified fanout mode present on link and flow, the
244  * subflow fanout count has to be less than or equal to that of the
245  * underlying link. The cpu-bindings for the subflows will be a subset of
246  * the underlying link.
247  * o In case if no cpulist specified on both underlying link and flow, the
248  * underlying link relies on a  MAC tunable to provide out of box fanout.
249  * The subflow will have no cpulist (the subflow will be unbound)
250  * o In case if no cpulist is specified on the underlying link, a subflow can
251  * carry  either a user-specified cpulist or fanout count. The cpu-bindings
252  * for the subflow will not adhere to restriction that they need to be subset
253  * of the underlying link.
254  * o In case where the underlying link is carrying either a user specified
255  * cpulist or fanout mode and for a unspecified subflow, the subflow will be
256  * created unbound.
257  * o While creating unbound subflows, bandwidth mode changes attempt to
258  * figure a right fanout count. In such cases the fanout count will override
259  * the unbound cpu-binding behavior.
260  * o In addition to this, while cycling between flow and link properties, we
261  * impose a restriction that if a link property has a subflow with
262  * user-specified attributes, we will not allow changing the link property.
263  * The administrator needs to reset all the user specified properties for the
264  * subflows before attempting a link property change.
265  * Some of the above rules can be overridden by specifying additional command
266  * line options while creating or modifying link or subflow properties.
267  */
268 
269 #include <sys/types.h>
270 #include <sys/conf.h>
271 #include <sys/id_space.h>
272 #include <sys/esunddi.h>
273 #include <sys/stat.h>
274 #include <sys/mkdev.h>
275 #include <sys/stream.h>
276 #include <sys/strsun.h>
277 #include <sys/strsubr.h>
278 #include <sys/dlpi.h>
279 #include <sys/modhash.h>
280 #include <sys/mac_provider.h>
281 #include <sys/mac_client_impl.h>
282 #include <sys/mac_soft_ring.h>
283 #include <sys/mac_impl.h>
284 #include <sys/mac.h>
285 #include <sys/dls.h>
286 #include <sys/dld.h>
287 #include <sys/modctl.h>
288 #include <sys/fs/dv_node.h>
289 #include <sys/thread.h>
290 #include <sys/proc.h>
291 #include <sys/callb.h>
292 #include <sys/cpuvar.h>
293 #include <sys/atomic.h>
294 #include <sys/bitmap.h>
295 #include <sys/sdt.h>
296 #include <sys/mac_flow.h>
297 #include <sys/ddi_intr_impl.h>
298 #include <sys/disp.h>
299 #include <sys/sdt.h>
300 #include <sys/vnic.h>
301 #include <sys/vnic_impl.h>
302 #include <sys/vlan.h>
303 #include <inet/ip.h>
304 #include <inet/ip6.h>
305 #include <sys/exacct.h>
306 #include <sys/exacct_impl.h>
307 #include <inet/nd.h>
308 #include <sys/ethernet.h>
309 
310 #define	IMPL_HASHSZ	67	/* prime */
311 
312 kmem_cache_t	*i_mac_impl_cachep;
313 mod_hash_t		*i_mac_impl_hash;
314 krwlock_t		i_mac_impl_lock;
315 uint_t			i_mac_impl_count;
316 static kmem_cache_t	*mac_ring_cache;
317 static id_space_t	*minor_ids;
318 static uint32_t		minor_count;
319 
320 /*
321  * Logging stuff. Perhaps mac_logging_interval could be broken into
322  * mac_flow_log_interval and mac_link_log_interval if we want to be
323  * able to schedule them differently.
324  */
325 uint_t			mac_logging_interval;
326 boolean_t		mac_flow_log_enable;
327 boolean_t		mac_link_log_enable;
328 timeout_id_t		mac_logging_timer;
329 
330 /* for debugging, see MAC_DBG_PRT() in mac_impl.h */
331 int mac_dbg = 0;
332 
333 #define	MACTYPE_KMODDIR	"mac"
334 #define	MACTYPE_HASHSZ	67
335 static mod_hash_t	*i_mactype_hash;
336 /*
337  * i_mactype_lock synchronizes threads that obtain references to mactype_t
338  * structures through i_mactype_getplugin().
339  */
340 static kmutex_t		i_mactype_lock;
341 
342 /*
343  * mac_tx_percpu_cnt
344  *
345  * Number of per cpu locks per mac_client_impl_t. Used by the transmit side
346  * in mac_tx to reduce lock contention. This is sized at boot time in mac_init.
347  * mac_tx_percpu_cnt_max is settable in /etc/system and must be a power of 2.
348  * Per cpu locks may be disabled by setting mac_tx_percpu_cnt_max to 1.
349  */
350 int mac_tx_percpu_cnt;
351 int mac_tx_percpu_cnt_max = 128;
352 
353 /*
354  * Call back functions for the bridge module.  These are guaranteed to be valid
355  * when holding a reference on a link or when holding mip->mi_bridge_lock and
356  * mi_bridge_link is non-NULL.
357  */
358 mac_bridge_tx_t mac_bridge_tx_cb;
359 mac_bridge_rx_t mac_bridge_rx_cb;
360 mac_bridge_ref_t mac_bridge_ref_cb;
361 mac_bridge_ls_t mac_bridge_ls_cb;
362 
363 static int i_mac_constructor(void *, void *, int);
364 static void i_mac_destructor(void *, void *);
365 static int i_mac_ring_ctor(void *, void *, int);
366 static void i_mac_ring_dtor(void *, void *);
367 static mblk_t *mac_rx_classify(mac_impl_t *, mac_resource_handle_t, mblk_t *);
368 void mac_tx_client_flush(mac_client_impl_t *);
369 void mac_tx_client_block(mac_client_impl_t *);
370 static void mac_rx_ring_quiesce(mac_ring_t *, uint_t);
371 static int mac_start_group_and_rings(mac_group_t *);
372 static void mac_stop_group_and_rings(mac_group_t *);
373 
374 /*
375  * Module initialization functions.
376  */
377 
378 void
379 mac_init(void)
380 {
381 	mac_tx_percpu_cnt = ((boot_max_ncpus == -1) ? max_ncpus :
382 	    boot_max_ncpus);
383 
384 	/* Upper bound is mac_tx_percpu_cnt_max */
385 	if (mac_tx_percpu_cnt > mac_tx_percpu_cnt_max)
386 		mac_tx_percpu_cnt = mac_tx_percpu_cnt_max;
387 
388 	if (mac_tx_percpu_cnt < 1) {
389 		/* Someone set max_tx_percpu_cnt_max to 0 or less */
390 		mac_tx_percpu_cnt = 1;
391 	}
392 
393 	ASSERT(mac_tx_percpu_cnt >= 1);
394 	mac_tx_percpu_cnt = (1 << highbit(mac_tx_percpu_cnt - 1));
395 	/*
396 	 * Make it of the form 2**N - 1 in the range
397 	 * [0 .. mac_tx_percpu_cnt_max - 1]
398 	 */
399 	mac_tx_percpu_cnt--;
400 
401 	i_mac_impl_cachep = kmem_cache_create("mac_impl_cache",
402 	    sizeof (mac_impl_t), 0, i_mac_constructor, i_mac_destructor,
403 	    NULL, NULL, NULL, 0);
404 	ASSERT(i_mac_impl_cachep != NULL);
405 
406 	mac_ring_cache = kmem_cache_create("mac_ring_cache",
407 	    sizeof (mac_ring_t), 0, i_mac_ring_ctor, i_mac_ring_dtor, NULL,
408 	    NULL, NULL, 0);
409 	ASSERT(mac_ring_cache != NULL);
410 
411 	i_mac_impl_hash = mod_hash_create_extended("mac_impl_hash",
412 	    IMPL_HASHSZ, mod_hash_null_keydtor, mod_hash_null_valdtor,
413 	    mod_hash_bystr, NULL, mod_hash_strkey_cmp, KM_SLEEP);
414 	rw_init(&i_mac_impl_lock, NULL, RW_DEFAULT, NULL);
415 
416 	mac_flow_init();
417 	mac_soft_ring_init();
418 	mac_bcast_init();
419 	mac_client_init();
420 
421 	i_mac_impl_count = 0;
422 
423 	i_mactype_hash = mod_hash_create_extended("mactype_hash",
424 	    MACTYPE_HASHSZ,
425 	    mod_hash_null_keydtor, mod_hash_null_valdtor,
426 	    mod_hash_bystr, NULL, mod_hash_strkey_cmp, KM_SLEEP);
427 
428 	/*
429 	 * Allocate an id space to manage minor numbers. The range of the
430 	 * space will be from MAC_MAX_MINOR+1 to MAC_PRIVATE_MINOR-1.  This
431 	 * leaves half of the 32-bit minors available for driver private use.
432 	 */
433 	minor_ids = id_space_create("mac_minor_ids", MAC_MAX_MINOR+1,
434 	    MAC_PRIVATE_MINOR-1);
435 	ASSERT(minor_ids != NULL);
436 	minor_count = 0;
437 
438 	/* Let's default to 20 seconds */
439 	mac_logging_interval = 20;
440 	mac_flow_log_enable = B_FALSE;
441 	mac_link_log_enable = B_FALSE;
442 	mac_logging_timer = 0;
443 }
444 
445 int
446 mac_fini(void)
447 {
448 	if (i_mac_impl_count > 0 || minor_count > 0)
449 		return (EBUSY);
450 
451 	id_space_destroy(minor_ids);
452 	mac_flow_fini();
453 
454 	mod_hash_destroy_hash(i_mac_impl_hash);
455 	rw_destroy(&i_mac_impl_lock);
456 
457 	mac_client_fini();
458 	kmem_cache_destroy(mac_ring_cache);
459 
460 	mod_hash_destroy_hash(i_mactype_hash);
461 	mac_soft_ring_finish();
462 	return (0);
463 }
464 
465 void
466 mac_init_ops(struct dev_ops *ops, const char *name)
467 {
468 	dld_init_ops(ops, name);
469 }
470 
471 void
472 mac_fini_ops(struct dev_ops *ops)
473 {
474 	dld_fini_ops(ops);
475 }
476 
477 /*ARGSUSED*/
478 static int
479 i_mac_constructor(void *buf, void *arg, int kmflag)
480 {
481 	mac_impl_t	*mip = buf;
482 
483 	bzero(buf, sizeof (mac_impl_t));
484 
485 	mip->mi_linkstate = LINK_STATE_UNKNOWN;
486 
487 	mutex_init(&mip->mi_lock, NULL, MUTEX_DRIVER, NULL);
488 	rw_init(&mip->mi_rw_lock, NULL, RW_DRIVER, NULL);
489 	mutex_init(&mip->mi_notify_lock, NULL, MUTEX_DRIVER, NULL);
490 	mutex_init(&mip->mi_promisc_lock, NULL, MUTEX_DRIVER, NULL);
491 	mutex_init(&mip->mi_ring_lock, NULL, MUTEX_DEFAULT, NULL);
492 
493 	mip->mi_notify_cb_info.mcbi_lockp = &mip->mi_notify_lock;
494 	cv_init(&mip->mi_notify_cb_info.mcbi_cv, NULL, CV_DRIVER, NULL);
495 	mip->mi_promisc_cb_info.mcbi_lockp = &mip->mi_promisc_lock;
496 	cv_init(&mip->mi_promisc_cb_info.mcbi_cv, NULL, CV_DRIVER, NULL);
497 
498 	mutex_init(&mip->mi_bridge_lock, NULL, MUTEX_DEFAULT, NULL);
499 
500 	return (0);
501 }
502 
503 /*ARGSUSED*/
504 static void
505 i_mac_destructor(void *buf, void *arg)
506 {
507 	mac_impl_t	*mip = buf;
508 	mac_cb_info_t	*mcbi;
509 
510 	ASSERT(mip->mi_ref == 0);
511 	ASSERT(mip->mi_active == 0);
512 	ASSERT(mip->mi_linkstate == LINK_STATE_UNKNOWN);
513 	ASSERT(mip->mi_devpromisc == 0);
514 	ASSERT(mip->mi_ksp == NULL);
515 	ASSERT(mip->mi_kstat_count == 0);
516 	ASSERT(mip->mi_nclients == 0);
517 	ASSERT(mip->mi_nactiveclients == 0);
518 	ASSERT(mip->mi_single_active_client == NULL);
519 	ASSERT(mip->mi_state_flags == 0);
520 	ASSERT(mip->mi_factory_addr == NULL);
521 	ASSERT(mip->mi_factory_addr_num == 0);
522 	ASSERT(mip->mi_default_tx_ring == NULL);
523 
524 	mcbi = &mip->mi_notify_cb_info;
525 	ASSERT(mcbi->mcbi_del_cnt == 0 && mcbi->mcbi_walker_cnt == 0);
526 	ASSERT(mip->mi_notify_bits == 0);
527 	ASSERT(mip->mi_notify_thread == NULL);
528 	ASSERT(mcbi->mcbi_lockp == &mip->mi_notify_lock);
529 	mcbi->mcbi_lockp = NULL;
530 
531 	mcbi = &mip->mi_promisc_cb_info;
532 	ASSERT(mcbi->mcbi_del_cnt == 0 && mip->mi_promisc_list == NULL);
533 	ASSERT(mip->mi_promisc_list == NULL);
534 	ASSERT(mcbi->mcbi_lockp == &mip->mi_promisc_lock);
535 	mcbi->mcbi_lockp = NULL;
536 
537 	ASSERT(mip->mi_bcast_ngrps == 0 && mip->mi_bcast_grp == NULL);
538 	ASSERT(mip->mi_perim_owner == NULL && mip->mi_perim_ocnt == 0);
539 
540 	mutex_destroy(&mip->mi_lock);
541 	rw_destroy(&mip->mi_rw_lock);
542 
543 	mutex_destroy(&mip->mi_promisc_lock);
544 	cv_destroy(&mip->mi_promisc_cb_info.mcbi_cv);
545 	mutex_destroy(&mip->mi_notify_lock);
546 	cv_destroy(&mip->mi_notify_cb_info.mcbi_cv);
547 	mutex_destroy(&mip->mi_ring_lock);
548 
549 	ASSERT(mip->mi_bridge_link == NULL);
550 }
551 
552 /* ARGSUSED */
553 static int
554 i_mac_ring_ctor(void *buf, void *arg, int kmflag)
555 {
556 	mac_ring_t *ring = (mac_ring_t *)buf;
557 
558 	bzero(ring, sizeof (mac_ring_t));
559 	cv_init(&ring->mr_cv, NULL, CV_DEFAULT, NULL);
560 	mutex_init(&ring->mr_lock, NULL, MUTEX_DEFAULT, NULL);
561 	ring->mr_state = MR_FREE;
562 	return (0);
563 }
564 
565 /* ARGSUSED */
566 static void
567 i_mac_ring_dtor(void *buf, void *arg)
568 {
569 	mac_ring_t *ring = (mac_ring_t *)buf;
570 
571 	cv_destroy(&ring->mr_cv);
572 	mutex_destroy(&ring->mr_lock);
573 }
574 
575 /*
576  * Common functions to do mac callback addition and deletion. Currently this is
577  * used by promisc callbacks and notify callbacks. List addition and deletion
578  * need to take care of list walkers. List walkers in general, can't hold list
579  * locks and make upcall callbacks due to potential lock order and recursive
580  * reentry issues. Instead list walkers increment the list walker count to mark
581  * the presence of a walker thread. Addition can be carefully done to ensure
582  * that the list walker always sees either the old list or the new list.
583  * However the deletion can't be done while the walker is active, instead the
584  * deleting thread simply marks the entry as logically deleted. The last walker
585  * physically deletes and frees up the logically deleted entries when the walk
586  * is complete.
587  */
588 void
589 mac_callback_add(mac_cb_info_t *mcbi, mac_cb_t **mcb_head,
590     mac_cb_t *mcb_elem)
591 {
592 	mac_cb_t	*p;
593 	mac_cb_t	**pp;
594 
595 	/* Verify it is not already in the list */
596 	for (pp = mcb_head; (p = *pp) != NULL; pp = &p->mcb_nextp) {
597 		if (p == mcb_elem)
598 			break;
599 	}
600 	VERIFY(p == NULL);
601 
602 	/*
603 	 * Add it to the head of the callback list. The membar ensures that
604 	 * the following list pointer manipulations reach global visibility
605 	 * in exactly the program order below.
606 	 */
607 	ASSERT(MUTEX_HELD(mcbi->mcbi_lockp));
608 
609 	mcb_elem->mcb_nextp = *mcb_head;
610 	membar_producer();
611 	*mcb_head = mcb_elem;
612 }
613 
614 /*
615  * Mark the entry as logically deleted. If there aren't any walkers unlink
616  * from the list. In either case return the corresponding status.
617  */
618 boolean_t
619 mac_callback_remove(mac_cb_info_t *mcbi, mac_cb_t **mcb_head,
620     mac_cb_t *mcb_elem)
621 {
622 	mac_cb_t	*p;
623 	mac_cb_t	**pp;
624 
625 	ASSERT(MUTEX_HELD(mcbi->mcbi_lockp));
626 	/*
627 	 * Search the callback list for the entry to be removed
628 	 */
629 	for (pp = mcb_head; (p = *pp) != NULL; pp = &p->mcb_nextp) {
630 		if (p == mcb_elem)
631 			break;
632 	}
633 	VERIFY(p != NULL);
634 
635 	/*
636 	 * If there are walkers just mark it as deleted and the last walker
637 	 * will remove from the list and free it.
638 	 */
639 	if (mcbi->mcbi_walker_cnt != 0) {
640 		p->mcb_flags |= MCB_CONDEMNED;
641 		mcbi->mcbi_del_cnt++;
642 		return (B_FALSE);
643 	}
644 
645 	ASSERT(mcbi->mcbi_del_cnt == 0);
646 	*pp = p->mcb_nextp;
647 	p->mcb_nextp = NULL;
648 	return (B_TRUE);
649 }
650 
651 /*
652  * Wait for all pending callback removals to be completed
653  */
654 void
655 mac_callback_remove_wait(mac_cb_info_t *mcbi)
656 {
657 	ASSERT(MUTEX_HELD(mcbi->mcbi_lockp));
658 	while (mcbi->mcbi_del_cnt != 0) {
659 		DTRACE_PROBE1(need_wait, mac_cb_info_t *, mcbi);
660 		cv_wait(&mcbi->mcbi_cv, mcbi->mcbi_lockp);
661 	}
662 }
663 
664 /*
665  * The last mac callback walker does the cleanup. Walk the list and unlik
666  * all the logically deleted entries and construct a temporary list of
667  * removed entries. Return the list of removed entries to the caller.
668  */
669 mac_cb_t *
670 mac_callback_walker_cleanup(mac_cb_info_t *mcbi, mac_cb_t **mcb_head)
671 {
672 	mac_cb_t	*p;
673 	mac_cb_t	**pp;
674 	mac_cb_t	*rmlist = NULL;		/* List of removed elements */
675 	int	cnt = 0;
676 
677 	ASSERT(MUTEX_HELD(mcbi->mcbi_lockp));
678 	ASSERT(mcbi->mcbi_del_cnt != 0 && mcbi->mcbi_walker_cnt == 0);
679 
680 	pp = mcb_head;
681 	while (*pp != NULL) {
682 		if ((*pp)->mcb_flags & MCB_CONDEMNED) {
683 			p = *pp;
684 			*pp = p->mcb_nextp;
685 			p->mcb_nextp = rmlist;
686 			rmlist = p;
687 			cnt++;
688 			continue;
689 		}
690 		pp = &(*pp)->mcb_nextp;
691 	}
692 
693 	ASSERT(mcbi->mcbi_del_cnt == cnt);
694 	mcbi->mcbi_del_cnt = 0;
695 	return (rmlist);
696 }
697 
698 boolean_t
699 mac_callback_lookup(mac_cb_t **mcb_headp, mac_cb_t *mcb_elem)
700 {
701 	mac_cb_t	*mcb;
702 
703 	/* Verify it is not already in the list */
704 	for (mcb = *mcb_headp; mcb != NULL; mcb = mcb->mcb_nextp) {
705 		if (mcb == mcb_elem)
706 			return (B_TRUE);
707 	}
708 
709 	return (B_FALSE);
710 }
711 
712 boolean_t
713 mac_callback_find(mac_cb_info_t *mcbi, mac_cb_t **mcb_headp, mac_cb_t *mcb_elem)
714 {
715 	boolean_t	found;
716 
717 	mutex_enter(mcbi->mcbi_lockp);
718 	found = mac_callback_lookup(mcb_headp, mcb_elem);
719 	mutex_exit(mcbi->mcbi_lockp);
720 
721 	return (found);
722 }
723 
724 /* Free the list of removed callbacks */
725 void
726 mac_callback_free(mac_cb_t *rmlist)
727 {
728 	mac_cb_t	*mcb;
729 	mac_cb_t	*mcb_next;
730 
731 	for (mcb = rmlist; mcb != NULL; mcb = mcb_next) {
732 		mcb_next = mcb->mcb_nextp;
733 		kmem_free(mcb->mcb_objp, mcb->mcb_objsize);
734 	}
735 }
736 
737 /*
738  * The promisc callbacks are in 2 lists, one off the 'mip' and another off the
739  * 'mcip' threaded by mpi_mi_link and mpi_mci_link respectively. However there
740  * is only a single shared total walker count, and an entry can't be physically
741  * unlinked if a walker is active on either list. The last walker does this
742  * cleanup of logically deleted entries.
743  */
744 void
745 i_mac_promisc_walker_cleanup(mac_impl_t *mip)
746 {
747 	mac_cb_t	*rmlist;
748 	mac_cb_t	*mcb;
749 	mac_cb_t	*mcb_next;
750 	mac_promisc_impl_t	*mpip;
751 
752 	/*
753 	 * Construct a temporary list of deleted callbacks by walking the
754 	 * the mi_promisc_list. Then for each entry in the temporary list,
755 	 * remove it from the mci_promisc_list and free the entry.
756 	 */
757 	rmlist = mac_callback_walker_cleanup(&mip->mi_promisc_cb_info,
758 	    &mip->mi_promisc_list);
759 
760 	for (mcb = rmlist; mcb != NULL; mcb = mcb_next) {
761 		mcb_next = mcb->mcb_nextp;
762 		mpip = (mac_promisc_impl_t *)mcb->mcb_objp;
763 		VERIFY(mac_callback_remove(&mip->mi_promisc_cb_info,
764 		    &mpip->mpi_mcip->mci_promisc_list, &mpip->mpi_mci_link));
765 		mcb->mcb_flags = 0;
766 		mcb->mcb_nextp = NULL;
767 		kmem_cache_free(mac_promisc_impl_cache, mpip);
768 	}
769 }
770 
771 void
772 i_mac_notify(mac_impl_t *mip, mac_notify_type_t type)
773 {
774 	mac_cb_info_t	*mcbi;
775 
776 	/*
777 	 * Signal the notify thread even after mi_ref has become zero and
778 	 * mi_disabled is set. The synchronization with the notify thread
779 	 * happens in mac_unregister and that implies the driver must make
780 	 * sure it is single-threaded (with respect to mac calls) and that
781 	 * all pending mac calls have returned before it calls mac_unregister
782 	 */
783 	rw_enter(&i_mac_impl_lock, RW_READER);
784 	if (mip->mi_state_flags & MIS_DISABLED)
785 		goto exit;
786 
787 	/*
788 	 * Guard against incorrect notifications.  (Running a newer
789 	 * mac client against an older implementation?)
790 	 */
791 	if (type >= MAC_NNOTE)
792 		goto exit;
793 
794 	mcbi = &mip->mi_notify_cb_info;
795 	mutex_enter(mcbi->mcbi_lockp);
796 	mip->mi_notify_bits |= (1 << type);
797 	cv_broadcast(&mcbi->mcbi_cv);
798 	mutex_exit(mcbi->mcbi_lockp);
799 
800 exit:
801 	rw_exit(&i_mac_impl_lock);
802 }
803 
804 /*
805  * Mac serialization primitives. Please see the block comment at the
806  * top of the file.
807  */
808 void
809 i_mac_perim_enter(mac_impl_t *mip)
810 {
811 	mac_client_impl_t	*mcip;
812 
813 	if (mip->mi_state_flags & MIS_IS_VNIC) {
814 		/*
815 		 * This is a VNIC. Return the lower mac since that is what
816 		 * we want to serialize on.
817 		 */
818 		mcip = mac_vnic_lower(mip);
819 		mip = mcip->mci_mip;
820 	}
821 
822 	mutex_enter(&mip->mi_perim_lock);
823 	if (mip->mi_perim_owner == curthread) {
824 		mip->mi_perim_ocnt++;
825 		mutex_exit(&mip->mi_perim_lock);
826 		return;
827 	}
828 
829 	while (mip->mi_perim_owner != NULL)
830 		cv_wait(&mip->mi_perim_cv, &mip->mi_perim_lock);
831 
832 	mip->mi_perim_owner = curthread;
833 	ASSERT(mip->mi_perim_ocnt == 0);
834 	mip->mi_perim_ocnt++;
835 #ifdef DEBUG
836 	mip->mi_perim_stack_depth = getpcstack(mip->mi_perim_stack,
837 	    MAC_PERIM_STACK_DEPTH);
838 #endif
839 	mutex_exit(&mip->mi_perim_lock);
840 }
841 
842 int
843 i_mac_perim_enter_nowait(mac_impl_t *mip)
844 {
845 	/*
846 	 * The vnic is a special case, since the serialization is done based
847 	 * on the lower mac. If the lower mac is busy, it does not imply the
848 	 * vnic can't be unregistered. But in the case of other drivers,
849 	 * a busy perimeter or open mac handles implies that the mac is busy
850 	 * and can't be unregistered.
851 	 */
852 	if (mip->mi_state_flags & MIS_IS_VNIC) {
853 		i_mac_perim_enter(mip);
854 		return (0);
855 	}
856 
857 	mutex_enter(&mip->mi_perim_lock);
858 	if (mip->mi_perim_owner != NULL) {
859 		mutex_exit(&mip->mi_perim_lock);
860 		return (EBUSY);
861 	}
862 	ASSERT(mip->mi_perim_ocnt == 0);
863 	mip->mi_perim_owner = curthread;
864 	mip->mi_perim_ocnt++;
865 	mutex_exit(&mip->mi_perim_lock);
866 
867 	return (0);
868 }
869 
870 void
871 i_mac_perim_exit(mac_impl_t *mip)
872 {
873 	mac_client_impl_t *mcip;
874 
875 	if (mip->mi_state_flags & MIS_IS_VNIC) {
876 		/*
877 		 * This is a VNIC. Return the lower mac since that is what
878 		 * we want to serialize on.
879 		 */
880 		mcip = mac_vnic_lower(mip);
881 		mip = mcip->mci_mip;
882 	}
883 
884 	ASSERT(mip->mi_perim_owner == curthread && mip->mi_perim_ocnt != 0);
885 
886 	mutex_enter(&mip->mi_perim_lock);
887 	if (--mip->mi_perim_ocnt == 0) {
888 		mip->mi_perim_owner = NULL;
889 		cv_signal(&mip->mi_perim_cv);
890 	}
891 	mutex_exit(&mip->mi_perim_lock);
892 }
893 
894 /*
895  * Returns whether the current thread holds the mac perimeter. Used in making
896  * assertions.
897  */
898 boolean_t
899 mac_perim_held(mac_handle_t mh)
900 {
901 	mac_impl_t	*mip = (mac_impl_t *)mh;
902 	mac_client_impl_t *mcip;
903 
904 	if (mip->mi_state_flags & MIS_IS_VNIC) {
905 		/*
906 		 * This is a VNIC. Return the lower mac since that is what
907 		 * we want to serialize on.
908 		 */
909 		mcip = mac_vnic_lower(mip);
910 		mip = mcip->mci_mip;
911 	}
912 	return (mip->mi_perim_owner == curthread);
913 }
914 
915 /*
916  * mac client interfaces to enter the mac perimeter of a mac end point, given
917  * its mac handle, or macname or linkid.
918  */
919 void
920 mac_perim_enter_by_mh(mac_handle_t mh, mac_perim_handle_t *mphp)
921 {
922 	mac_impl_t	*mip = (mac_impl_t *)mh;
923 
924 	i_mac_perim_enter(mip);
925 	/*
926 	 * The mac_perim_handle_t returned encodes the 'mip' and whether a
927 	 * mac_open has been done internally while entering the perimeter.
928 	 * This information is used in mac_perim_exit
929 	 */
930 	MAC_ENCODE_MPH(*mphp, mip, 0);
931 }
932 
933 int
934 mac_perim_enter_by_macname(const char *name, mac_perim_handle_t *mphp)
935 {
936 	int	err;
937 	mac_handle_t	mh;
938 
939 	if ((err = mac_open(name, &mh)) != 0)
940 		return (err);
941 
942 	mac_perim_enter_by_mh(mh, mphp);
943 	MAC_ENCODE_MPH(*mphp, mh, 1);
944 	return (0);
945 }
946 
947 int
948 mac_perim_enter_by_linkid(datalink_id_t linkid, mac_perim_handle_t *mphp)
949 {
950 	int	err;
951 	mac_handle_t	mh;
952 
953 	if ((err = mac_open_by_linkid(linkid, &mh)) != 0)
954 		return (err);
955 
956 	mac_perim_enter_by_mh(mh, mphp);
957 	MAC_ENCODE_MPH(*mphp, mh, 1);
958 	return (0);
959 }
960 
961 void
962 mac_perim_exit(mac_perim_handle_t mph)
963 {
964 	mac_impl_t	*mip;
965 	boolean_t	need_close;
966 
967 	MAC_DECODE_MPH(mph, mip, need_close);
968 	i_mac_perim_exit(mip);
969 	if (need_close)
970 		mac_close((mac_handle_t)mip);
971 }
972 
973 int
974 mac_hold(const char *macname, mac_impl_t **pmip)
975 {
976 	mac_impl_t	*mip;
977 	int		err;
978 
979 	/*
980 	 * Check the device name length to make sure it won't overflow our
981 	 * buffer.
982 	 */
983 	if (strlen(macname) >= MAXNAMELEN)
984 		return (EINVAL);
985 
986 	/*
987 	 * Look up its entry in the global hash table.
988 	 */
989 	rw_enter(&i_mac_impl_lock, RW_WRITER);
990 	err = mod_hash_find(i_mac_impl_hash, (mod_hash_key_t)macname,
991 	    (mod_hash_val_t *)&mip);
992 
993 	if (err != 0) {
994 		rw_exit(&i_mac_impl_lock);
995 		return (ENOENT);
996 	}
997 
998 	if (mip->mi_state_flags & MIS_DISABLED) {
999 		rw_exit(&i_mac_impl_lock);
1000 		return (ENOENT);
1001 	}
1002 
1003 	if (mip->mi_state_flags & MIS_EXCLUSIVE_HELD) {
1004 		rw_exit(&i_mac_impl_lock);
1005 		return (EBUSY);
1006 	}
1007 
1008 	mip->mi_ref++;
1009 	rw_exit(&i_mac_impl_lock);
1010 
1011 	*pmip = mip;
1012 	return (0);
1013 }
1014 
1015 void
1016 mac_rele(mac_impl_t *mip)
1017 {
1018 	rw_enter(&i_mac_impl_lock, RW_WRITER);
1019 	ASSERT(mip->mi_ref != 0);
1020 	if (--mip->mi_ref == 0) {
1021 		ASSERT(mip->mi_nactiveclients == 0 &&
1022 		    !(mip->mi_state_flags & MIS_EXCLUSIVE));
1023 	}
1024 	rw_exit(&i_mac_impl_lock);
1025 }
1026 
1027 /*
1028  * Private GLDv3 function to start a MAC instance.
1029  */
1030 int
1031 mac_start(mac_handle_t mh)
1032 {
1033 	mac_impl_t	*mip = (mac_impl_t *)mh;
1034 	int		err = 0;
1035 
1036 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1037 	ASSERT(mip->mi_start != NULL);
1038 
1039 	/*
1040 	 * Check whether the device is already started.
1041 	 */
1042 	if (mip->mi_active++ == 0) {
1043 		mac_ring_t *ring = NULL;
1044 
1045 		/*
1046 		 * Start the device.
1047 		 */
1048 		err = mip->mi_start(mip->mi_driver);
1049 		if (err != 0) {
1050 			mip->mi_active--;
1051 			return (err);
1052 		}
1053 
1054 		/*
1055 		 * Start the default tx ring.
1056 		 */
1057 		if (mip->mi_default_tx_ring != NULL) {
1058 
1059 			ring = (mac_ring_t *)mip->mi_default_tx_ring;
1060 			err = mac_start_ring(ring);
1061 			if (err != 0) {
1062 				mip->mi_active--;
1063 				return (err);
1064 			}
1065 			ring->mr_state = MR_INUSE;
1066 		}
1067 
1068 		if (mip->mi_rx_groups != NULL) {
1069 			/*
1070 			 * Start the default ring, since it will be needed
1071 			 * to receive broadcast and multicast traffic for
1072 			 * both primary and non-primary MAC clients.
1073 			 */
1074 			mac_group_t *grp = &mip->mi_rx_groups[0];
1075 
1076 			ASSERT(grp->mrg_state == MAC_GROUP_STATE_REGISTERED);
1077 			err = mac_start_group_and_rings(grp);
1078 			if (err != 0) {
1079 				mip->mi_active--;
1080 				if (ring != NULL) {
1081 					mac_stop_ring(ring);
1082 					ring->mr_state = MR_FREE;
1083 				}
1084 				return (err);
1085 			}
1086 			mac_set_rx_group_state(grp, MAC_GROUP_STATE_SHARED);
1087 		}
1088 	}
1089 
1090 	return (err);
1091 }
1092 
1093 /*
1094  * Private GLDv3 function to stop a MAC instance.
1095  */
1096 void
1097 mac_stop(mac_handle_t mh)
1098 {
1099 	mac_impl_t	*mip = (mac_impl_t *)mh;
1100 
1101 	ASSERT(mip->mi_stop != NULL);
1102 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1103 
1104 	/*
1105 	 * Check whether the device is still needed.
1106 	 */
1107 	ASSERT(mip->mi_active != 0);
1108 	if (--mip->mi_active == 0) {
1109 		if (mip->mi_rx_groups != NULL) {
1110 			/*
1111 			 * There should be no more active clients since the
1112 			 * MAC is being stopped. Stop the default RX group
1113 			 * and transition it back to registered state.
1114 			 */
1115 			mac_group_t *grp = &mip->mi_rx_groups[0];
1116 
1117 			/*
1118 			 * When clients are torn down, the groups
1119 			 * are release via mac_release_rx_group which
1120 			 * knows the the default group is always in
1121 			 * started mode since broadcast uses it. So
1122 			 * we can assert that their are no clients
1123 			 * (since mac_bcast_add doesn't register itself
1124 			 * as a client) and group is in SHARED state.
1125 			 */
1126 			ASSERT(grp->mrg_state == MAC_GROUP_STATE_SHARED);
1127 			ASSERT(MAC_RX_GROUP_NO_CLIENT(grp) &&
1128 			    mip->mi_nactiveclients == 0);
1129 			mac_stop_group_and_rings(grp);
1130 			mac_set_rx_group_state(grp, MAC_GROUP_STATE_REGISTERED);
1131 		}
1132 
1133 		if (mip->mi_default_tx_ring != NULL) {
1134 			mac_ring_t *ring;
1135 
1136 			ring = (mac_ring_t *)mip->mi_default_tx_ring;
1137 			mac_stop_ring(ring);
1138 			ring->mr_state = MR_FREE;
1139 		}
1140 
1141 		/*
1142 		 * Stop the device.
1143 		 */
1144 		mip->mi_stop(mip->mi_driver);
1145 	}
1146 }
1147 
1148 int
1149 i_mac_promisc_set(mac_impl_t *mip, boolean_t on)
1150 {
1151 	int		err = 0;
1152 
1153 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1154 	ASSERT(mip->mi_setpromisc != NULL);
1155 
1156 	if (on) {
1157 		/*
1158 		 * Enable promiscuous mode on the device if not yet enabled.
1159 		 */
1160 		if (mip->mi_devpromisc++ == 0) {
1161 			err = mip->mi_setpromisc(mip->mi_driver, B_TRUE);
1162 			if (err != 0) {
1163 				mip->mi_devpromisc--;
1164 				return (err);
1165 			}
1166 			i_mac_notify(mip, MAC_NOTE_DEVPROMISC);
1167 		}
1168 	} else {
1169 		if (mip->mi_devpromisc == 0)
1170 			return (EPROTO);
1171 
1172 		/*
1173 		 * Disable promiscuous mode on the device if this is the last
1174 		 * enabling.
1175 		 */
1176 		if (--mip->mi_devpromisc == 0) {
1177 			err = mip->mi_setpromisc(mip->mi_driver, B_FALSE);
1178 			if (err != 0) {
1179 				mip->mi_devpromisc++;
1180 				return (err);
1181 			}
1182 			i_mac_notify(mip, MAC_NOTE_DEVPROMISC);
1183 		}
1184 	}
1185 
1186 	return (0);
1187 }
1188 
1189 /*
1190  * The promiscuity state can change any time. If the caller needs to take
1191  * actions that are atomic with the promiscuity state, then the caller needs
1192  * to bracket the entire sequence with mac_perim_enter/exit
1193  */
1194 boolean_t
1195 mac_promisc_get(mac_handle_t mh)
1196 {
1197 	mac_impl_t		*mip = (mac_impl_t *)mh;
1198 
1199 	/*
1200 	 * Return the current promiscuity.
1201 	 */
1202 	return (mip->mi_devpromisc != 0);
1203 }
1204 
1205 /*
1206  * Invoked at MAC instance attach time to initialize the list
1207  * of factory MAC addresses supported by a MAC instance. This function
1208  * builds a local cache in the mac_impl_t for the MAC addresses
1209  * supported by the underlying hardware. The MAC clients themselves
1210  * use the mac_addr_factory*() functions to query and reserve
1211  * factory MAC addresses.
1212  */
1213 void
1214 mac_addr_factory_init(mac_impl_t *mip)
1215 {
1216 	mac_capab_multifactaddr_t capab;
1217 	uint8_t *addr;
1218 	int i;
1219 
1220 	/*
1221 	 * First round to see how many factory MAC addresses are available.
1222 	 */
1223 	bzero(&capab, sizeof (capab));
1224 	if (!i_mac_capab_get((mac_handle_t)mip, MAC_CAPAB_MULTIFACTADDR,
1225 	    &capab) || (capab.mcm_naddr == 0)) {
1226 		/*
1227 		 * The MAC instance doesn't support multiple factory
1228 		 * MAC addresses, we're done here.
1229 		 */
1230 		return;
1231 	}
1232 
1233 	/*
1234 	 * Allocate the space and get all the factory addresses.
1235 	 */
1236 	addr = kmem_alloc(capab.mcm_naddr * MAXMACADDRLEN, KM_SLEEP);
1237 	capab.mcm_getaddr(mip->mi_driver, capab.mcm_naddr, addr);
1238 
1239 	mip->mi_factory_addr_num = capab.mcm_naddr;
1240 	mip->mi_factory_addr = kmem_zalloc(mip->mi_factory_addr_num *
1241 	    sizeof (mac_factory_addr_t), KM_SLEEP);
1242 
1243 	for (i = 0; i < capab.mcm_naddr; i++) {
1244 		bcopy(addr + i * MAXMACADDRLEN,
1245 		    mip->mi_factory_addr[i].mfa_addr,
1246 		    mip->mi_type->mt_addr_length);
1247 		mip->mi_factory_addr[i].mfa_in_use = B_FALSE;
1248 	}
1249 
1250 	kmem_free(addr, capab.mcm_naddr * MAXMACADDRLEN);
1251 }
1252 
1253 void
1254 mac_addr_factory_fini(mac_impl_t *mip)
1255 {
1256 	if (mip->mi_factory_addr == NULL) {
1257 		ASSERT(mip->mi_factory_addr_num == 0);
1258 		return;
1259 	}
1260 
1261 	kmem_free(mip->mi_factory_addr, mip->mi_factory_addr_num *
1262 	    sizeof (mac_factory_addr_t));
1263 
1264 	mip->mi_factory_addr = NULL;
1265 	mip->mi_factory_addr_num = 0;
1266 }
1267 
1268 /*
1269  * Reserve a factory MAC address. If *slot is set to -1, the function
1270  * attempts to reserve any of the available factory MAC addresses and
1271  * returns the reserved slot id. If no slots are available, the function
1272  * returns ENOSPC. If *slot is not set to -1, the function reserves
1273  * the specified slot if it is available, or returns EBUSY is the slot
1274  * is already used. Returns ENOTSUP if the underlying MAC does not
1275  * support multiple factory addresses. If the slot number is not -1 but
1276  * is invalid, returns EINVAL.
1277  */
1278 int
1279 mac_addr_factory_reserve(mac_client_handle_t mch, int *slot)
1280 {
1281 	mac_client_impl_t *mcip = (mac_client_impl_t *)mch;
1282 	mac_impl_t *mip = mcip->mci_mip;
1283 	int i, ret = 0;
1284 
1285 	i_mac_perim_enter(mip);
1286 	/*
1287 	 * Protect against concurrent readers that may need a self-consistent
1288 	 * view of the factory addresses
1289 	 */
1290 	rw_enter(&mip->mi_rw_lock, RW_WRITER);
1291 
1292 	if (mip->mi_factory_addr_num == 0) {
1293 		ret = ENOTSUP;
1294 		goto bail;
1295 	}
1296 
1297 	if (*slot != -1) {
1298 		/* check the specified slot */
1299 		if (*slot < 1 || *slot > mip->mi_factory_addr_num) {
1300 			ret = EINVAL;
1301 			goto bail;
1302 		}
1303 		if (mip->mi_factory_addr[*slot-1].mfa_in_use) {
1304 			ret = EBUSY;
1305 			goto bail;
1306 		}
1307 	} else {
1308 		/* pick the next available slot */
1309 		for (i = 0; i < mip->mi_factory_addr_num; i++) {
1310 			if (!mip->mi_factory_addr[i].mfa_in_use)
1311 				break;
1312 		}
1313 
1314 		if (i == mip->mi_factory_addr_num) {
1315 			ret = ENOSPC;
1316 			goto bail;
1317 		}
1318 		*slot = i+1;
1319 	}
1320 
1321 	mip->mi_factory_addr[*slot-1].mfa_in_use = B_TRUE;
1322 	mip->mi_factory_addr[*slot-1].mfa_client = mcip;
1323 
1324 bail:
1325 	rw_exit(&mip->mi_rw_lock);
1326 	i_mac_perim_exit(mip);
1327 	return (ret);
1328 }
1329 
1330 /*
1331  * Release the specified factory MAC address slot.
1332  */
1333 void
1334 mac_addr_factory_release(mac_client_handle_t mch, uint_t slot)
1335 {
1336 	mac_client_impl_t *mcip = (mac_client_impl_t *)mch;
1337 	mac_impl_t *mip = mcip->mci_mip;
1338 
1339 	i_mac_perim_enter(mip);
1340 	/*
1341 	 * Protect against concurrent readers that may need a self-consistent
1342 	 * view of the factory addresses
1343 	 */
1344 	rw_enter(&mip->mi_rw_lock, RW_WRITER);
1345 
1346 	ASSERT(slot > 0 && slot <= mip->mi_factory_addr_num);
1347 	ASSERT(mip->mi_factory_addr[slot-1].mfa_in_use);
1348 
1349 	mip->mi_factory_addr[slot-1].mfa_in_use = B_FALSE;
1350 
1351 	rw_exit(&mip->mi_rw_lock);
1352 	i_mac_perim_exit(mip);
1353 }
1354 
1355 /*
1356  * Stores in mac_addr the value of the specified MAC address. Returns
1357  * 0 on success, or EINVAL if the slot number is not valid for the MAC.
1358  * The caller must provide a string of at least MAXNAMELEN bytes.
1359  */
1360 void
1361 mac_addr_factory_value(mac_handle_t mh, int slot, uchar_t *mac_addr,
1362     uint_t *addr_len, char *client_name, boolean_t *in_use_arg)
1363 {
1364 	mac_impl_t *mip = (mac_impl_t *)mh;
1365 	boolean_t in_use;
1366 
1367 	ASSERT(slot > 0 && slot <= mip->mi_factory_addr_num);
1368 
1369 	/*
1370 	 * Readers need to hold mi_rw_lock. Writers need to hold mac perimeter
1371 	 * and mi_rw_lock
1372 	 */
1373 	rw_enter(&mip->mi_rw_lock, RW_READER);
1374 	bcopy(mip->mi_factory_addr[slot-1].mfa_addr, mac_addr, MAXMACADDRLEN);
1375 	*addr_len = mip->mi_type->mt_addr_length;
1376 	in_use = mip->mi_factory_addr[slot-1].mfa_in_use;
1377 	if (in_use && client_name != NULL) {
1378 		bcopy(mip->mi_factory_addr[slot-1].mfa_client->mci_name,
1379 		    client_name, MAXNAMELEN);
1380 	}
1381 	if (in_use_arg != NULL)
1382 		*in_use_arg = in_use;
1383 	rw_exit(&mip->mi_rw_lock);
1384 }
1385 
1386 /*
1387  * Returns the number of factory MAC addresses (in addition to the
1388  * primary MAC address), 0 if the underlying MAC doesn't support
1389  * that feature.
1390  */
1391 uint_t
1392 mac_addr_factory_num(mac_handle_t mh)
1393 {
1394 	mac_impl_t *mip = (mac_impl_t *)mh;
1395 
1396 	return (mip->mi_factory_addr_num);
1397 }
1398 
1399 
1400 void
1401 mac_rx_group_unmark(mac_group_t *grp, uint_t flag)
1402 {
1403 	mac_ring_t	*ring;
1404 
1405 	for (ring = grp->mrg_rings; ring != NULL; ring = ring->mr_next)
1406 		ring->mr_flag &= ~flag;
1407 }
1408 
1409 /*
1410  * The following mac_hwrings_xxx() functions are private mac client functions
1411  * used by the aggr driver to access and control the underlying HW Rx group
1412  * and rings. In this case, the aggr driver has exclusive control of the
1413  * underlying HW Rx group/rings, it calls the following functions to
1414  * start/stop the HW Rx rings, disable/enable polling, add/remove mac'
1415  * addresses, or set up the Rx callback.
1416  */
1417 /* ARGSUSED */
1418 static void
1419 mac_hwrings_rx_process(void *arg, mac_resource_handle_t srs,
1420     mblk_t *mp_chain, boolean_t loopback)
1421 {
1422 	mac_soft_ring_set_t	*mac_srs = (mac_soft_ring_set_t *)srs;
1423 	mac_srs_rx_t		*srs_rx = &mac_srs->srs_rx;
1424 	mac_direct_rx_t		proc;
1425 	void			*arg1;
1426 	mac_resource_handle_t	arg2;
1427 
1428 	proc = srs_rx->sr_func;
1429 	arg1 = srs_rx->sr_arg1;
1430 	arg2 = mac_srs->srs_mrh;
1431 
1432 	proc(arg1, arg2, mp_chain, NULL);
1433 }
1434 
1435 /*
1436  * This function is called to get the list of HW rings that are reserved by
1437  * an exclusive mac client.
1438  *
1439  * Return value: the number of HW rings.
1440  */
1441 int
1442 mac_hwrings_get(mac_client_handle_t mch, mac_group_handle_t *hwgh,
1443     mac_ring_handle_t *hwrh, mac_ring_type_t rtype)
1444 {
1445 	mac_client_impl_t	*mcip = (mac_client_impl_t *)mch;
1446 	int			cnt = 0;
1447 
1448 	switch (rtype) {
1449 	case MAC_RING_TYPE_RX: {
1450 		flow_entry_t	*flent = mcip->mci_flent;
1451 		mac_group_t	*grp;
1452 		mac_ring_t	*ring;
1453 
1454 		grp = flent->fe_rx_ring_group;
1455 		/*
1456 		 * The mac client did not reserve any RX group, return directly.
1457 		 * This is probably because the underlying MAC does not support
1458 		 * any groups.
1459 		 */
1460 		*hwgh = NULL;
1461 		if (grp == NULL)
1462 			return (0);
1463 		/*
1464 		 * This group must be reserved by this mac client.
1465 		 */
1466 		ASSERT((grp->mrg_state == MAC_GROUP_STATE_RESERVED) &&
1467 		    (mch == (mac_client_handle_t)
1468 		    (MAC_RX_GROUP_ONLY_CLIENT(grp))));
1469 		for (ring = grp->mrg_rings;
1470 		    ring != NULL; ring = ring->mr_next, cnt++) {
1471 			ASSERT(cnt < MAX_RINGS_PER_GROUP);
1472 			hwrh[cnt] = (mac_ring_handle_t)ring;
1473 		}
1474 		*hwgh = (mac_group_handle_t)grp;
1475 		return (cnt);
1476 	}
1477 	case MAC_RING_TYPE_TX: {
1478 		mac_soft_ring_set_t	*tx_srs;
1479 		mac_srs_tx_t		*tx;
1480 
1481 		tx_srs = MCIP_TX_SRS(mcip);
1482 		tx = &tx_srs->srs_tx;
1483 		for (; cnt < tx->st_ring_count; cnt++)
1484 			hwrh[cnt] = tx->st_rings[cnt];
1485 		return (cnt);
1486 	}
1487 	default:
1488 		ASSERT(B_FALSE);
1489 		return (-1);
1490 	}
1491 }
1492 
1493 /*
1494  * Setup the RX callback of the mac client which exclusively controls HW ring.
1495  */
1496 void
1497 mac_hwring_setup(mac_ring_handle_t hwrh, mac_resource_handle_t prh)
1498 {
1499 	mac_ring_t		*hw_ring = (mac_ring_t *)hwrh;
1500 	mac_soft_ring_set_t	*mac_srs = hw_ring->mr_srs;
1501 
1502 	mac_srs->srs_mrh = prh;
1503 	mac_srs->srs_rx.sr_lower_proc = mac_hwrings_rx_process;
1504 }
1505 
1506 void
1507 mac_hwring_teardown(mac_ring_handle_t hwrh)
1508 {
1509 	mac_ring_t		*hw_ring = (mac_ring_t *)hwrh;
1510 	mac_soft_ring_set_t	*mac_srs = hw_ring->mr_srs;
1511 
1512 	mac_srs->srs_rx.sr_lower_proc = mac_rx_srs_process;
1513 	mac_srs->srs_mrh = NULL;
1514 }
1515 
1516 int
1517 mac_hwring_disable_intr(mac_ring_handle_t rh)
1518 {
1519 	mac_ring_t *rr_ring = (mac_ring_t *)rh;
1520 	mac_intr_t *intr = &rr_ring->mr_info.mri_intr;
1521 
1522 	return (intr->mi_disable(intr->mi_handle));
1523 }
1524 
1525 int
1526 mac_hwring_enable_intr(mac_ring_handle_t rh)
1527 {
1528 	mac_ring_t *rr_ring = (mac_ring_t *)rh;
1529 	mac_intr_t *intr = &rr_ring->mr_info.mri_intr;
1530 
1531 	return (intr->mi_enable(intr->mi_handle));
1532 }
1533 
1534 int
1535 mac_hwring_start(mac_ring_handle_t rh)
1536 {
1537 	mac_ring_t *rr_ring = (mac_ring_t *)rh;
1538 
1539 	MAC_RING_UNMARK(rr_ring, MR_QUIESCE);
1540 	return (0);
1541 }
1542 
1543 void
1544 mac_hwring_stop(mac_ring_handle_t rh)
1545 {
1546 	mac_ring_t *rr_ring = (mac_ring_t *)rh;
1547 
1548 	mac_rx_ring_quiesce(rr_ring, MR_QUIESCE);
1549 }
1550 
1551 mblk_t *
1552 mac_hwring_poll(mac_ring_handle_t rh, int bytes_to_pickup)
1553 {
1554 	mac_ring_t *rr_ring = (mac_ring_t *)rh;
1555 	mac_ring_info_t *info = &rr_ring->mr_info;
1556 
1557 	return (info->mri_poll(info->mri_driver, bytes_to_pickup));
1558 }
1559 
1560 /*
1561  * Send packets through the selected tx ring.
1562  */
1563 mblk_t *
1564 mac_hwring_tx(mac_ring_handle_t rh, mblk_t *mp)
1565 {
1566 	mac_ring_t *ring = (mac_ring_t *)rh;
1567 	mac_ring_info_t *info = &ring->mr_info;
1568 
1569 	ASSERT(ring->mr_type == MAC_RING_TYPE_TX &&
1570 	    ring->mr_state >= MR_INUSE);
1571 	return (info->mri_tx(info->mri_driver, mp));
1572 }
1573 
1574 int
1575 mac_hwgroup_addmac(mac_group_handle_t gh, const uint8_t *addr)
1576 {
1577 	mac_group_t *group = (mac_group_t *)gh;
1578 
1579 	return (mac_group_addmac(group, addr));
1580 }
1581 
1582 int
1583 mac_hwgroup_remmac(mac_group_handle_t gh, const uint8_t *addr)
1584 {
1585 	mac_group_t *group = (mac_group_t *)gh;
1586 
1587 	return (mac_group_remmac(group, addr));
1588 }
1589 
1590 /*
1591  * Set the RX group to be shared/reserved. Note that the group must be
1592  * started/stopped outside of this function.
1593  */
1594 void
1595 mac_set_rx_group_state(mac_group_t *grp, mac_group_state_t state)
1596 {
1597 	/*
1598 	 * If there is no change in the group state, just return.
1599 	 */
1600 	if (grp->mrg_state == state)
1601 		return;
1602 
1603 	switch (state) {
1604 	case MAC_GROUP_STATE_RESERVED:
1605 		/*
1606 		 * Successfully reserved the group.
1607 		 *
1608 		 * Given that there is an exclusive client controlling this
1609 		 * group, we enable the group level polling when available,
1610 		 * so that SRSs get to turn on/off individual rings they's
1611 		 * assigned to.
1612 		 */
1613 		ASSERT(MAC_PERIM_HELD(grp->mrg_mh));
1614 
1615 		if (GROUP_INTR_DISABLE_FUNC(grp) != NULL)
1616 			GROUP_INTR_DISABLE_FUNC(grp)(GROUP_INTR_HANDLE(grp));
1617 
1618 		break;
1619 
1620 	case MAC_GROUP_STATE_SHARED:
1621 		/*
1622 		 * Set all rings of this group to software classified.
1623 		 * If the group has an overriding interrupt, then re-enable it.
1624 		 */
1625 		ASSERT(MAC_PERIM_HELD(grp->mrg_mh));
1626 
1627 		if (GROUP_INTR_ENABLE_FUNC(grp) != NULL)
1628 			GROUP_INTR_ENABLE_FUNC(grp)(GROUP_INTR_HANDLE(grp));
1629 
1630 		/* The ring is not available for reservations any more */
1631 		break;
1632 
1633 	case MAC_GROUP_STATE_REGISTERED:
1634 		/* Also callable from mac_register, perim is not held */
1635 		break;
1636 
1637 	default:
1638 		ASSERT(B_FALSE);
1639 		break;
1640 	}
1641 
1642 	grp->mrg_state = state;
1643 }
1644 
1645 /*
1646  * Quiesce future hardware classified packets for the specified Rx ring
1647  */
1648 static void
1649 mac_rx_ring_quiesce(mac_ring_t *rx_ring, uint_t ring_flag)
1650 {
1651 	ASSERT(rx_ring->mr_classify_type == MAC_HW_CLASSIFIER);
1652 	ASSERT(ring_flag == MR_CONDEMNED || ring_flag  == MR_QUIESCE);
1653 
1654 	mutex_enter(&rx_ring->mr_lock);
1655 	rx_ring->mr_flag |= ring_flag;
1656 	while (rx_ring->mr_refcnt != 0)
1657 		cv_wait(&rx_ring->mr_cv, &rx_ring->mr_lock);
1658 	mutex_exit(&rx_ring->mr_lock);
1659 }
1660 
1661 /*
1662  * Please see mac_tx for details about the per cpu locking scheme
1663  */
1664 static void
1665 mac_tx_lock_all(mac_client_impl_t *mcip)
1666 {
1667 	int	i;
1668 
1669 	for (i = 0; i <= mac_tx_percpu_cnt; i++)
1670 		mutex_enter(&mcip->mci_tx_pcpu[i].pcpu_tx_lock);
1671 }
1672 
1673 static void
1674 mac_tx_unlock_all(mac_client_impl_t *mcip)
1675 {
1676 	int	i;
1677 
1678 	for (i = mac_tx_percpu_cnt; i >= 0; i--)
1679 		mutex_exit(&mcip->mci_tx_pcpu[i].pcpu_tx_lock);
1680 }
1681 
1682 static void
1683 mac_tx_unlock_allbutzero(mac_client_impl_t *mcip)
1684 {
1685 	int	i;
1686 
1687 	for (i = mac_tx_percpu_cnt; i > 0; i--)
1688 		mutex_exit(&mcip->mci_tx_pcpu[i].pcpu_tx_lock);
1689 }
1690 
1691 static int
1692 mac_tx_sum_refcnt(mac_client_impl_t *mcip)
1693 {
1694 	int	i;
1695 	int	refcnt = 0;
1696 
1697 	for (i = 0; i <= mac_tx_percpu_cnt; i++)
1698 		refcnt += mcip->mci_tx_pcpu[i].pcpu_tx_refcnt;
1699 
1700 	return (refcnt);
1701 }
1702 
1703 /*
1704  * Stop future Tx packets coming down from the client in preparation for
1705  * quiescing the Tx side. This is needed for dynamic reclaim and reassignment
1706  * of rings between clients
1707  */
1708 void
1709 mac_tx_client_block(mac_client_impl_t *mcip)
1710 {
1711 	mac_tx_lock_all(mcip);
1712 	mcip->mci_tx_flag |= MCI_TX_QUIESCE;
1713 	while (mac_tx_sum_refcnt(mcip) != 0) {
1714 		mac_tx_unlock_allbutzero(mcip);
1715 		cv_wait(&mcip->mci_tx_cv, &mcip->mci_tx_pcpu[0].pcpu_tx_lock);
1716 		mutex_exit(&mcip->mci_tx_pcpu[0].pcpu_tx_lock);
1717 		mac_tx_lock_all(mcip);
1718 	}
1719 	mac_tx_unlock_all(mcip);
1720 }
1721 
1722 void
1723 mac_tx_client_unblock(mac_client_impl_t *mcip)
1724 {
1725 	mac_tx_lock_all(mcip);
1726 	mcip->mci_tx_flag &= ~MCI_TX_QUIESCE;
1727 	mac_tx_unlock_all(mcip);
1728 	/*
1729 	 * We may fail to disable flow control for the last MAC_NOTE_TX
1730 	 * notification because the MAC client is quiesced. Send the
1731 	 * notification again.
1732 	 */
1733 	i_mac_notify(mcip->mci_mip, MAC_NOTE_TX);
1734 }
1735 
1736 /*
1737  * Wait for an SRS to quiesce. The SRS worker will signal us when the
1738  * quiesce is done.
1739  */
1740 static void
1741 mac_srs_quiesce_wait(mac_soft_ring_set_t *srs, uint_t srs_flag)
1742 {
1743 	mutex_enter(&srs->srs_lock);
1744 	while (!(srs->srs_state & srs_flag))
1745 		cv_wait(&srs->srs_quiesce_done_cv, &srs->srs_lock);
1746 	mutex_exit(&srs->srs_lock);
1747 }
1748 
1749 /*
1750  * Quiescing an Rx SRS is achieved by the following sequence. The protocol
1751  * works bottom up by cutting off packet flow from the bottommost point in the
1752  * mac, then the SRS, and then the soft rings. There are 2 use cases of this
1753  * mechanism. One is a temporary quiesce of the SRS, such as say while changing
1754  * the Rx callbacks. Another use case is Rx SRS teardown. In the former case
1755  * the QUIESCE prefix/suffix is used and in the latter the CONDEMNED is used
1756  * for the SRS and MR flags. In the former case the threads pause waiting for
1757  * a restart, while in the latter case the threads exit. The Tx SRS teardown
1758  * is also mostly similar to the above.
1759  *
1760  * 1. Stop future hardware classified packets at the lowest level in the mac.
1761  *    Remove any hardware classification rule (CONDEMNED case) and mark the
1762  *    rings as CONDEMNED or QUIESCE as appropriate. This prevents the mr_refcnt
1763  *    from increasing. Upcalls from the driver that come through hardware
1764  *    classification will be dropped in mac_rx from now on. Then we wait for
1765  *    the mr_refcnt to drop to zero. When the mr_refcnt reaches zero we are
1766  *    sure there aren't any upcall threads from the driver through hardware
1767  *    classification. In the case of SRS teardown we also remove the
1768  *    classification rule in the driver.
1769  *
1770  * 2. Stop future software classified packets by marking the flow entry with
1771  *    FE_QUIESCE or FE_CONDEMNED as appropriate which prevents the refcnt from
1772  *    increasing. We also remove the flow entry from the table in the latter
1773  *    case. Then wait for the fe_refcnt to reach an appropriate quiescent value
1774  *    that indicates there aren't any active threads using that flow entry.
1775  *
1776  * 3. Quiesce the SRS and softrings by signaling the SRS. The SRS poll thread,
1777  *    SRS worker thread, and the soft ring threads are quiesced in sequence
1778  *    with the SRS worker thread serving as a master controller. This
1779  *    mechansim is explained in mac_srs_worker_quiesce().
1780  *
1781  * The restart mechanism to reactivate the SRS and softrings is explained
1782  * in mac_srs_worker_restart(). Here we just signal the SRS worker to start the
1783  * restart sequence.
1784  */
1785 void
1786 mac_rx_srs_quiesce(mac_soft_ring_set_t *srs, uint_t srs_quiesce_flag)
1787 {
1788 	flow_entry_t	*flent = srs->srs_flent;
1789 	uint_t	mr_flag, srs_done_flag;
1790 
1791 	ASSERT(MAC_PERIM_HELD((mac_handle_t)FLENT_TO_MIP(flent)));
1792 	ASSERT(!(srs->srs_type & SRST_TX));
1793 
1794 	if (srs_quiesce_flag == SRS_CONDEMNED) {
1795 		mr_flag = MR_CONDEMNED;
1796 		srs_done_flag = SRS_CONDEMNED_DONE;
1797 		if (srs->srs_type & SRST_CLIENT_POLL_ENABLED)
1798 			mac_srs_client_poll_disable(srs->srs_mcip, srs);
1799 	} else {
1800 		ASSERT(srs_quiesce_flag == SRS_QUIESCE);
1801 		mr_flag = MR_QUIESCE;
1802 		srs_done_flag = SRS_QUIESCE_DONE;
1803 		if (srs->srs_type & SRST_CLIENT_POLL_ENABLED)
1804 			mac_srs_client_poll_quiesce(srs->srs_mcip, srs);
1805 	}
1806 
1807 	if (srs->srs_ring != NULL) {
1808 		mac_rx_ring_quiesce(srs->srs_ring, mr_flag);
1809 	} else {
1810 		/*
1811 		 * SRS is driven by software classification. In case
1812 		 * of CONDEMNED, the top level teardown functions will
1813 		 * deal with flow removal.
1814 		 */
1815 		if (srs_quiesce_flag != SRS_CONDEMNED) {
1816 			FLOW_MARK(flent, FE_QUIESCE);
1817 			mac_flow_wait(flent, FLOW_DRIVER_UPCALL);
1818 		}
1819 	}
1820 
1821 	/*
1822 	 * Signal the SRS to quiesce itself, and then cv_wait for the
1823 	 * SRS quiesce to complete. The SRS worker thread will wake us
1824 	 * up when the quiesce is complete
1825 	 */
1826 	mac_srs_signal(srs, srs_quiesce_flag);
1827 	mac_srs_quiesce_wait(srs, srs_done_flag);
1828 }
1829 
1830 /*
1831  * Remove an SRS.
1832  */
1833 void
1834 mac_rx_srs_remove(mac_soft_ring_set_t *srs)
1835 {
1836 	flow_entry_t *flent = srs->srs_flent;
1837 	int i;
1838 
1839 	mac_rx_srs_quiesce(srs, SRS_CONDEMNED);
1840 	/*
1841 	 * Locate and remove our entry in the fe_rx_srs[] array, and
1842 	 * adjust the fe_rx_srs array entries and array count by
1843 	 * moving the last entry into the vacated spot.
1844 	 */
1845 	mutex_enter(&flent->fe_lock);
1846 	for (i = 0; i < flent->fe_rx_srs_cnt; i++) {
1847 		if (flent->fe_rx_srs[i] == srs)
1848 			break;
1849 	}
1850 
1851 	ASSERT(i != 0 && i < flent->fe_rx_srs_cnt);
1852 	if (i != flent->fe_rx_srs_cnt - 1) {
1853 		flent->fe_rx_srs[i] =
1854 		    flent->fe_rx_srs[flent->fe_rx_srs_cnt - 1];
1855 		i = flent->fe_rx_srs_cnt - 1;
1856 	}
1857 
1858 	flent->fe_rx_srs[i] = NULL;
1859 	flent->fe_rx_srs_cnt--;
1860 	mutex_exit(&flent->fe_lock);
1861 
1862 	mac_srs_free(srs);
1863 }
1864 
1865 static void
1866 mac_srs_clear_flag(mac_soft_ring_set_t *srs, uint_t flag)
1867 {
1868 	mutex_enter(&srs->srs_lock);
1869 	srs->srs_state &= ~flag;
1870 	mutex_exit(&srs->srs_lock);
1871 }
1872 
1873 void
1874 mac_rx_srs_restart(mac_soft_ring_set_t *srs)
1875 {
1876 	flow_entry_t	*flent = srs->srs_flent;
1877 	mac_ring_t	*mr;
1878 
1879 	ASSERT(MAC_PERIM_HELD((mac_handle_t)FLENT_TO_MIP(flent)));
1880 	ASSERT((srs->srs_type & SRST_TX) == 0);
1881 
1882 	/*
1883 	 * This handles a change in the number of SRSs between the quiesce and
1884 	 * and restart operation of a flow.
1885 	 */
1886 	if (!SRS_QUIESCED(srs))
1887 		return;
1888 
1889 	/*
1890 	 * Signal the SRS to restart itself. Wait for the restart to complete
1891 	 * Note that we only restart the SRS if it is not marked as
1892 	 * permanently quiesced.
1893 	 */
1894 	if (!SRS_QUIESCED_PERMANENT(srs)) {
1895 		mac_srs_signal(srs, SRS_RESTART);
1896 		mac_srs_quiesce_wait(srs, SRS_RESTART_DONE);
1897 		mac_srs_clear_flag(srs, SRS_RESTART_DONE);
1898 
1899 		mac_srs_client_poll_restart(srs->srs_mcip, srs);
1900 	}
1901 
1902 	/* Finally clear the flags to let the packets in */
1903 	mr = srs->srs_ring;
1904 	if (mr != NULL) {
1905 		MAC_RING_UNMARK(mr, MR_QUIESCE);
1906 		/* In case the ring was stopped, safely restart it */
1907 		(void) mac_start_ring(mr);
1908 	} else {
1909 		FLOW_UNMARK(flent, FE_QUIESCE);
1910 	}
1911 }
1912 
1913 /*
1914  * Temporary quiesce of a flow and associated Rx SRS.
1915  * Please see block comment above mac_rx_classify_flow_rem.
1916  */
1917 /* ARGSUSED */
1918 int
1919 mac_rx_classify_flow_quiesce(flow_entry_t *flent, void *arg)
1920 {
1921 	int		i;
1922 
1923 	for (i = 0; i < flent->fe_rx_srs_cnt; i++) {
1924 		mac_rx_srs_quiesce((mac_soft_ring_set_t *)flent->fe_rx_srs[i],
1925 		    SRS_QUIESCE);
1926 	}
1927 	return (0);
1928 }
1929 
1930 /*
1931  * Restart a flow and associated Rx SRS that has been quiesced temporarily
1932  * Please see block comment above mac_rx_classify_flow_rem
1933  */
1934 /* ARGSUSED */
1935 int
1936 mac_rx_classify_flow_restart(flow_entry_t *flent, void *arg)
1937 {
1938 	int		i;
1939 
1940 	for (i = 0; i < flent->fe_rx_srs_cnt; i++)
1941 		mac_rx_srs_restart((mac_soft_ring_set_t *)flent->fe_rx_srs[i]);
1942 
1943 	return (0);
1944 }
1945 
1946 void
1947 mac_srs_perm_quiesce(mac_client_handle_t mch, boolean_t on)
1948 {
1949 	mac_client_impl_t	*mcip = (mac_client_impl_t *)mch;
1950 	flow_entry_t		*flent = mcip->mci_flent;
1951 	mac_impl_t		*mip = mcip->mci_mip;
1952 	mac_soft_ring_set_t	*mac_srs;
1953 	int			i;
1954 
1955 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1956 
1957 	if (flent == NULL)
1958 		return;
1959 
1960 	for (i = 0; i < flent->fe_rx_srs_cnt; i++) {
1961 		mac_srs = flent->fe_rx_srs[i];
1962 		mutex_enter(&mac_srs->srs_lock);
1963 		if (on)
1964 			mac_srs->srs_state |= SRS_QUIESCE_PERM;
1965 		else
1966 			mac_srs->srs_state &= ~SRS_QUIESCE_PERM;
1967 		mutex_exit(&mac_srs->srs_lock);
1968 	}
1969 }
1970 
1971 void
1972 mac_rx_client_quiesce(mac_client_handle_t mch)
1973 {
1974 	mac_client_impl_t	*mcip = (mac_client_impl_t *)mch;
1975 	mac_impl_t		*mip = mcip->mci_mip;
1976 
1977 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1978 
1979 	if (MCIP_DATAPATH_SETUP(mcip)) {
1980 		(void) mac_rx_classify_flow_quiesce(mcip->mci_flent,
1981 		    NULL);
1982 		(void) mac_flow_walk_nolock(mcip->mci_subflow_tab,
1983 		    mac_rx_classify_flow_quiesce, NULL);
1984 	}
1985 }
1986 
1987 void
1988 mac_rx_client_restart(mac_client_handle_t mch)
1989 {
1990 	mac_client_impl_t	*mcip = (mac_client_impl_t *)mch;
1991 	mac_impl_t		*mip = mcip->mci_mip;
1992 
1993 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
1994 
1995 	if (MCIP_DATAPATH_SETUP(mcip)) {
1996 		(void) mac_rx_classify_flow_restart(mcip->mci_flent, NULL);
1997 		(void) mac_flow_walk_nolock(mcip->mci_subflow_tab,
1998 		    mac_rx_classify_flow_restart, NULL);
1999 	}
2000 }
2001 
2002 /*
2003  * This function only quiesces the Tx SRS and softring worker threads. Callers
2004  * need to make sure that there aren't any mac client threads doing current or
2005  * future transmits in the mac before calling this function.
2006  */
2007 void
2008 mac_tx_srs_quiesce(mac_soft_ring_set_t *srs, uint_t srs_quiesce_flag)
2009 {
2010 	mac_client_impl_t	*mcip = srs->srs_mcip;
2011 
2012 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
2013 
2014 	ASSERT(srs->srs_type & SRST_TX);
2015 	ASSERT(srs_quiesce_flag == SRS_CONDEMNED ||
2016 	    srs_quiesce_flag == SRS_QUIESCE);
2017 
2018 	/*
2019 	 * Signal the SRS to quiesce itself, and then cv_wait for the
2020 	 * SRS quiesce to complete. The SRS worker thread will wake us
2021 	 * up when the quiesce is complete
2022 	 */
2023 	mac_srs_signal(srs, srs_quiesce_flag);
2024 	mac_srs_quiesce_wait(srs, srs_quiesce_flag == SRS_QUIESCE ?
2025 	    SRS_QUIESCE_DONE : SRS_CONDEMNED_DONE);
2026 }
2027 
2028 void
2029 mac_tx_srs_restart(mac_soft_ring_set_t *srs)
2030 {
2031 	/*
2032 	 * Resizing the fanout could result in creation of new SRSs.
2033 	 * They may not necessarily be in the quiesced state in which
2034 	 * case it need be restarted
2035 	 */
2036 	if (!SRS_QUIESCED(srs))
2037 		return;
2038 
2039 	mac_srs_signal(srs, SRS_RESTART);
2040 	mac_srs_quiesce_wait(srs, SRS_RESTART_DONE);
2041 	mac_srs_clear_flag(srs, SRS_RESTART_DONE);
2042 }
2043 
2044 /*
2045  * Temporary quiesce of a flow and associated Rx SRS.
2046  * Please see block comment above mac_rx_srs_quiesce
2047  */
2048 /* ARGSUSED */
2049 int
2050 mac_tx_flow_quiesce(flow_entry_t *flent, void *arg)
2051 {
2052 	/*
2053 	 * The fe_tx_srs is null for a subflow on an interface that is
2054 	 * not plumbed
2055 	 */
2056 	if (flent->fe_tx_srs != NULL)
2057 		mac_tx_srs_quiesce(flent->fe_tx_srs, SRS_QUIESCE);
2058 	return (0);
2059 }
2060 
2061 /* ARGSUSED */
2062 int
2063 mac_tx_flow_restart(flow_entry_t *flent, void *arg)
2064 {
2065 	/*
2066 	 * The fe_tx_srs is null for a subflow on an interface that is
2067 	 * not plumbed
2068 	 */
2069 	if (flent->fe_tx_srs != NULL)
2070 		mac_tx_srs_restart(flent->fe_tx_srs);
2071 	return (0);
2072 }
2073 
2074 void
2075 mac_tx_client_quiesce(mac_client_impl_t *mcip, uint_t srs_quiesce_flag)
2076 {
2077 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
2078 
2079 	mac_tx_client_block(mcip);
2080 	if (MCIP_TX_SRS(mcip) != NULL) {
2081 		mac_tx_srs_quiesce(MCIP_TX_SRS(mcip), srs_quiesce_flag);
2082 		(void) mac_flow_walk_nolock(mcip->mci_subflow_tab,
2083 		    mac_tx_flow_quiesce, NULL);
2084 	}
2085 }
2086 
2087 void
2088 mac_tx_client_restart(mac_client_impl_t *mcip)
2089 {
2090 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
2091 
2092 	mac_tx_client_unblock(mcip);
2093 	if (MCIP_TX_SRS(mcip) != NULL) {
2094 		mac_tx_srs_restart(MCIP_TX_SRS(mcip));
2095 		(void) mac_flow_walk_nolock(mcip->mci_subflow_tab,
2096 		    mac_tx_flow_restart, NULL);
2097 	}
2098 }
2099 
2100 void
2101 mac_tx_client_flush(mac_client_impl_t *mcip)
2102 {
2103 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
2104 
2105 	mac_tx_client_quiesce(mcip, SRS_QUIESCE);
2106 	mac_tx_client_restart(mcip);
2107 }
2108 
2109 void
2110 mac_client_quiesce(mac_client_impl_t *mcip)
2111 {
2112 	mac_rx_client_quiesce((mac_client_handle_t)mcip);
2113 	mac_tx_client_quiesce(mcip, SRS_QUIESCE);
2114 }
2115 
2116 void
2117 mac_client_restart(mac_client_impl_t *mcip)
2118 {
2119 	mac_rx_client_restart((mac_client_handle_t)mcip);
2120 	mac_tx_client_restart(mcip);
2121 }
2122 
2123 /*
2124  * Allocate a minor number.
2125  */
2126 minor_t
2127 mac_minor_hold(boolean_t sleep)
2128 {
2129 	minor_t	minor;
2130 
2131 	/*
2132 	 * Grab a value from the arena.
2133 	 */
2134 	atomic_add_32(&minor_count, 1);
2135 
2136 	if (sleep)
2137 		minor = (uint_t)id_alloc(minor_ids);
2138 	else
2139 		minor = (uint_t)id_alloc_nosleep(minor_ids);
2140 
2141 	if (minor == 0) {
2142 		atomic_add_32(&minor_count, -1);
2143 		return (0);
2144 	}
2145 
2146 	return (minor);
2147 }
2148 
2149 /*
2150  * Release a previously allocated minor number.
2151  */
2152 void
2153 mac_minor_rele(minor_t minor)
2154 {
2155 	/*
2156 	 * Return the value to the arena.
2157 	 */
2158 	id_free(minor_ids, minor);
2159 	atomic_add_32(&minor_count, -1);
2160 }
2161 
2162 uint32_t
2163 mac_no_notification(mac_handle_t mh)
2164 {
2165 	mac_impl_t *mip = (mac_impl_t *)mh;
2166 
2167 	return (((mip->mi_state_flags & MIS_LEGACY) != 0) ?
2168 	    mip->mi_capab_legacy.ml_unsup_note : 0);
2169 }
2170 
2171 /*
2172  * Prevent any new opens of this mac in preparation for unregister
2173  */
2174 int
2175 i_mac_disable(mac_impl_t *mip)
2176 {
2177 	mac_client_impl_t	*mcip;
2178 
2179 	rw_enter(&i_mac_impl_lock, RW_WRITER);
2180 	if (mip->mi_state_flags & MIS_DISABLED) {
2181 		/* Already disabled, return success */
2182 		rw_exit(&i_mac_impl_lock);
2183 		return (0);
2184 	}
2185 	/*
2186 	 * See if there are any other references to this mac_t (e.g., VLAN's).
2187 	 * If so return failure. If all the other checks below pass, then
2188 	 * set mi_disabled atomically under the i_mac_impl_lock to prevent
2189 	 * any new VLAN's from being created or new mac client opens of this
2190 	 * mac end point.
2191 	 */
2192 	if (mip->mi_ref > 0) {
2193 		rw_exit(&i_mac_impl_lock);
2194 		return (EBUSY);
2195 	}
2196 
2197 	/*
2198 	 * mac clients must delete all multicast groups they join before
2199 	 * closing. bcast groups are reference counted, the last client
2200 	 * to delete the group will wait till the group is physically
2201 	 * deleted. Since all clients have closed this mac end point
2202 	 * mi_bcast_ngrps must be zero at this point
2203 	 */
2204 	ASSERT(mip->mi_bcast_ngrps == 0);
2205 
2206 	/*
2207 	 * Don't let go of this if it has some flows.
2208 	 * All other code guarantees no flows are added to a disabled
2209 	 * mac, therefore it is sufficient to check for the flow table
2210 	 * only here.
2211 	 */
2212 	mcip = mac_primary_client_handle(mip);
2213 	if ((mcip != NULL) && mac_link_has_flows((mac_client_handle_t)mcip)) {
2214 		rw_exit(&i_mac_impl_lock);
2215 		return (ENOTEMPTY);
2216 	}
2217 
2218 	mip->mi_state_flags |= MIS_DISABLED;
2219 	rw_exit(&i_mac_impl_lock);
2220 	return (0);
2221 }
2222 
2223 int
2224 mac_disable_nowait(mac_handle_t mh)
2225 {
2226 	mac_impl_t	*mip = (mac_impl_t *)mh;
2227 	int err;
2228 
2229 	if ((err = i_mac_perim_enter_nowait(mip)) != 0)
2230 		return (err);
2231 	err = i_mac_disable(mip);
2232 	i_mac_perim_exit(mip);
2233 	return (err);
2234 }
2235 
2236 int
2237 mac_disable(mac_handle_t mh)
2238 {
2239 	mac_impl_t	*mip = (mac_impl_t *)mh;
2240 	int err;
2241 
2242 	i_mac_perim_enter(mip);
2243 	err = i_mac_disable(mip);
2244 	i_mac_perim_exit(mip);
2245 
2246 	/*
2247 	 * Clean up notification thread and wait for it to exit.
2248 	 */
2249 	if (err == 0)
2250 		i_mac_notify_exit(mip);
2251 
2252 	return (err);
2253 }
2254 
2255 /*
2256  * Called when the MAC instance has a non empty flow table, to de-multiplex
2257  * incoming packets to the right flow.
2258  * The MAC's rw lock is assumed held as a READER.
2259  */
2260 /* ARGSUSED */
2261 static mblk_t *
2262 mac_rx_classify(mac_impl_t *mip, mac_resource_handle_t mrh, mblk_t *mp)
2263 {
2264 	flow_entry_t	*flent = NULL;
2265 	uint_t		flags = FLOW_INBOUND;
2266 	int		err;
2267 
2268 	/*
2269 	 * If the mac is a port of an aggregation, pass FLOW_IGNORE_VLAN
2270 	 * to mac_flow_lookup() so that the VLAN packets can be successfully
2271 	 * passed to the non-VLAN aggregation flows.
2272 	 *
2273 	 * Note that there is possibly a race between this and
2274 	 * mac_unicast_remove/add() and VLAN packets could be incorrectly
2275 	 * classified to non-VLAN flows of non-aggregation mac clients. These
2276 	 * VLAN packets will be then filtered out by the mac module.
2277 	 */
2278 	if ((mip->mi_state_flags & MIS_EXCLUSIVE) != 0)
2279 		flags |= FLOW_IGNORE_VLAN;
2280 
2281 	err = mac_flow_lookup(mip->mi_flow_tab, mp, flags, &flent);
2282 	if (err != 0) {
2283 		/* no registered receive function */
2284 		return (mp);
2285 	} else {
2286 		mac_client_impl_t	*mcip;
2287 
2288 		/*
2289 		 * This flent might just be an additional one on the MAC client,
2290 		 * i.e. for classification purposes (different fdesc), however
2291 		 * the resources, SRS et. al., are in the mci_flent, so if
2292 		 * this isn't the mci_flent, we need to get it.
2293 		 */
2294 		if ((mcip = flent->fe_mcip) != NULL &&
2295 		    mcip->mci_flent != flent) {
2296 			FLOW_REFRELE(flent);
2297 			flent = mcip->mci_flent;
2298 			FLOW_TRY_REFHOLD(flent, err);
2299 			if (err != 0)
2300 				return (mp);
2301 		}
2302 		(flent->fe_cb_fn)(flent->fe_cb_arg1, flent->fe_cb_arg2, mp,
2303 		    B_FALSE);
2304 		FLOW_REFRELE(flent);
2305 	}
2306 	return (NULL);
2307 }
2308 
2309 mblk_t *
2310 mac_rx_flow(mac_handle_t mh, mac_resource_handle_t mrh, mblk_t *mp_chain)
2311 {
2312 	mac_impl_t	*mip = (mac_impl_t *)mh;
2313 	mblk_t		*bp, *bp1, **bpp, *list = NULL;
2314 
2315 	/*
2316 	 * We walk the chain and attempt to classify each packet.
2317 	 * The packets that couldn't be classified will be returned
2318 	 * back to the caller.
2319 	 */
2320 	bp = mp_chain;
2321 	bpp = &list;
2322 	while (bp != NULL) {
2323 		bp1 = bp;
2324 		bp = bp->b_next;
2325 		bp1->b_next = NULL;
2326 
2327 		if (mac_rx_classify(mip, mrh, bp1) != NULL) {
2328 			*bpp = bp1;
2329 			bpp = &bp1->b_next;
2330 		}
2331 	}
2332 	return (list);
2333 }
2334 
2335 static int
2336 mac_tx_flow_srs_wakeup(flow_entry_t *flent, void *arg)
2337 {
2338 	mac_ring_handle_t ring = arg;
2339 
2340 	if (flent->fe_tx_srs)
2341 		mac_tx_srs_wakeup(flent->fe_tx_srs, ring);
2342 	return (0);
2343 }
2344 
2345 void
2346 i_mac_tx_srs_notify(mac_impl_t *mip, mac_ring_handle_t ring)
2347 {
2348 	mac_client_impl_t	*cclient;
2349 	mac_soft_ring_set_t	*mac_srs;
2350 
2351 	/*
2352 	 * After grabbing the mi_rw_lock, the list of clients can't change.
2353 	 * If there are any clients mi_disabled must be B_FALSE and can't
2354 	 * get set since there are clients. If there aren't any clients we
2355 	 * don't do anything. In any case the mip has to be valid. The driver
2356 	 * must make sure that it goes single threaded (with respect to mac
2357 	 * calls) and wait for all pending mac calls to finish before calling
2358 	 * mac_unregister.
2359 	 */
2360 	rw_enter(&i_mac_impl_lock, RW_READER);
2361 	if (mip->mi_state_flags & MIS_DISABLED) {
2362 		rw_exit(&i_mac_impl_lock);
2363 		return;
2364 	}
2365 
2366 	/*
2367 	 * Get MAC tx srs from walking mac_client_handle list.
2368 	 */
2369 	rw_enter(&mip->mi_rw_lock, RW_READER);
2370 	for (cclient = mip->mi_clients_list; cclient != NULL;
2371 	    cclient = cclient->mci_client_next) {
2372 		if ((mac_srs = MCIP_TX_SRS(cclient)) != NULL)
2373 			mac_tx_srs_wakeup(mac_srs, ring);
2374 		(void) mac_flow_walk(cclient->mci_subflow_tab,
2375 		    mac_tx_flow_srs_wakeup, ring);
2376 	}
2377 	rw_exit(&mip->mi_rw_lock);
2378 	rw_exit(&i_mac_impl_lock);
2379 }
2380 
2381 /* ARGSUSED */
2382 void
2383 mac_multicast_refresh(mac_handle_t mh, mac_multicst_t refresh, void *arg,
2384     boolean_t add)
2385 {
2386 	mac_impl_t *mip = (mac_impl_t *)mh;
2387 
2388 	i_mac_perim_enter((mac_impl_t *)mh);
2389 	/*
2390 	 * If no specific refresh function was given then default to the
2391 	 * driver's m_multicst entry point.
2392 	 */
2393 	if (refresh == NULL) {
2394 		refresh = mip->mi_multicst;
2395 		arg = mip->mi_driver;
2396 	}
2397 
2398 	mac_bcast_refresh(mip, refresh, arg, add);
2399 	i_mac_perim_exit((mac_impl_t *)mh);
2400 }
2401 
2402 void
2403 mac_promisc_refresh(mac_handle_t mh, mac_setpromisc_t refresh, void *arg)
2404 {
2405 	mac_impl_t	*mip = (mac_impl_t *)mh;
2406 
2407 	/*
2408 	 * If no specific refresh function was given then default to the
2409 	 * driver's m_promisc entry point.
2410 	 */
2411 	if (refresh == NULL) {
2412 		refresh = mip->mi_setpromisc;
2413 		arg = mip->mi_driver;
2414 	}
2415 	ASSERT(refresh != NULL);
2416 
2417 	/*
2418 	 * Call the refresh function with the current promiscuity.
2419 	 */
2420 	refresh(arg, (mip->mi_devpromisc != 0));
2421 }
2422 
2423 /*
2424  * The mac client requests that the mac not to change its margin size to
2425  * be less than the specified value.  If "current" is B_TRUE, then the client
2426  * requests the mac not to change its margin size to be smaller than the
2427  * current size. Further, return the current margin size value in this case.
2428  *
2429  * We keep every requested size in an ordered list from largest to smallest.
2430  */
2431 int
2432 mac_margin_add(mac_handle_t mh, uint32_t *marginp, boolean_t current)
2433 {
2434 	mac_impl_t		*mip = (mac_impl_t *)mh;
2435 	mac_margin_req_t	**pp, *p;
2436 	int			err = 0;
2437 
2438 	rw_enter(&(mip->mi_rw_lock), RW_WRITER);
2439 	if (current)
2440 		*marginp = mip->mi_margin;
2441 
2442 	/*
2443 	 * If the current margin value cannot satisfy the margin requested,
2444 	 * return ENOTSUP directly.
2445 	 */
2446 	if (*marginp > mip->mi_margin) {
2447 		err = ENOTSUP;
2448 		goto done;
2449 	}
2450 
2451 	/*
2452 	 * Check whether the given margin is already in the list. If so,
2453 	 * bump the reference count.
2454 	 */
2455 	for (pp = &mip->mi_mmrp; (p = *pp) != NULL; pp = &p->mmr_nextp) {
2456 		if (p->mmr_margin == *marginp) {
2457 			/*
2458 			 * The margin requested is already in the list,
2459 			 * so just bump the reference count.
2460 			 */
2461 			p->mmr_ref++;
2462 			goto done;
2463 		}
2464 		if (p->mmr_margin < *marginp)
2465 			break;
2466 	}
2467 
2468 
2469 	p = kmem_zalloc(sizeof (mac_margin_req_t), KM_SLEEP);
2470 	p->mmr_margin = *marginp;
2471 	p->mmr_ref++;
2472 	p->mmr_nextp = *pp;
2473 	*pp = p;
2474 
2475 done:
2476 	rw_exit(&(mip->mi_rw_lock));
2477 	return (err);
2478 }
2479 
2480 /*
2481  * The mac client requests to cancel its previous mac_margin_add() request.
2482  * We remove the requested margin size from the list.
2483  */
2484 int
2485 mac_margin_remove(mac_handle_t mh, uint32_t margin)
2486 {
2487 	mac_impl_t		*mip = (mac_impl_t *)mh;
2488 	mac_margin_req_t	**pp, *p;
2489 	int			err = 0;
2490 
2491 	rw_enter(&(mip->mi_rw_lock), RW_WRITER);
2492 	/*
2493 	 * Find the entry in the list for the given margin.
2494 	 */
2495 	for (pp = &(mip->mi_mmrp); (p = *pp) != NULL; pp = &(p->mmr_nextp)) {
2496 		if (p->mmr_margin == margin) {
2497 			if (--p->mmr_ref == 0)
2498 				break;
2499 
2500 			/*
2501 			 * There is still a reference to this address so
2502 			 * there's nothing more to do.
2503 			 */
2504 			goto done;
2505 		}
2506 	}
2507 
2508 	/*
2509 	 * We did not find an entry for the given margin.
2510 	 */
2511 	if (p == NULL) {
2512 		err = ENOENT;
2513 		goto done;
2514 	}
2515 
2516 	ASSERT(p->mmr_ref == 0);
2517 
2518 	/*
2519 	 * Remove it from the list.
2520 	 */
2521 	*pp = p->mmr_nextp;
2522 	kmem_free(p, sizeof (mac_margin_req_t));
2523 done:
2524 	rw_exit(&(mip->mi_rw_lock));
2525 	return (err);
2526 }
2527 
2528 boolean_t
2529 mac_margin_update(mac_handle_t mh, uint32_t margin)
2530 {
2531 	mac_impl_t	*mip = (mac_impl_t *)mh;
2532 	uint32_t	margin_needed = 0;
2533 
2534 	rw_enter(&(mip->mi_rw_lock), RW_WRITER);
2535 
2536 	if (mip->mi_mmrp != NULL)
2537 		margin_needed = mip->mi_mmrp->mmr_margin;
2538 
2539 	if (margin_needed <= margin)
2540 		mip->mi_margin = margin;
2541 
2542 	rw_exit(&(mip->mi_rw_lock));
2543 
2544 	if (margin_needed <= margin)
2545 		i_mac_notify(mip, MAC_NOTE_MARGIN);
2546 
2547 	return (margin_needed <= margin);
2548 }
2549 
2550 /*
2551  * MAC Type Plugin functions.
2552  */
2553 
2554 mactype_t *
2555 mactype_getplugin(const char *pname)
2556 {
2557 	mactype_t	*mtype = NULL;
2558 	boolean_t	tried_modload = B_FALSE;
2559 
2560 	mutex_enter(&i_mactype_lock);
2561 
2562 find_registered_mactype:
2563 	if (mod_hash_find(i_mactype_hash, (mod_hash_key_t)pname,
2564 	    (mod_hash_val_t *)&mtype) != 0) {
2565 		if (!tried_modload) {
2566 			/*
2567 			 * If the plugin has not yet been loaded, then
2568 			 * attempt to load it now.  If modload() succeeds,
2569 			 * the plugin should have registered using
2570 			 * mactype_register(), in which case we can go back
2571 			 * and attempt to find it again.
2572 			 */
2573 			if (modload(MACTYPE_KMODDIR, (char *)pname) != -1) {
2574 				tried_modload = B_TRUE;
2575 				goto find_registered_mactype;
2576 			}
2577 		}
2578 	} else {
2579 		/*
2580 		 * Note that there's no danger that the plugin we've loaded
2581 		 * could be unloaded between the modload() step and the
2582 		 * reference count bump here, as we're holding
2583 		 * i_mactype_lock, which mactype_unregister() also holds.
2584 		 */
2585 		atomic_inc_32(&mtype->mt_ref);
2586 	}
2587 
2588 	mutex_exit(&i_mactype_lock);
2589 	return (mtype);
2590 }
2591 
2592 mactype_register_t *
2593 mactype_alloc(uint_t mactype_version)
2594 {
2595 	mactype_register_t *mtrp;
2596 
2597 	/*
2598 	 * Make sure there isn't a version mismatch between the plugin and
2599 	 * the framework.  In the future, if multiple versions are
2600 	 * supported, this check could become more sophisticated.
2601 	 */
2602 	if (mactype_version != MACTYPE_VERSION)
2603 		return (NULL);
2604 
2605 	mtrp = kmem_zalloc(sizeof (mactype_register_t), KM_SLEEP);
2606 	mtrp->mtr_version = mactype_version;
2607 	return (mtrp);
2608 }
2609 
2610 void
2611 mactype_free(mactype_register_t *mtrp)
2612 {
2613 	kmem_free(mtrp, sizeof (mactype_register_t));
2614 }
2615 
2616 int
2617 mactype_register(mactype_register_t *mtrp)
2618 {
2619 	mactype_t	*mtp;
2620 	mactype_ops_t	*ops = mtrp->mtr_ops;
2621 
2622 	/* Do some sanity checking before we register this MAC type. */
2623 	if (mtrp->mtr_ident == NULL || ops == NULL)
2624 		return (EINVAL);
2625 
2626 	/*
2627 	 * Verify that all mandatory callbacks are set in the ops
2628 	 * vector.
2629 	 */
2630 	if (ops->mtops_unicst_verify == NULL ||
2631 	    ops->mtops_multicst_verify == NULL ||
2632 	    ops->mtops_sap_verify == NULL ||
2633 	    ops->mtops_header == NULL ||
2634 	    ops->mtops_header_info == NULL) {
2635 		return (EINVAL);
2636 	}
2637 
2638 	mtp = kmem_zalloc(sizeof (*mtp), KM_SLEEP);
2639 	mtp->mt_ident = mtrp->mtr_ident;
2640 	mtp->mt_ops = *ops;
2641 	mtp->mt_type = mtrp->mtr_mactype;
2642 	mtp->mt_nativetype = mtrp->mtr_nativetype;
2643 	mtp->mt_addr_length = mtrp->mtr_addrlen;
2644 	if (mtrp->mtr_brdcst_addr != NULL) {
2645 		mtp->mt_brdcst_addr = kmem_alloc(mtrp->mtr_addrlen, KM_SLEEP);
2646 		bcopy(mtrp->mtr_brdcst_addr, mtp->mt_brdcst_addr,
2647 		    mtrp->mtr_addrlen);
2648 	}
2649 
2650 	mtp->mt_stats = mtrp->mtr_stats;
2651 	mtp->mt_statcount = mtrp->mtr_statcount;
2652 
2653 	mtp->mt_mapping = mtrp->mtr_mapping;
2654 	mtp->mt_mappingcount = mtrp->mtr_mappingcount;
2655 
2656 	if (mod_hash_insert(i_mactype_hash,
2657 	    (mod_hash_key_t)mtp->mt_ident, (mod_hash_val_t)mtp) != 0) {
2658 		kmem_free(mtp->mt_brdcst_addr, mtp->mt_addr_length);
2659 		kmem_free(mtp, sizeof (*mtp));
2660 		return (EEXIST);
2661 	}
2662 	return (0);
2663 }
2664 
2665 int
2666 mactype_unregister(const char *ident)
2667 {
2668 	mactype_t	*mtp;
2669 	mod_hash_val_t	val;
2670 	int 		err;
2671 
2672 	/*
2673 	 * Let's not allow MAC drivers to use this plugin while we're
2674 	 * trying to unregister it.  Holding i_mactype_lock also prevents a
2675 	 * plugin from unregistering while a MAC driver is attempting to
2676 	 * hold a reference to it in i_mactype_getplugin().
2677 	 */
2678 	mutex_enter(&i_mactype_lock);
2679 
2680 	if ((err = mod_hash_find(i_mactype_hash, (mod_hash_key_t)ident,
2681 	    (mod_hash_val_t *)&mtp)) != 0) {
2682 		/* A plugin is trying to unregister, but it never registered. */
2683 		err = ENXIO;
2684 		goto done;
2685 	}
2686 
2687 	if (mtp->mt_ref != 0) {
2688 		err = EBUSY;
2689 		goto done;
2690 	}
2691 
2692 	err = mod_hash_remove(i_mactype_hash, (mod_hash_key_t)ident, &val);
2693 	ASSERT(err == 0);
2694 	if (err != 0) {
2695 		/* This should never happen, thus the ASSERT() above. */
2696 		err = EINVAL;
2697 		goto done;
2698 	}
2699 	ASSERT(mtp == (mactype_t *)val);
2700 
2701 	if (mtp->mt_brdcst_addr != NULL)
2702 		kmem_free(mtp->mt_brdcst_addr, mtp->mt_addr_length);
2703 	kmem_free(mtp, sizeof (mactype_t));
2704 done:
2705 	mutex_exit(&i_mactype_lock);
2706 	return (err);
2707 }
2708 
2709 /*
2710  * mac_set_prop() sets mac or hardware driver properties:
2711  * 	MAC resource properties include maxbw, priority, and cpu binding list.
2712  *	Driver properties are private properties to the hardware, such as mtu
2713  *	and speed.  There's one other MAC property -- the PVID.
2714  * If the property is a driver property, mac_set_prop() calls driver's callback
2715  * function to set it.
2716  * If the property is a mac resource property, mac_set_prop() invokes
2717  * mac_set_resources() which will cache the property value in mac_impl_t and
2718  * may call mac_client_set_resource() to update property value of the primary
2719  * mac client, if it exists.
2720  */
2721 int
2722 mac_set_prop(mac_handle_t mh, mac_prop_t *macprop, void *val, uint_t valsize)
2723 {
2724 	int err = ENOTSUP;
2725 	mac_impl_t *mip = (mac_impl_t *)mh;
2726 
2727 	ASSERT(MAC_PERIM_HELD(mh));
2728 
2729 	switch (macprop->mp_id) {
2730 	case MAC_PROP_MAXBW:
2731 	case MAC_PROP_PRIO:
2732 	case MAC_PROP_BIND_CPU: {
2733 		mac_resource_props_t mrp;
2734 
2735 		/* If it is mac property, call mac_set_resources() */
2736 		if (valsize < sizeof (mac_resource_props_t))
2737 			return (EINVAL);
2738 		bcopy(val, &mrp, sizeof (mrp));
2739 		err = mac_set_resources(mh, &mrp);
2740 		break;
2741 	}
2742 
2743 	case MAC_PROP_PVID:
2744 		if (valsize < sizeof (uint16_t) ||
2745 		    (mip->mi_state_flags & MIS_IS_VNIC))
2746 			return (EINVAL);
2747 		err = mac_set_pvid(mh, *(uint16_t *)val);
2748 		break;
2749 
2750 	case MAC_PROP_MTU: {
2751 		uint32_t mtu;
2752 
2753 		if (valsize < sizeof (mtu))
2754 			return (EINVAL);
2755 		bcopy(val, &mtu, sizeof (mtu));
2756 		err = mac_set_mtu(mh, mtu, NULL);
2757 		break;
2758 	}
2759 
2760 	case MAC_PROP_LLIMIT:
2761 	case MAC_PROP_LDECAY: {
2762 		uint32_t learnval;
2763 
2764 		if (valsize < sizeof (learnval) ||
2765 		    (mip->mi_state_flags & MIS_IS_VNIC))
2766 			return (EINVAL);
2767 		bcopy(val, &learnval, sizeof (learnval));
2768 		if (learnval == 0 && macprop->mp_id == MAC_PROP_LDECAY)
2769 			return (EINVAL);
2770 		if (macprop->mp_id == MAC_PROP_LLIMIT)
2771 			mip->mi_llimit = learnval;
2772 		else
2773 			mip->mi_ldecay = learnval;
2774 		err = 0;
2775 		break;
2776 	}
2777 
2778 	default:
2779 		/* For other driver properties, call driver's callback */
2780 		if (mip->mi_callbacks->mc_callbacks & MC_SETPROP) {
2781 			err = mip->mi_callbacks->mc_setprop(mip->mi_driver,
2782 			    macprop->mp_name, macprop->mp_id, valsize, val);
2783 		}
2784 	}
2785 	return (err);
2786 }
2787 
2788 /*
2789  * mac_get_prop() gets mac or hardware driver properties.
2790  *
2791  * If the property is a driver property, mac_get_prop() calls driver's callback
2792  * function to get it.
2793  * If the property is a mac property, mac_get_prop() invokes mac_get_resources()
2794  * which returns the cached value in mac_impl_t.
2795  */
2796 int
2797 mac_get_prop(mac_handle_t mh, mac_prop_t *macprop, void *val, uint_t valsize,
2798     uint_t *perm)
2799 {
2800 	int err = ENOTSUP;
2801 	mac_impl_t *mip = (mac_impl_t *)mh;
2802 	link_state_t link_state;
2803 	boolean_t is_getprop, is_setprop;
2804 
2805 	is_getprop = (mip->mi_callbacks->mc_callbacks & MC_GETPROP);
2806 	is_setprop = (mip->mi_callbacks->mc_callbacks & MC_SETPROP);
2807 
2808 	switch (macprop->mp_id) {
2809 	case MAC_PROP_MAXBW:
2810 	case MAC_PROP_PRIO:
2811 	case MAC_PROP_BIND_CPU: {
2812 		mac_resource_props_t mrp;
2813 
2814 		/* If mac property, read from cache */
2815 		if (valsize < sizeof (mac_resource_props_t))
2816 			return (EINVAL);
2817 		mac_get_resources(mh, &mrp);
2818 		bcopy(&mrp, val, sizeof (mac_resource_props_t));
2819 		return (0);
2820 	}
2821 
2822 	case MAC_PROP_PVID:
2823 		if (valsize < sizeof (uint16_t) ||
2824 		    (mip->mi_state_flags & MIS_IS_VNIC))
2825 			return (EINVAL);
2826 		*(uint16_t *)val = mac_get_pvid(mh);
2827 		return (0);
2828 
2829 	case MAC_PROP_LLIMIT:
2830 	case MAC_PROP_LDECAY:
2831 		if (valsize < sizeof (uint32_t) ||
2832 		    (mip->mi_state_flags & MIS_IS_VNIC))
2833 			return (EINVAL);
2834 		if (macprop->mp_id == MAC_PROP_LLIMIT)
2835 			bcopy(&mip->mi_llimit, val, sizeof (mip->mi_llimit));
2836 		else
2837 			bcopy(&mip->mi_ldecay, val, sizeof (mip->mi_ldecay));
2838 		return (0);
2839 
2840 	case MAC_PROP_MTU: {
2841 		uint32_t sdu;
2842 		mac_propval_range_t range;
2843 
2844 		if ((macprop->mp_flags & MAC_PROP_POSSIBLE) != 0) {
2845 			if (valsize < sizeof (mac_propval_range_t))
2846 				return (EINVAL);
2847 			if (is_getprop) {
2848 				err = mip->mi_callbacks->mc_getprop(mip->
2849 				    mi_driver, macprop->mp_name, macprop->mp_id,
2850 				    macprop->mp_flags, valsize, val, perm);
2851 			}
2852 			/*
2853 			 * If the driver doesn't have *_m_getprop defined or
2854 			 * if the driver doesn't support setting MTU then
2855 			 * return the CURRENT value as POSSIBLE value.
2856 			 */
2857 			if (!is_getprop || err == ENOTSUP) {
2858 				mac_sdu_get(mh, NULL, &sdu);
2859 				range.mpr_count = 1;
2860 				range.mpr_type = MAC_PROPVAL_UINT32;
2861 				range.range_uint32[0].mpur_min =
2862 				    range.range_uint32[0].mpur_max = sdu;
2863 				bcopy(&range, val, sizeof (range));
2864 				err = 0;
2865 			}
2866 			return (err);
2867 		}
2868 		if (valsize < sizeof (sdu))
2869 			return (EINVAL);
2870 		if ((macprop->mp_flags & MAC_PROP_DEFAULT) == 0) {
2871 			mac_sdu_get(mh, NULL, &sdu);
2872 			bcopy(&sdu, val, sizeof (sdu));
2873 			if (is_setprop && (mip->mi_callbacks->mc_setprop(mip->
2874 			    mi_driver, macprop->mp_name, macprop->mp_id,
2875 			    valsize, val) == 0)) {
2876 				*perm = MAC_PROP_PERM_RW;
2877 			} else {
2878 				*perm = MAC_PROP_PERM_READ;
2879 			}
2880 			return (0);
2881 		} else {
2882 			if (mip->mi_info.mi_media == DL_ETHER) {
2883 				sdu = ETHERMTU;
2884 				bcopy(&sdu, val, sizeof (sdu));
2885 
2886 				return (0);
2887 			}
2888 			/*
2889 			 * ask driver for its default.
2890 			 */
2891 			break;
2892 		}
2893 	}
2894 	case MAC_PROP_STATUS:
2895 		if (valsize < sizeof (link_state))
2896 			return (EINVAL);
2897 		*perm = MAC_PROP_PERM_READ;
2898 		link_state = mac_link_get(mh);
2899 		bcopy(&link_state, val, sizeof (link_state));
2900 		return (0);
2901 	default:
2902 		break;
2903 
2904 	}
2905 	/* If driver property, request from driver */
2906 	if (is_getprop) {
2907 		err = mip->mi_callbacks->mc_getprop(mip->mi_driver,
2908 		    macprop->mp_name, macprop->mp_id, macprop->mp_flags,
2909 		    valsize, val, perm);
2910 	}
2911 	return (err);
2912 }
2913 
2914 int
2915 mac_fastpath_disable(mac_handle_t mh)
2916 {
2917 	mac_impl_t	*mip = (mac_impl_t *)mh;
2918 
2919 	if ((mip->mi_state_flags & MIS_LEGACY) == 0)
2920 		return (0);
2921 
2922 	return (mip->mi_capab_legacy.ml_fastpath_disable(mip->mi_driver));
2923 }
2924 
2925 void
2926 mac_fastpath_enable(mac_handle_t mh)
2927 {
2928 	mac_impl_t	*mip = (mac_impl_t *)mh;
2929 
2930 	if ((mip->mi_state_flags & MIS_LEGACY) == 0)
2931 		return;
2932 
2933 	mip->mi_capab_legacy.ml_fastpath_enable(mip->mi_driver);
2934 }
2935 
2936 void
2937 mac_register_priv_prop(mac_impl_t *mip, mac_priv_prop_t *mpp, uint_t nprop)
2938 {
2939 	mac_priv_prop_t *mpriv;
2940 
2941 	if (mpp == NULL)
2942 		return;
2943 
2944 	mpriv = kmem_zalloc(nprop * sizeof (*mpriv), KM_SLEEP);
2945 	(void) memcpy(mpriv, mpp, nprop * sizeof (*mpriv));
2946 	mip->mi_priv_prop = mpriv;
2947 	mip->mi_priv_prop_count = nprop;
2948 }
2949 
2950 void
2951 mac_unregister_priv_prop(mac_impl_t *mip)
2952 {
2953 	mac_priv_prop_t	*mpriv;
2954 
2955 	mpriv = mip->mi_priv_prop;
2956 	if (mpriv != NULL) {
2957 		kmem_free(mpriv, mip->mi_priv_prop_count * sizeof (*mpriv));
2958 		mip->mi_priv_prop = NULL;
2959 	}
2960 	mip->mi_priv_prop_count = 0;
2961 }
2962 
2963 /*
2964  * mac_ring_t 'mr' macros. Some rogue drivers may access ring structure
2965  * (by invoking mac_rx()) even after processing mac_stop_ring(). In such
2966  * cases if MAC free's the ring structure after mac_stop_ring(), any
2967  * illegal access to the ring structure coming from the driver will panic
2968  * the system. In order to protect the system from such inadverent access,
2969  * we maintain a cache of rings in the mac_impl_t after they get free'd up.
2970  * When packets are received on free'd up rings, MAC (through the generation
2971  * count mechanism) will drop such packets.
2972  */
2973 static mac_ring_t *
2974 mac_ring_alloc(mac_impl_t *mip, mac_capab_rings_t *cap_rings)
2975 {
2976 	mac_ring_t *ring;
2977 
2978 	if (cap_rings->mr_type == MAC_RING_TYPE_RX) {
2979 		mutex_enter(&mip->mi_ring_lock);
2980 		if (mip->mi_ring_freelist != NULL) {
2981 			ring = mip->mi_ring_freelist;
2982 			mip->mi_ring_freelist = ring->mr_next;
2983 			bzero(ring, sizeof (mac_ring_t));
2984 		} else {
2985 			ring = kmem_cache_alloc(mac_ring_cache, KM_SLEEP);
2986 		}
2987 		mutex_exit(&mip->mi_ring_lock);
2988 	} else {
2989 		ring = kmem_zalloc(sizeof (mac_ring_t), KM_SLEEP);
2990 	}
2991 	ASSERT((ring != NULL) && (ring->mr_state == MR_FREE));
2992 	return (ring);
2993 }
2994 
2995 static void
2996 mac_ring_free(mac_impl_t *mip, mac_ring_t *ring)
2997 {
2998 	if (ring->mr_type == MAC_RING_TYPE_RX) {
2999 		mutex_enter(&mip->mi_ring_lock);
3000 		ring->mr_state = MR_FREE;
3001 		ring->mr_flag = 0;
3002 		ring->mr_next = mip->mi_ring_freelist;
3003 		mip->mi_ring_freelist = ring;
3004 		mutex_exit(&mip->mi_ring_lock);
3005 	} else {
3006 		kmem_free(ring, sizeof (mac_ring_t));
3007 	}
3008 }
3009 
3010 static void
3011 mac_ring_freeall(mac_impl_t *mip)
3012 {
3013 	mac_ring_t *ring_next;
3014 	mutex_enter(&mip->mi_ring_lock);
3015 	mac_ring_t *ring = mip->mi_ring_freelist;
3016 	while (ring != NULL) {
3017 		ring_next = ring->mr_next;
3018 		kmem_cache_free(mac_ring_cache, ring);
3019 		ring = ring_next;
3020 	}
3021 	mip->mi_ring_freelist = NULL;
3022 	mutex_exit(&mip->mi_ring_lock);
3023 }
3024 
3025 int
3026 mac_start_ring(mac_ring_t *ring)
3027 {
3028 	int rv = 0;
3029 
3030 	if (ring->mr_start != NULL)
3031 		rv = ring->mr_start(ring->mr_driver, ring->mr_gen_num);
3032 
3033 	return (rv);
3034 }
3035 
3036 void
3037 mac_stop_ring(mac_ring_t *ring)
3038 {
3039 	if (ring->mr_stop != NULL)
3040 		ring->mr_stop(ring->mr_driver);
3041 
3042 	/*
3043 	 * Increment the ring generation number for this ring.
3044 	 */
3045 	ring->mr_gen_num++;
3046 }
3047 
3048 int
3049 mac_start_group(mac_group_t *group)
3050 {
3051 	int rv = 0;
3052 
3053 	if (group->mrg_start != NULL)
3054 		rv = group->mrg_start(group->mrg_driver);
3055 
3056 	return (rv);
3057 }
3058 
3059 void
3060 mac_stop_group(mac_group_t *group)
3061 {
3062 	if (group->mrg_stop != NULL)
3063 		group->mrg_stop(group->mrg_driver);
3064 }
3065 
3066 /*
3067  * Called from mac_start() on the default Rx group. Broadcast and multicast
3068  * packets are received only on the default group. Hence the default group
3069  * needs to be up even if the primary client is not up, for the other groups
3070  * to be functional. We do this by calling this function at mac_start time
3071  * itself. However the broadcast packets that are received can't make their
3072  * way beyond mac_rx until a mac client creates a broadcast flow.
3073  */
3074 static int
3075 mac_start_group_and_rings(mac_group_t *group)
3076 {
3077 	mac_ring_t	*ring;
3078 	int		rv = 0;
3079 
3080 	ASSERT(group->mrg_state == MAC_GROUP_STATE_REGISTERED);
3081 	if ((rv = mac_start_group(group)) != 0)
3082 		return (rv);
3083 
3084 	for (ring = group->mrg_rings; ring != NULL; ring = ring->mr_next) {
3085 		ASSERT(ring->mr_state == MR_FREE);
3086 		if ((rv = mac_start_ring(ring)) != 0)
3087 			goto error;
3088 		ring->mr_state = MR_INUSE;
3089 		ring->mr_classify_type = MAC_SW_CLASSIFIER;
3090 	}
3091 	return (0);
3092 
3093 error:
3094 	mac_stop_group_and_rings(group);
3095 	return (rv);
3096 }
3097 
3098 /* Called from mac_stop on the default Rx group */
3099 static void
3100 mac_stop_group_and_rings(mac_group_t *group)
3101 {
3102 	mac_ring_t	*ring;
3103 
3104 	for (ring = group->mrg_rings; ring != NULL; ring = ring->mr_next) {
3105 		if (ring->mr_state != MR_FREE) {
3106 			mac_stop_ring(ring);
3107 			ring->mr_state = MR_FREE;
3108 			ring->mr_flag = 0;
3109 			ring->mr_classify_type = MAC_NO_CLASSIFIER;
3110 		}
3111 	}
3112 	mac_stop_group(group);
3113 }
3114 
3115 
3116 static mac_ring_t *
3117 mac_init_ring(mac_impl_t *mip, mac_group_t *group, int index,
3118     mac_capab_rings_t *cap_rings)
3119 {
3120 	mac_ring_t *ring;
3121 	mac_ring_info_t ring_info;
3122 
3123 	ring = mac_ring_alloc(mip, cap_rings);
3124 
3125 	/* Prepare basic information of ring */
3126 	ring->mr_index = index;
3127 	ring->mr_type = group->mrg_type;
3128 	ring->mr_gh = (mac_group_handle_t)group;
3129 
3130 	/* Insert the new ring to the list. */
3131 	ring->mr_next = group->mrg_rings;
3132 	group->mrg_rings = ring;
3133 
3134 	/* Zero to reuse the info data structure */
3135 	bzero(&ring_info, sizeof (ring_info));
3136 
3137 	/* Query ring information from driver */
3138 	cap_rings->mr_rget(mip->mi_driver, group->mrg_type, group->mrg_index,
3139 	    index, &ring_info, (mac_ring_handle_t)ring);
3140 
3141 	ring->mr_info = ring_info;
3142 
3143 	/* Update ring's status */
3144 	ring->mr_state = MR_FREE;
3145 	ring->mr_flag = 0;
3146 
3147 	/* Update the ring count of the group */
3148 	group->mrg_cur_count++;
3149 	return (ring);
3150 }
3151 
3152 /*
3153  * Rings are chained together for easy regrouping.
3154  */
3155 static void
3156 mac_init_group(mac_impl_t *mip, mac_group_t *group, int size,
3157     mac_capab_rings_t *cap_rings)
3158 {
3159 	int index;
3160 
3161 	/*
3162 	 * Initialize all ring members of this group. Size of zero will not
3163 	 * enter the loop, so it's safe for initializing an empty group.
3164 	 */
3165 	for (index = size - 1; index >= 0; index--)
3166 		(void) mac_init_ring(mip, group, index, cap_rings);
3167 }
3168 
3169 int
3170 mac_init_rings(mac_impl_t *mip, mac_ring_type_t rtype)
3171 {
3172 	mac_capab_rings_t *cap_rings;
3173 	mac_group_t *group, *groups;
3174 	mac_group_info_t group_info;
3175 	uint_t group_free = 0;
3176 	uint_t ring_left;
3177 	mac_ring_t *ring;
3178 	int g, err = 0;
3179 
3180 	switch (rtype) {
3181 	case MAC_RING_TYPE_RX:
3182 		ASSERT(mip->mi_rx_groups == NULL);
3183 
3184 		cap_rings = &mip->mi_rx_rings_cap;
3185 		cap_rings->mr_type = MAC_RING_TYPE_RX;
3186 		break;
3187 	case MAC_RING_TYPE_TX:
3188 		ASSERT(mip->mi_tx_groups == NULL);
3189 
3190 		cap_rings = &mip->mi_tx_rings_cap;
3191 		cap_rings->mr_type = MAC_RING_TYPE_TX;
3192 		break;
3193 	default:
3194 		ASSERT(B_FALSE);
3195 	}
3196 
3197 	if (!i_mac_capab_get((mac_handle_t)mip, MAC_CAPAB_RINGS,
3198 	    cap_rings))
3199 		return (0);
3200 
3201 	/*
3202 	 * Allocate a contiguous buffer for all groups.
3203 	 */
3204 	groups = kmem_zalloc(sizeof (mac_group_t) * (cap_rings->mr_gnum + 1),
3205 	    KM_SLEEP);
3206 
3207 	ring_left = cap_rings->mr_rnum;
3208 
3209 	/*
3210 	 * Get all ring groups if any, and get their ring members
3211 	 * if any.
3212 	 */
3213 	for (g = 0; g < cap_rings->mr_gnum; g++) {
3214 		group = groups + g;
3215 
3216 		/* Prepare basic information of the group */
3217 		group->mrg_index = g;
3218 		group->mrg_type = rtype;
3219 		group->mrg_state = MAC_GROUP_STATE_UNINIT;
3220 		group->mrg_mh = (mac_handle_t)mip;
3221 		group->mrg_next = group + 1;
3222 
3223 		/* Zero to reuse the info data structure */
3224 		bzero(&group_info, sizeof (group_info));
3225 
3226 		/* Query group information from driver */
3227 		cap_rings->mr_gget(mip->mi_driver, rtype, g, &group_info,
3228 		    (mac_group_handle_t)group);
3229 
3230 		switch (cap_rings->mr_group_type) {
3231 		case MAC_GROUP_TYPE_DYNAMIC:
3232 			if (cap_rings->mr_gaddring == NULL ||
3233 			    cap_rings->mr_gremring == NULL) {
3234 				DTRACE_PROBE3(
3235 				    mac__init__rings_no_addremring,
3236 				    char *, mip->mi_name,
3237 				    mac_group_add_ring_t,
3238 				    cap_rings->mr_gaddring,
3239 				    mac_group_add_ring_t,
3240 				    cap_rings->mr_gremring);
3241 				err = EINVAL;
3242 				goto bail;
3243 			}
3244 
3245 			switch (rtype) {
3246 			case MAC_RING_TYPE_RX:
3247 				/*
3248 				 * The first RX group must have non-zero
3249 				 * rings, and the following groups must
3250 				 * have zero rings.
3251 				 */
3252 				if (g == 0 && group_info.mgi_count == 0) {
3253 					DTRACE_PROBE1(
3254 					    mac__init__rings__rx__def__zero,
3255 					    char *, mip->mi_name);
3256 					err = EINVAL;
3257 					goto bail;
3258 				}
3259 				if (g > 0 && group_info.mgi_count != 0) {
3260 					DTRACE_PROBE3(
3261 					    mac__init__rings__rx__nonzero,
3262 					    char *, mip->mi_name,
3263 					    int, g, int, group_info.mgi_count);
3264 					err = EINVAL;
3265 					goto bail;
3266 				}
3267 				break;
3268 			case MAC_RING_TYPE_TX:
3269 				/*
3270 				 * All TX ring groups must have zero rings.
3271 				 */
3272 				if (group_info.mgi_count != 0) {
3273 					DTRACE_PROBE3(
3274 					    mac__init__rings__tx__nonzero,
3275 					    char *, mip->mi_name,
3276 					    int, g, int, group_info.mgi_count);
3277 					err = EINVAL;
3278 					goto bail;
3279 				}
3280 				break;
3281 			}
3282 			break;
3283 		case MAC_GROUP_TYPE_STATIC:
3284 			/*
3285 			 * Note that an empty group is allowed, e.g., an aggr
3286 			 * would start with an empty group.
3287 			 */
3288 			break;
3289 		default:
3290 			/* unknown group type */
3291 			DTRACE_PROBE2(mac__init__rings__unknown__type,
3292 			    char *, mip->mi_name,
3293 			    int, cap_rings->mr_group_type);
3294 			err = EINVAL;
3295 			goto bail;
3296 		}
3297 
3298 
3299 		/*
3300 		 * Driver must register group->mgi_addmac/remmac() for rx groups
3301 		 * to support multiple MAC addresses.
3302 		 */
3303 		if (rtype == MAC_RING_TYPE_RX) {
3304 			if ((group_info.mgi_addmac == NULL) ||
3305 			    (group_info.mgi_addmac == NULL))
3306 				goto bail;
3307 		}
3308 
3309 		/* Cache driver-supplied information */
3310 		group->mrg_info = group_info;
3311 
3312 		/* Update the group's status and group count. */
3313 		mac_set_rx_group_state(group, MAC_GROUP_STATE_REGISTERED);
3314 		group_free++;
3315 
3316 		group->mrg_rings = NULL;
3317 		group->mrg_cur_count = 0;
3318 		mac_init_group(mip, group, group_info.mgi_count, cap_rings);
3319 		ring_left -= group_info.mgi_count;
3320 
3321 		/* The current group size should be equal to default value */
3322 		ASSERT(group->mrg_cur_count == group_info.mgi_count);
3323 	}
3324 
3325 	/* Build up a dummy group for free resources as a pool */
3326 	group = groups + cap_rings->mr_gnum;
3327 
3328 	/* Prepare basic information of the group */
3329 	group->mrg_index = -1;
3330 	group->mrg_type = rtype;
3331 	group->mrg_state = MAC_GROUP_STATE_UNINIT;
3332 	group->mrg_mh = (mac_handle_t)mip;
3333 	group->mrg_next = NULL;
3334 
3335 	/*
3336 	 * If there are ungrouped rings, allocate a continuous buffer for
3337 	 * remaining resources.
3338 	 */
3339 	if (ring_left != 0) {
3340 		group->mrg_rings = NULL;
3341 		group->mrg_cur_count = 0;
3342 		mac_init_group(mip, group, ring_left, cap_rings);
3343 
3344 		/* The current group size should be equal to ring_left */
3345 		ASSERT(group->mrg_cur_count == ring_left);
3346 
3347 		ring_left = 0;
3348 
3349 		/* Update this group's status */
3350 		mac_set_rx_group_state(group, MAC_GROUP_STATE_REGISTERED);
3351 	} else
3352 		group->mrg_rings = NULL;
3353 
3354 	ASSERT(ring_left == 0);
3355 
3356 bail:
3357 	/* Cache other important information to finalize the initialization */
3358 	switch (rtype) {
3359 	case MAC_RING_TYPE_RX:
3360 		mip->mi_rx_group_type = cap_rings->mr_group_type;
3361 		mip->mi_rx_group_count = cap_rings->mr_gnum;
3362 		mip->mi_rx_groups = groups;
3363 		break;
3364 	case MAC_RING_TYPE_TX:
3365 		mip->mi_tx_group_type = cap_rings->mr_group_type;
3366 		mip->mi_tx_group_count = cap_rings->mr_gnum;
3367 		mip->mi_tx_group_free = group_free;
3368 		mip->mi_tx_groups = groups;
3369 
3370 		/*
3371 		 * Ring 0 is used as the default one and it could be assigned
3372 		 * to a client as well.
3373 		 */
3374 		group = groups + cap_rings->mr_gnum;
3375 		ring = group->mrg_rings;
3376 		while ((ring->mr_index != 0) && (ring->mr_next != NULL))
3377 			ring = ring->mr_next;
3378 		ASSERT(ring->mr_index == 0);
3379 		mip->mi_default_tx_ring = (mac_ring_handle_t)ring;
3380 		break;
3381 	default:
3382 		ASSERT(B_FALSE);
3383 	}
3384 
3385 	if (err != 0)
3386 		mac_free_rings(mip, rtype);
3387 
3388 	return (err);
3389 }
3390 
3391 /*
3392  * Called to free all ring groups with particular type. It's supposed all groups
3393  * have been released by clinet.
3394  */
3395 void
3396 mac_free_rings(mac_impl_t *mip, mac_ring_type_t rtype)
3397 {
3398 	mac_group_t *group, *groups;
3399 	uint_t group_count;
3400 
3401 	switch (rtype) {
3402 	case MAC_RING_TYPE_RX:
3403 		if (mip->mi_rx_groups == NULL)
3404 			return;
3405 
3406 		groups = mip->mi_rx_groups;
3407 		group_count = mip->mi_rx_group_count;
3408 
3409 		mip->mi_rx_groups = NULL;
3410 		mip->mi_rx_group_count = 0;
3411 		break;
3412 	case MAC_RING_TYPE_TX:
3413 		ASSERT(mip->mi_tx_group_count == mip->mi_tx_group_free);
3414 
3415 		if (mip->mi_tx_groups == NULL)
3416 			return;
3417 
3418 		groups = mip->mi_tx_groups;
3419 		group_count = mip->mi_tx_group_count;
3420 
3421 		mip->mi_tx_groups = NULL;
3422 		mip->mi_tx_group_count = 0;
3423 		mip->mi_tx_group_free = 0;
3424 		mip->mi_default_tx_ring = NULL;
3425 		break;
3426 	default:
3427 		ASSERT(B_FALSE);
3428 	}
3429 
3430 	for (group = groups; group != NULL; group = group->mrg_next) {
3431 		mac_ring_t *ring;
3432 
3433 		if (group->mrg_cur_count == 0)
3434 			continue;
3435 
3436 		ASSERT(group->mrg_rings != NULL);
3437 
3438 		while ((ring = group->mrg_rings) != NULL) {
3439 			group->mrg_rings = ring->mr_next;
3440 			mac_ring_free(mip, ring);
3441 		}
3442 	}
3443 
3444 	/* Free all the cached rings */
3445 	mac_ring_freeall(mip);
3446 	/* Free the block of group data strutures */
3447 	kmem_free(groups, sizeof (mac_group_t) * (group_count + 1));
3448 }
3449 
3450 /*
3451  * Associate a MAC address with a receive group.
3452  *
3453  * The return value of this function should always be checked properly, because
3454  * any type of failure could cause unexpected results. A group can be added
3455  * or removed with a MAC address only after it has been reserved. Ideally,
3456  * a successful reservation always leads to calling mac_group_addmac() to
3457  * steer desired traffic. Failure of adding an unicast MAC address doesn't
3458  * always imply that the group is functioning abnormally.
3459  *
3460  * Currently this function is called everywhere, and it reflects assumptions
3461  * about MAC addresses in the implementation. CR 6735196.
3462  */
3463 int
3464 mac_group_addmac(mac_group_t *group, const uint8_t *addr)
3465 {
3466 	ASSERT(group->mrg_type == MAC_RING_TYPE_RX);
3467 	ASSERT(group->mrg_info.mgi_addmac != NULL);
3468 
3469 	return (group->mrg_info.mgi_addmac(group->mrg_info.mgi_driver, addr));
3470 }
3471 
3472 /*
3473  * Remove the association between MAC address and receive group.
3474  */
3475 int
3476 mac_group_remmac(mac_group_t *group, const uint8_t *addr)
3477 {
3478 	ASSERT(group->mrg_type == MAC_RING_TYPE_RX);
3479 	ASSERT(group->mrg_info.mgi_remmac != NULL);
3480 
3481 	return (group->mrg_info.mgi_remmac(group->mrg_info.mgi_driver, addr));
3482 }
3483 
3484 /*
3485  * Release a ring in use by marking it MR_FREE.
3486  * Any other client may reserve it for its use.
3487  */
3488 void
3489 mac_release_tx_ring(mac_ring_handle_t rh)
3490 {
3491 	mac_ring_t *ring = (mac_ring_t *)rh;
3492 	mac_group_t *group = (mac_group_t *)ring->mr_gh;
3493 	mac_impl_t *mip = (mac_impl_t *)group->mrg_mh;
3494 
3495 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3496 	ASSERT(ring->mr_state != MR_FREE);
3497 
3498 	/*
3499 	 * Default tx ring will be released by mac_stop().
3500 	 */
3501 	if (rh == mip->mi_default_tx_ring)
3502 		return;
3503 
3504 	mac_stop_ring(ring);
3505 
3506 	ring->mr_state = MR_FREE;
3507 	ring->mr_flag = 0;
3508 }
3509 
3510 /*
3511  * This is the entry point for packets transmitted through the bridging code.
3512  * If no bridge is in place, MAC_RING_TX transmits using tx ring. The 'rh'
3513  * pointer may be NULL to select the default ring.
3514  */
3515 mblk_t *
3516 mac_bridge_tx(mac_impl_t *mip, mac_ring_handle_t rh, mblk_t *mp)
3517 {
3518 	mac_handle_t mh;
3519 
3520 	/*
3521 	 * Once we take a reference on the bridge link, the bridge
3522 	 * module itself can't unload, so the callback pointers are
3523 	 * stable.
3524 	 */
3525 	mutex_enter(&mip->mi_bridge_lock);
3526 	if ((mh = mip->mi_bridge_link) != NULL)
3527 		mac_bridge_ref_cb(mh, B_TRUE);
3528 	mutex_exit(&mip->mi_bridge_lock);
3529 	if (mh == NULL) {
3530 		MAC_RING_TX(mip, rh, mp, mp);
3531 	} else {
3532 		mp = mac_bridge_tx_cb(mh, rh, mp);
3533 		mac_bridge_ref_cb(mh, B_FALSE);
3534 	}
3535 
3536 	return (mp);
3537 }
3538 
3539 /*
3540  * Find a ring from its index.
3541  */
3542 mac_ring_t *
3543 mac_find_ring(mac_group_t *group, int index)
3544 {
3545 	mac_ring_t *ring = group->mrg_rings;
3546 
3547 	for (ring = group->mrg_rings; ring != NULL; ring = ring->mr_next)
3548 		if (ring->mr_index == index)
3549 			break;
3550 
3551 	return (ring);
3552 }
3553 /*
3554  * Add a ring to an existing group.
3555  *
3556  * The ring must be either passed directly (for example if the ring
3557  * movement is initiated by the framework), or specified through a driver
3558  * index (for example when the ring is added by the driver.
3559  *
3560  * The caller needs to call mac_perim_enter() before calling this function.
3561  */
3562 int
3563 i_mac_group_add_ring(mac_group_t *group, mac_ring_t *ring, int index)
3564 {
3565 	mac_impl_t *mip = (mac_impl_t *)group->mrg_mh;
3566 	mac_capab_rings_t *cap_rings;
3567 	boolean_t driver_call = (ring == NULL);
3568 	mac_group_type_t group_type;
3569 	int ret = 0;
3570 
3571 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3572 
3573 	switch (group->mrg_type) {
3574 	case MAC_RING_TYPE_RX:
3575 		cap_rings = &mip->mi_rx_rings_cap;
3576 		group_type = mip->mi_rx_group_type;
3577 		break;
3578 	case MAC_RING_TYPE_TX:
3579 		cap_rings = &mip->mi_tx_rings_cap;
3580 		group_type = mip->mi_tx_group_type;
3581 		break;
3582 	default:
3583 		ASSERT(B_FALSE);
3584 	}
3585 
3586 	/*
3587 	 * There should be no ring with the same ring index in the target
3588 	 * group.
3589 	 */
3590 	ASSERT(mac_find_ring(group, driver_call ? index : ring->mr_index) ==
3591 	    NULL);
3592 
3593 	if (driver_call) {
3594 		/*
3595 		 * The function is called as a result of a request from
3596 		 * a driver to add a ring to an existing group, for example
3597 		 * from the aggregation driver. Allocate a new mac_ring_t
3598 		 * for that ring.
3599 		 */
3600 		ring = mac_init_ring(mip, group, index, cap_rings);
3601 		ASSERT(group->mrg_state > MAC_GROUP_STATE_UNINIT);
3602 	} else {
3603 		/*
3604 		 * The function is called as a result of a MAC layer request
3605 		 * to add a ring to an existing group. In this case the
3606 		 * ring is being moved between groups, which requires
3607 		 * the underlying driver to support dynamic grouping,
3608 		 * and the mac_ring_t already exists.
3609 		 */
3610 		ASSERT(group_type == MAC_GROUP_TYPE_DYNAMIC);
3611 		ASSERT(cap_rings->mr_gaddring != NULL);
3612 		ASSERT(ring->mr_gh == NULL);
3613 	}
3614 
3615 	/*
3616 	 * At this point the ring should not be in use, and it should be
3617 	 * of the right for the target group.
3618 	 */
3619 	ASSERT(ring->mr_state < MR_INUSE);
3620 	ASSERT(ring->mr_srs == NULL);
3621 	ASSERT(ring->mr_type == group->mrg_type);
3622 
3623 	if (!driver_call) {
3624 		/*
3625 		 * Add the driver level hardware ring if the process was not
3626 		 * initiated by the driver, and the target group is not the
3627 		 * group.
3628 		 */
3629 		if (group->mrg_driver != NULL) {
3630 			cap_rings->mr_gaddring(group->mrg_driver,
3631 			    ring->mr_driver, ring->mr_type);
3632 		}
3633 
3634 		/*
3635 		 * Insert the ring ahead existing rings.
3636 		 */
3637 		ring->mr_next = group->mrg_rings;
3638 		group->mrg_rings = ring;
3639 		ring->mr_gh = (mac_group_handle_t)group;
3640 		group->mrg_cur_count++;
3641 	}
3642 
3643 	/*
3644 	 * If the group has not been actively used, we're done.
3645 	 */
3646 	if (group->mrg_index != -1 &&
3647 	    group->mrg_state < MAC_GROUP_STATE_RESERVED)
3648 		return (0);
3649 
3650 	/*
3651 	 * Set up SRS/SR according to the ring type.
3652 	 */
3653 	switch (ring->mr_type) {
3654 	case MAC_RING_TYPE_RX:
3655 		/*
3656 		 * Setup SRS on top of the new ring if the group is
3657 		 * reserved for someones exclusive use.
3658 		 */
3659 		if (group->mrg_state == MAC_GROUP_STATE_RESERVED) {
3660 			flow_entry_t *flent;
3661 			mac_client_impl_t *mcip;
3662 
3663 			mcip = MAC_RX_GROUP_ONLY_CLIENT(group);
3664 			ASSERT(mcip != NULL);
3665 			flent = mcip->mci_flent;
3666 			ASSERT(flent->fe_rx_srs_cnt > 0);
3667 			mac_srs_group_setup(mcip, flent, group, SRST_LINK);
3668 		}
3669 		break;
3670 	case MAC_RING_TYPE_TX:
3671 		/*
3672 		 * For TX this function is only invoked during the
3673 		 * initial creation of a group when a share is
3674 		 * associated with a MAC client. So the datapath is not
3675 		 * yet setup, and will be setup later after the
3676 		 * group has been reserved and populated.
3677 		 */
3678 		break;
3679 	default:
3680 		ASSERT(B_FALSE);
3681 	}
3682 
3683 	/*
3684 	 * Start the ring if needed. Failure causes to undo the grouping action.
3685 	 */
3686 	if ((ret = mac_start_ring(ring)) != 0) {
3687 		if (ring->mr_type == MAC_RING_TYPE_RX) {
3688 			if (ring->mr_srs != NULL) {
3689 				mac_rx_srs_remove(ring->mr_srs);
3690 				ring->mr_srs = NULL;
3691 			}
3692 		}
3693 		if (!driver_call) {
3694 			cap_rings->mr_gremring(group->mrg_driver,
3695 			    ring->mr_driver, ring->mr_type);
3696 		}
3697 		group->mrg_cur_count--;
3698 		group->mrg_rings = ring->mr_next;
3699 
3700 		ring->mr_gh = NULL;
3701 
3702 		if (driver_call)
3703 			mac_ring_free(mip, ring);
3704 
3705 		return (ret);
3706 	}
3707 
3708 	/*
3709 	 * Update the ring's state.
3710 	 */
3711 	ring->mr_state = MR_INUSE;
3712 	MAC_RING_UNMARK(ring, MR_INCIPIENT);
3713 	return (0);
3714 }
3715 
3716 /*
3717  * Remove a ring from it's current group. MAC internal function for dynamic
3718  * grouping.
3719  *
3720  * The caller needs to call mac_perim_enter() before calling this function.
3721  */
3722 void
3723 i_mac_group_rem_ring(mac_group_t *group, mac_ring_t *ring,
3724     boolean_t driver_call)
3725 {
3726 	mac_impl_t *mip = (mac_impl_t *)group->mrg_mh;
3727 	mac_capab_rings_t *cap_rings = NULL;
3728 	mac_group_type_t group_type;
3729 
3730 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3731 
3732 	ASSERT(mac_find_ring(group, ring->mr_index) == ring);
3733 	ASSERT((mac_group_t *)ring->mr_gh == group);
3734 	ASSERT(ring->mr_type == group->mrg_type);
3735 
3736 	switch (ring->mr_type) {
3737 	case MAC_RING_TYPE_RX:
3738 		group_type = mip->mi_rx_group_type;
3739 		cap_rings = &mip->mi_rx_rings_cap;
3740 
3741 		if (group->mrg_state >= MAC_GROUP_STATE_RESERVED)
3742 			mac_stop_ring(ring);
3743 
3744 		/*
3745 		 * Only hardware classified packets hold a reference to the
3746 		 * ring all the way up the Rx path. mac_rx_srs_remove()
3747 		 * will take care of quiescing the Rx path and removing the
3748 		 * SRS. The software classified path neither holds a reference
3749 		 * nor any association with the ring in mac_rx.
3750 		 */
3751 		if (ring->mr_srs != NULL) {
3752 			mac_rx_srs_remove(ring->mr_srs);
3753 			ring->mr_srs = NULL;
3754 		}
3755 		ring->mr_state = MR_FREE;
3756 		ring->mr_flag = 0;
3757 
3758 		break;
3759 	case MAC_RING_TYPE_TX:
3760 		/*
3761 		 * For TX this function is only invoked in two
3762 		 * cases:
3763 		 *
3764 		 * 1) In the case of a failure during the
3765 		 * initial creation of a group when a share is
3766 		 * associated with a MAC client. So the SRS is not
3767 		 * yet setup, and will be setup later after the
3768 		 * group has been reserved and populated.
3769 		 *
3770 		 * 2) From mac_release_tx_group() when freeing
3771 		 * a TX SRS.
3772 		 *
3773 		 * In both cases the SRS and its soft rings are
3774 		 * already quiesced.
3775 		 */
3776 		ASSERT(!driver_call);
3777 		group_type = mip->mi_tx_group_type;
3778 		cap_rings = &mip->mi_tx_rings_cap;
3779 		break;
3780 	default:
3781 		ASSERT(B_FALSE);
3782 	}
3783 
3784 	/*
3785 	 * Remove the ring from the group.
3786 	 */
3787 	if (ring == group->mrg_rings)
3788 		group->mrg_rings = ring->mr_next;
3789 	else {
3790 		mac_ring_t *pre;
3791 
3792 		pre = group->mrg_rings;
3793 		while (pre->mr_next != ring)
3794 			pre = pre->mr_next;
3795 		pre->mr_next = ring->mr_next;
3796 	}
3797 	group->mrg_cur_count--;
3798 
3799 	if (!driver_call) {
3800 		ASSERT(group_type == MAC_GROUP_TYPE_DYNAMIC);
3801 		ASSERT(cap_rings->mr_gremring != NULL);
3802 
3803 		/*
3804 		 * Remove the driver level hardware ring.
3805 		 */
3806 		if (group->mrg_driver != NULL) {
3807 			cap_rings->mr_gremring(group->mrg_driver,
3808 			    ring->mr_driver, ring->mr_type);
3809 		}
3810 	}
3811 
3812 	ring->mr_gh = NULL;
3813 	if (driver_call) {
3814 		mac_ring_free(mip, ring);
3815 	} else {
3816 		ring->mr_state = MR_FREE;
3817 		ring->mr_flag = 0;
3818 	}
3819 }
3820 
3821 /*
3822  * Move a ring to the target group. If needed, remove the ring from the group
3823  * that it currently belongs to.
3824  *
3825  * The caller need to enter MAC's perimeter by calling mac_perim_enter().
3826  */
3827 static int
3828 mac_group_mov_ring(mac_impl_t *mip, mac_group_t *d_group, mac_ring_t *ring)
3829 {
3830 	mac_group_t *s_group = (mac_group_t *)ring->mr_gh;
3831 	int rv;
3832 
3833 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3834 	ASSERT(d_group != NULL);
3835 	ASSERT(s_group->mrg_mh == d_group->mrg_mh);
3836 
3837 	if (s_group == d_group)
3838 		return (0);
3839 
3840 	/*
3841 	 * Remove it from current group first.
3842 	 */
3843 	if (s_group != NULL)
3844 		i_mac_group_rem_ring(s_group, ring, B_FALSE);
3845 
3846 	/*
3847 	 * Add it to the new group.
3848 	 */
3849 	rv = i_mac_group_add_ring(d_group, ring, 0);
3850 	if (rv != 0) {
3851 		/*
3852 		 * Failed to add ring back to source group. If
3853 		 * that fails, the ring is stuck in limbo, log message.
3854 		 */
3855 		if (i_mac_group_add_ring(s_group, ring, 0)) {
3856 			cmn_err(CE_WARN, "%s: failed to move ring %p\n",
3857 			    mip->mi_name, (void *)ring);
3858 		}
3859 	}
3860 
3861 	return (rv);
3862 }
3863 
3864 /*
3865  * Find a MAC address according to its value.
3866  */
3867 mac_address_t *
3868 mac_find_macaddr(mac_impl_t *mip, uint8_t *mac_addr)
3869 {
3870 	mac_address_t *map;
3871 
3872 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3873 
3874 	for (map = mip->mi_addresses; map != NULL; map = map->ma_next) {
3875 		if (bcmp(mac_addr, map->ma_addr, map->ma_len) == 0)
3876 			break;
3877 	}
3878 
3879 	return (map);
3880 }
3881 
3882 /*
3883  * Check whether the MAC address is shared by multiple clients.
3884  */
3885 boolean_t
3886 mac_check_macaddr_shared(mac_address_t *map)
3887 {
3888 	ASSERT(MAC_PERIM_HELD((mac_handle_t)map->ma_mip));
3889 
3890 	return (map->ma_nusers > 1);
3891 }
3892 
3893 /*
3894  * Remove the specified MAC address from the MAC address list and free it.
3895  */
3896 static void
3897 mac_free_macaddr(mac_address_t *map)
3898 {
3899 	mac_impl_t *mip = map->ma_mip;
3900 
3901 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3902 	ASSERT(mip->mi_addresses != NULL);
3903 
3904 	map = mac_find_macaddr(mip, map->ma_addr);
3905 
3906 	ASSERT(map != NULL);
3907 	ASSERT(map->ma_nusers == 0);
3908 
3909 	if (map == mip->mi_addresses) {
3910 		mip->mi_addresses = map->ma_next;
3911 	} else {
3912 		mac_address_t *pre;
3913 
3914 		pre = mip->mi_addresses;
3915 		while (pre->ma_next != map)
3916 			pre = pre->ma_next;
3917 		pre->ma_next = map->ma_next;
3918 	}
3919 
3920 	kmem_free(map, sizeof (mac_address_t));
3921 }
3922 
3923 /*
3924  * Add a MAC address reference for a client. If the desired MAC address
3925  * exists, add a reference to it. Otherwise, add the new address by adding
3926  * it to a reserved group or setting promiscuous mode. Won't try different
3927  * group is the group is non-NULL, so the caller must explictly share
3928  * default group when needed.
3929  *
3930  * Note, the primary MAC address is initialized at registration time, so
3931  * to add it to default group only need to activate it if its reference
3932  * count is still zero. Also, some drivers may not have advertised RINGS
3933  * capability.
3934  */
3935 int
3936 mac_add_macaddr(mac_impl_t *mip, mac_group_t *group, uint8_t *mac_addr,
3937     boolean_t use_hw)
3938 {
3939 	mac_address_t *map;
3940 	int err = 0;
3941 	boolean_t allocated_map = B_FALSE;
3942 
3943 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
3944 
3945 	map = mac_find_macaddr(mip, mac_addr);
3946 
3947 	/*
3948 	 * If the new MAC address has not been added. Allocate a new one
3949 	 * and set it up.
3950 	 */
3951 	if (map == NULL) {
3952 		map = kmem_zalloc(sizeof (mac_address_t), KM_SLEEP);
3953 		map->ma_len = mip->mi_type->mt_addr_length;
3954 		bcopy(mac_addr, map->ma_addr, map->ma_len);
3955 		map->ma_nusers = 0;
3956 		map->ma_group = group;
3957 		map->ma_mip = mip;
3958 
3959 		/* add the new MAC address to the head of the address list */
3960 		map->ma_next = mip->mi_addresses;
3961 		mip->mi_addresses = map;
3962 
3963 		allocated_map = B_TRUE;
3964 	}
3965 
3966 	ASSERT(map->ma_group == group);
3967 
3968 	/*
3969 	 * If the MAC address is already in use, simply account for the
3970 	 * new client.
3971 	 */
3972 	if (map->ma_nusers++ > 0)
3973 		return (0);
3974 
3975 	/*
3976 	 * Activate this MAC address by adding it to the reserved group.
3977 	 */
3978 	if (group != NULL) {
3979 		err = mac_group_addmac(group, (const uint8_t *)mac_addr);
3980 		if (err == 0) {
3981 			map->ma_type = MAC_ADDRESS_TYPE_UNICAST_CLASSIFIED;
3982 			return (0);
3983 		}
3984 	}
3985 
3986 	/*
3987 	 * The MAC address addition failed. If the client requires a
3988 	 * hardware classified MAC address, fail the operation.
3989 	 */
3990 	if (use_hw) {
3991 		err = ENOSPC;
3992 		goto bail;
3993 	}
3994 
3995 	/*
3996 	 * Try promiscuous mode.
3997 	 *
3998 	 * For drivers that don't advertise RINGS capability, do
3999 	 * nothing for the primary address.
4000 	 */
4001 	if ((group == NULL) &&
4002 	    (bcmp(map->ma_addr, mip->mi_addr, map->ma_len) == 0)) {
4003 		map->ma_type = MAC_ADDRESS_TYPE_UNICAST_CLASSIFIED;
4004 		return (0);
4005 	}
4006 
4007 	/*
4008 	 * Enable promiscuous mode in order to receive traffic
4009 	 * to the new MAC address.
4010 	 */
4011 	if ((err = i_mac_promisc_set(mip, B_TRUE)) == 0) {
4012 		map->ma_type = MAC_ADDRESS_TYPE_UNICAST_PROMISC;
4013 		return (0);
4014 	}
4015 
4016 	/*
4017 	 * Free the MAC address that could not be added. Don't free
4018 	 * a pre-existing address, it could have been the entry
4019 	 * for the primary MAC address which was pre-allocated by
4020 	 * mac_init_macaddr(), and which must remain on the list.
4021 	 */
4022 bail:
4023 	map->ma_nusers--;
4024 	if (allocated_map)
4025 		mac_free_macaddr(map);
4026 	return (err);
4027 }
4028 
4029 /*
4030  * Remove a reference to a MAC address. This may cause to remove the MAC
4031  * address from an associated group or to turn off promiscuous mode.
4032  * The caller needs to handle the failure properly.
4033  */
4034 int
4035 mac_remove_macaddr(mac_address_t *map)
4036 {
4037 	mac_impl_t *mip = map->ma_mip;
4038 	int err = 0;
4039 
4040 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
4041 
4042 	ASSERT(map == mac_find_macaddr(mip, map->ma_addr));
4043 
4044 	/*
4045 	 * If it's not the last client using this MAC address, only update
4046 	 * the MAC clients count.
4047 	 */
4048 	if (--map->ma_nusers > 0)
4049 		return (0);
4050 
4051 	/*
4052 	 * The MAC address is no longer used by any MAC client, so remove
4053 	 * it from its associated group, or turn off promiscuous mode
4054 	 * if it was enabled for the MAC address.
4055 	 */
4056 	switch (map->ma_type) {
4057 	case MAC_ADDRESS_TYPE_UNICAST_CLASSIFIED:
4058 		/*
4059 		 * Don't free the preset primary address for drivers that
4060 		 * don't advertise RINGS capability.
4061 		 */
4062 		if (map->ma_group == NULL)
4063 			return (0);
4064 
4065 		err = mac_group_remmac(map->ma_group, map->ma_addr);
4066 		break;
4067 	case MAC_ADDRESS_TYPE_UNICAST_PROMISC:
4068 		err = i_mac_promisc_set(mip, B_FALSE);
4069 		break;
4070 	default:
4071 		ASSERT(B_FALSE);
4072 	}
4073 
4074 	if (err != 0)
4075 		return (err);
4076 
4077 	/*
4078 	 * We created MAC address for the primary one at registration, so we
4079 	 * won't free it here. mac_fini_macaddr() will take care of it.
4080 	 */
4081 	if (bcmp(map->ma_addr, mip->mi_addr, map->ma_len) != 0)
4082 		mac_free_macaddr(map);
4083 
4084 	return (0);
4085 }
4086 
4087 /*
4088  * Update an existing MAC address. The caller need to make sure that the new
4089  * value has not been used.
4090  */
4091 int
4092 mac_update_macaddr(mac_address_t *map, uint8_t *mac_addr)
4093 {
4094 	mac_impl_t *mip = map->ma_mip;
4095 	int err = 0;
4096 
4097 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
4098 	ASSERT(mac_find_macaddr(mip, mac_addr) == NULL);
4099 
4100 	switch (map->ma_type) {
4101 	case MAC_ADDRESS_TYPE_UNICAST_CLASSIFIED:
4102 		/*
4103 		 * Update the primary address for drivers that are not
4104 		 * RINGS capable.
4105 		 */
4106 		if (map->ma_group == NULL) {
4107 			err = mip->mi_unicst(mip->mi_driver, (const uint8_t *)
4108 			    mac_addr);
4109 			if (err != 0)
4110 				return (err);
4111 			break;
4112 		}
4113 
4114 		/*
4115 		 * If this MAC address is not currently in use,
4116 		 * simply break out and update the value.
4117 		 */
4118 		if (map->ma_nusers == 0)
4119 			break;
4120 
4121 		/*
4122 		 * Need to replace the MAC address associated with a group.
4123 		 */
4124 		err = mac_group_remmac(map->ma_group, map->ma_addr);
4125 		if (err != 0)
4126 			return (err);
4127 
4128 		err = mac_group_addmac(map->ma_group, mac_addr);
4129 
4130 		/*
4131 		 * Failure hints hardware error. The MAC layer needs to
4132 		 * have error notification facility to handle this.
4133 		 * Now, simply try to restore the value.
4134 		 */
4135 		if (err != 0)
4136 			(void) mac_group_addmac(map->ma_group, map->ma_addr);
4137 
4138 		break;
4139 	case MAC_ADDRESS_TYPE_UNICAST_PROMISC:
4140 		/*
4141 		 * Need to do nothing more if in promiscuous mode.
4142 		 */
4143 		break;
4144 	default:
4145 		ASSERT(B_FALSE);
4146 	}
4147 
4148 	/*
4149 	 * Successfully replaced the MAC address.
4150 	 */
4151 	if (err == 0)
4152 		bcopy(mac_addr, map->ma_addr, map->ma_len);
4153 
4154 	return (err);
4155 }
4156 
4157 /*
4158  * Freshen the MAC address with new value. Its caller must have updated the
4159  * hardware MAC address before calling this function.
4160  * This funcitons is supposed to be used to handle the MAC address change
4161  * notification from underlying drivers.
4162  */
4163 void
4164 mac_freshen_macaddr(mac_address_t *map, uint8_t *mac_addr)
4165 {
4166 	mac_impl_t *mip = map->ma_mip;
4167 
4168 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
4169 	ASSERT(mac_find_macaddr(mip, mac_addr) == NULL);
4170 
4171 	/*
4172 	 * Freshen the MAC address with new value.
4173 	 */
4174 	bcopy(mac_addr, map->ma_addr, map->ma_len);
4175 	bcopy(mac_addr, mip->mi_addr, map->ma_len);
4176 
4177 	/*
4178 	 * Update all MAC clients that share this MAC address.
4179 	 */
4180 	mac_unicast_update_clients(mip, map);
4181 }
4182 
4183 /*
4184  * Set up the primary MAC address.
4185  */
4186 void
4187 mac_init_macaddr(mac_impl_t *mip)
4188 {
4189 	mac_address_t *map;
4190 
4191 	/*
4192 	 * The reference count is initialized to zero, until it's really
4193 	 * activated.
4194 	 */
4195 	map = kmem_zalloc(sizeof (mac_address_t), KM_SLEEP);
4196 	map->ma_len = mip->mi_type->mt_addr_length;
4197 	bcopy(mip->mi_addr, map->ma_addr, map->ma_len);
4198 
4199 	/*
4200 	 * If driver advertises RINGS capability, it shouldn't have initialized
4201 	 * its primary MAC address. For other drivers, including VNIC, the
4202 	 * primary address must work after registration.
4203 	 */
4204 	if (mip->mi_rx_groups == NULL)
4205 		map->ma_type = MAC_ADDRESS_TYPE_UNICAST_CLASSIFIED;
4206 
4207 	/*
4208 	 * The primary MAC address is reserved for default group according
4209 	 * to current design.
4210 	 */
4211 	map->ma_group = mip->mi_rx_groups;
4212 	map->ma_mip = mip;
4213 
4214 	mip->mi_addresses = map;
4215 }
4216 
4217 /*
4218  * Clean up the primary MAC address. Note, only one primary MAC address
4219  * is allowed. All other MAC addresses must have been freed appropriately.
4220  */
4221 void
4222 mac_fini_macaddr(mac_impl_t *mip)
4223 {
4224 	mac_address_t *map = mip->mi_addresses;
4225 
4226 	if (map == NULL)
4227 		return;
4228 
4229 	/*
4230 	 * If mi_addresses is initialized, there should be exactly one
4231 	 * entry left on the list with no users.
4232 	 */
4233 	ASSERT(map->ma_nusers == 0);
4234 	ASSERT(map->ma_next == NULL);
4235 
4236 	kmem_free(map, sizeof (mac_address_t));
4237 	mip->mi_addresses = NULL;
4238 }
4239 
4240 /*
4241  * Logging related functions.
4242  */
4243 
4244 /* Write the Flow description to the log file */
4245 int
4246 mac_write_flow_desc(flow_entry_t *flent, mac_client_impl_t *mcip)
4247 {
4248 	flow_desc_t		*fdesc;
4249 	mac_resource_props_t	*mrp;
4250 	net_desc_t		ndesc;
4251 
4252 	bzero(&ndesc, sizeof (net_desc_t));
4253 
4254 	/*
4255 	 * Grab the fe_lock to see a self-consistent fe_flow_desc.
4256 	 * Updates to the fe_flow_desc are done under the fe_lock
4257 	 */
4258 	mutex_enter(&flent->fe_lock);
4259 	fdesc = &flent->fe_flow_desc;
4260 	mrp = &flent->fe_resource_props;
4261 
4262 	ndesc.nd_name = flent->fe_flow_name;
4263 	ndesc.nd_devname = mcip->mci_name;
4264 	bcopy(fdesc->fd_src_mac, ndesc.nd_ehost, ETHERADDRL);
4265 	bcopy(fdesc->fd_dst_mac, ndesc.nd_edest, ETHERADDRL);
4266 	ndesc.nd_sap = htonl(fdesc->fd_sap);
4267 	ndesc.nd_isv4 = (uint8_t)fdesc->fd_ipversion == IPV4_VERSION;
4268 	ndesc.nd_bw_limit = mrp->mrp_maxbw;
4269 	if (ndesc.nd_isv4) {
4270 		ndesc.nd_saddr[3] = htonl(fdesc->fd_local_addr.s6_addr32[3]);
4271 		ndesc.nd_daddr[3] = htonl(fdesc->fd_remote_addr.s6_addr32[3]);
4272 	} else {
4273 		bcopy(&fdesc->fd_local_addr, ndesc.nd_saddr, IPV6_ADDR_LEN);
4274 		bcopy(&fdesc->fd_remote_addr, ndesc.nd_daddr, IPV6_ADDR_LEN);
4275 	}
4276 	ndesc.nd_sport = htons(fdesc->fd_local_port);
4277 	ndesc.nd_dport = htons(fdesc->fd_remote_port);
4278 	ndesc.nd_protocol = (uint8_t)fdesc->fd_protocol;
4279 	mutex_exit(&flent->fe_lock);
4280 
4281 	return (exacct_commit_netinfo((void *)&ndesc, EX_NET_FLDESC_REC));
4282 }
4283 
4284 /* Write the Flow statistics to the log file */
4285 int
4286 mac_write_flow_stats(flow_entry_t *flent)
4287 {
4288 	flow_stats_t	*fl_stats;
4289 	net_stat_t	nstat;
4290 
4291 	fl_stats = &flent->fe_flowstats;
4292 	nstat.ns_name = flent->fe_flow_name;
4293 	nstat.ns_ibytes = fl_stats->fs_rbytes;
4294 	nstat.ns_obytes = fl_stats->fs_obytes;
4295 	nstat.ns_ipackets = fl_stats->fs_ipackets;
4296 	nstat.ns_opackets = fl_stats->fs_opackets;
4297 	nstat.ns_ierrors = fl_stats->fs_ierrors;
4298 	nstat.ns_oerrors = fl_stats->fs_oerrors;
4299 
4300 	return (exacct_commit_netinfo((void *)&nstat, EX_NET_FLSTAT_REC));
4301 }
4302 
4303 /* Write the Link Description to the log file */
4304 int
4305 mac_write_link_desc(mac_client_impl_t *mcip)
4306 {
4307 	net_desc_t		ndesc;
4308 	flow_entry_t		*flent = mcip->mci_flent;
4309 
4310 	bzero(&ndesc, sizeof (net_desc_t));
4311 
4312 	ndesc.nd_name = mcip->mci_name;
4313 	ndesc.nd_devname = mcip->mci_name;
4314 	ndesc.nd_isv4 = B_TRUE;
4315 	/*
4316 	 * Grab the fe_lock to see a self-consistent fe_flow_desc.
4317 	 * Updates to the fe_flow_desc are done under the fe_lock
4318 	 * after removing the flent from the flow table.
4319 	 */
4320 	mutex_enter(&flent->fe_lock);
4321 	bcopy(flent->fe_flow_desc.fd_src_mac, ndesc.nd_ehost, ETHERADDRL);
4322 	mutex_exit(&flent->fe_lock);
4323 
4324 	return (exacct_commit_netinfo((void *)&ndesc, EX_NET_LNDESC_REC));
4325 }
4326 
4327 /* Write the Link statistics to the log file */
4328 int
4329 mac_write_link_stats(mac_client_impl_t *mcip)
4330 {
4331 	net_stat_t	nstat;
4332 
4333 	nstat.ns_name = mcip->mci_name;
4334 	nstat.ns_ibytes = mcip->mci_stat_ibytes;
4335 	nstat.ns_obytes = mcip->mci_stat_obytes;
4336 	nstat.ns_ipackets = mcip->mci_stat_ipackets;
4337 	nstat.ns_opackets = mcip->mci_stat_opackets;
4338 	nstat.ns_ierrors = mcip->mci_stat_ierrors;
4339 	nstat.ns_oerrors = mcip->mci_stat_oerrors;
4340 
4341 	return (exacct_commit_netinfo((void *)&nstat, EX_NET_LNSTAT_REC));
4342 }
4343 
4344 /*
4345  * For a given flow, if the descrition has not been logged before, do it now.
4346  * If it is a VNIC, then we have collected information about it from the MAC
4347  * table, so skip it.
4348  */
4349 /*ARGSUSED*/
4350 static int
4351 mac_log_flowinfo(flow_entry_t *flent, void *args)
4352 {
4353 	mac_client_impl_t	*mcip = flent->fe_mcip;
4354 
4355 	if (mcip == NULL)
4356 		return (0);
4357 
4358 	/*
4359 	 * If the name starts with "vnic", and fe_user_generated is true (to
4360 	 * exclude the mcast and active flow entries created implicitly for
4361 	 * a vnic, it is a VNIC flow.  i.e. vnic1 is a vnic flow,
4362 	 * vnic/bge1/mcast1 is not and neither is vnic/bge1/active.
4363 	 */
4364 	if (strncasecmp(flent->fe_flow_name, "vnic", 4) == 0 &&
4365 	    (flent->fe_type & FLOW_USER) != 0) {
4366 		return (0);
4367 	}
4368 
4369 	if (!flent->fe_desc_logged) {
4370 		/*
4371 		 * We don't return error because we want to continu the
4372 		 * walk in case this is the last walk which means we
4373 		 * need to reset fe_desc_logged in all the flows.
4374 		 */
4375 		if (mac_write_flow_desc(flent, mcip) != 0)
4376 			return (0);
4377 		flent->fe_desc_logged = B_TRUE;
4378 	}
4379 
4380 	/*
4381 	 * Regardless of the error, we want to proceed in case we have to
4382 	 * reset fe_desc_logged.
4383 	 */
4384 	(void) mac_write_flow_stats(flent);
4385 
4386 	if (mcip != NULL && !(mcip->mci_state_flags & MCIS_DESC_LOGGED))
4387 		flent->fe_desc_logged = B_FALSE;
4388 
4389 	return (0);
4390 }
4391 
4392 typedef struct i_mac_log_state_s {
4393 	boolean_t	mi_last;
4394 	int		mi_fenable;
4395 	int		mi_lenable;
4396 } i_mac_log_state_t;
4397 
4398 /*
4399  * Walk the mac_impl_ts and log the description for each mac client of this mac,
4400  * if it hasn't already been done. Additionally, log statistics for the link as
4401  * well. Walk the flow table and log information for each flow as well.
4402  * If it is the last walk (mci_last), then we turn off mci_desc_logged (and
4403  * also fe_desc_logged, if flow logging is on) since we want to log the
4404  * description if and when logging is restarted.
4405  */
4406 /*ARGSUSED*/
4407 static uint_t
4408 i_mac_log_walker(mod_hash_key_t key, mod_hash_val_t *val, void *arg)
4409 {
4410 	mac_impl_t		*mip = (mac_impl_t *)val;
4411 	i_mac_log_state_t	*lstate = (i_mac_log_state_t *)arg;
4412 	int			ret;
4413 	mac_client_impl_t	*mcip;
4414 
4415 	/*
4416 	 * Only walk the client list for NIC and etherstub
4417 	 */
4418 	if ((mip->mi_state_flags & MIS_DISABLED) ||
4419 	    ((mip->mi_state_flags & MIS_IS_VNIC) &&
4420 	    (mac_get_lower_mac_handle((mac_handle_t)mip) != NULL)))
4421 		return (MH_WALK_CONTINUE);
4422 
4423 	for (mcip = mip->mi_clients_list; mcip != NULL;
4424 	    mcip = mcip->mci_client_next) {
4425 		if (!MCIP_DATAPATH_SETUP(mcip))
4426 			continue;
4427 		if (lstate->mi_lenable) {
4428 			if (!(mcip->mci_state_flags & MCIS_DESC_LOGGED)) {
4429 				ret = mac_write_link_desc(mcip);
4430 				if (ret != 0) {
4431 				/*
4432 				 * We can't terminate it if this is the last
4433 				 * walk, else there might be some links with
4434 				 * mi_desc_logged set to true, which means
4435 				 * their description won't be logged the next
4436 				 * time logging is started (similarly for the
4437 				 * flows within such links). We can continue
4438 				 * without walking the flow table (i.e. to
4439 				 * set fe_desc_logged to false) because we
4440 				 * won't have written any flow stuff for this
4441 				 * link as we haven't logged the link itself.
4442 				 */
4443 					if (lstate->mi_last)
4444 						return (MH_WALK_CONTINUE);
4445 					else
4446 						return (MH_WALK_TERMINATE);
4447 				}
4448 				mcip->mci_state_flags |= MCIS_DESC_LOGGED;
4449 			}
4450 		}
4451 
4452 		if (mac_write_link_stats(mcip) != 0 && !lstate->mi_last)
4453 			return (MH_WALK_TERMINATE);
4454 
4455 		if (lstate->mi_last)
4456 			mcip->mci_state_flags &= ~MCIS_DESC_LOGGED;
4457 
4458 		if (lstate->mi_fenable) {
4459 			if (mcip->mci_subflow_tab != NULL) {
4460 				(void) mac_flow_walk(mcip->mci_subflow_tab,
4461 				    mac_log_flowinfo, mip);
4462 			}
4463 		}
4464 	}
4465 	return (MH_WALK_CONTINUE);
4466 }
4467 
4468 /*
4469  * The timer thread that runs every mac_logging_interval seconds and logs
4470  * link and/or flow information.
4471  */
4472 /* ARGSUSED */
4473 void
4474 mac_log_linkinfo(void *arg)
4475 {
4476 	i_mac_log_state_t	lstate;
4477 
4478 	rw_enter(&i_mac_impl_lock, RW_READER);
4479 	if (!mac_flow_log_enable && !mac_link_log_enable) {
4480 		rw_exit(&i_mac_impl_lock);
4481 		return;
4482 	}
4483 	lstate.mi_fenable = mac_flow_log_enable;
4484 	lstate.mi_lenable = mac_link_log_enable;
4485 	lstate.mi_last = B_FALSE;
4486 	rw_exit(&i_mac_impl_lock);
4487 
4488 	mod_hash_walk(i_mac_impl_hash, i_mac_log_walker, &lstate);
4489 
4490 	rw_enter(&i_mac_impl_lock, RW_WRITER);
4491 	if (mac_flow_log_enable || mac_link_log_enable) {
4492 		mac_logging_timer = timeout(mac_log_linkinfo, NULL,
4493 		    SEC_TO_TICK(mac_logging_interval));
4494 	}
4495 	rw_exit(&i_mac_impl_lock);
4496 }
4497 
4498 typedef struct i_mac_fastpath_state_s {
4499 	boolean_t	mf_disable;
4500 	int		mf_err;
4501 } i_mac_fastpath_state_t;
4502 
4503 /*ARGSUSED*/
4504 static uint_t
4505 i_mac_fastpath_disable_walker(mod_hash_key_t key, mod_hash_val_t *val,
4506     void *arg)
4507 {
4508 	i_mac_fastpath_state_t	*state = arg;
4509 	mac_handle_t		mh = (mac_handle_t)val;
4510 
4511 	if (state->mf_disable)
4512 		state->mf_err = mac_fastpath_disable(mh);
4513 	else
4514 		mac_fastpath_enable(mh);
4515 
4516 	return (state->mf_err == 0 ? MH_WALK_CONTINUE : MH_WALK_TERMINATE);
4517 }
4518 
4519 /*
4520  * Start the logging timer.
4521  */
4522 int
4523 mac_start_logusage(mac_logtype_t type, uint_t interval)
4524 {
4525 	i_mac_fastpath_state_t state = {B_TRUE, 0};
4526 	int err;
4527 
4528 	rw_enter(&i_mac_impl_lock, RW_WRITER);
4529 	switch (type) {
4530 	case MAC_LOGTYPE_FLOW:
4531 		if (mac_flow_log_enable) {
4532 			rw_exit(&i_mac_impl_lock);
4533 			return (0);
4534 		}
4535 		/* FALLTHRU */
4536 	case MAC_LOGTYPE_LINK:
4537 		if (mac_link_log_enable) {
4538 			rw_exit(&i_mac_impl_lock);
4539 			return (0);
4540 		}
4541 		break;
4542 	default:
4543 		ASSERT(0);
4544 	}
4545 
4546 	/* Disable fastpath */
4547 	mod_hash_walk(i_mac_impl_hash, i_mac_fastpath_disable_walker, &state);
4548 	if ((err = state.mf_err) != 0) {
4549 		/* Reenable fastpath  */
4550 		state.mf_disable = B_FALSE;
4551 		state.mf_err = 0;
4552 		mod_hash_walk(i_mac_impl_hash,
4553 		    i_mac_fastpath_disable_walker, &state);
4554 		rw_exit(&i_mac_impl_lock);
4555 		return (err);
4556 	}
4557 
4558 	switch (type) {
4559 	case MAC_LOGTYPE_FLOW:
4560 		mac_flow_log_enable = B_TRUE;
4561 		/* FALLTHRU */
4562 	case MAC_LOGTYPE_LINK:
4563 		mac_link_log_enable = B_TRUE;
4564 		break;
4565 	}
4566 
4567 	mac_logging_interval = interval;
4568 	rw_exit(&i_mac_impl_lock);
4569 	mac_log_linkinfo(NULL);
4570 	return (0);
4571 }
4572 
4573 /*
4574  * Stop the logging timer if both Link and Flow logging are turned off.
4575  */
4576 void
4577 mac_stop_logusage(mac_logtype_t type)
4578 {
4579 	i_mac_log_state_t	lstate;
4580 	i_mac_fastpath_state_t	state = {B_FALSE, 0};
4581 
4582 	rw_enter(&i_mac_impl_lock, RW_WRITER);
4583 	lstate.mi_fenable = mac_flow_log_enable;
4584 	lstate.mi_lenable = mac_link_log_enable;
4585 
4586 	/* Last walk */
4587 	lstate.mi_last = B_TRUE;
4588 
4589 	switch (type) {
4590 	case MAC_LOGTYPE_FLOW:
4591 		if (lstate.mi_fenable) {
4592 			ASSERT(mac_link_log_enable);
4593 			mac_flow_log_enable = B_FALSE;
4594 			mac_link_log_enable = B_FALSE;
4595 			break;
4596 		}
4597 		/* FALLTHRU */
4598 	case MAC_LOGTYPE_LINK:
4599 		if (!lstate.mi_lenable || mac_flow_log_enable) {
4600 			rw_exit(&i_mac_impl_lock);
4601 			return;
4602 		}
4603 		mac_link_log_enable = B_FALSE;
4604 		break;
4605 	default:
4606 		ASSERT(0);
4607 	}
4608 
4609 	/* Reenable fastpath */
4610 	mod_hash_walk(i_mac_impl_hash, i_mac_fastpath_disable_walker, &state);
4611 
4612 	rw_exit(&i_mac_impl_lock);
4613 	(void) untimeout(mac_logging_timer);
4614 	mac_logging_timer = 0;
4615 
4616 	/* Last walk */
4617 	mod_hash_walk(i_mac_impl_hash, i_mac_log_walker, &lstate);
4618 }
4619 
4620 /*
4621  * Walk the rx and tx SRS/SRs for a flow and update the priority value.
4622  */
4623 void
4624 mac_flow_update_priority(mac_client_impl_t *mcip, flow_entry_t *flent)
4625 {
4626 	pri_t			pri;
4627 	int			count;
4628 	mac_soft_ring_set_t	*mac_srs;
4629 
4630 	if (flent->fe_rx_srs_cnt <= 0)
4631 		return;
4632 
4633 	if (((mac_soft_ring_set_t *)flent->fe_rx_srs[0])->srs_type ==
4634 	    SRST_FLOW) {
4635 		pri = FLOW_PRIORITY(mcip->mci_min_pri,
4636 		    mcip->mci_max_pri,
4637 		    flent->fe_resource_props.mrp_priority);
4638 	} else {
4639 		pri = mcip->mci_max_pri;
4640 	}
4641 
4642 	for (count = 0; count < flent->fe_rx_srs_cnt; count++) {
4643 		mac_srs = flent->fe_rx_srs[count];
4644 		mac_update_srs_priority(mac_srs, pri);
4645 	}
4646 	/*
4647 	 * If we have a Tx SRS, we need to modify all the threads associated
4648 	 * with it.
4649 	 */
4650 	if (flent->fe_tx_srs != NULL)
4651 		mac_update_srs_priority(flent->fe_tx_srs, pri);
4652 }
4653 
4654 /*
4655  * RX and TX rings are reserved according to different semantics depending
4656  * on the requests from the MAC clients and type of rings:
4657  *
4658  * On the Tx side, by default we reserve individual rings, independently from
4659  * the groups.
4660  *
4661  * On the Rx side, the reservation is at the granularity of the group
4662  * of rings, and used for v12n level 1 only. It has a special case for the
4663  * primary client.
4664  *
4665  * If a share is allocated to a MAC client, we allocate a TX group and an
4666  * RX group to the client, and assign TX rings and RX rings to these
4667  * groups according to information gathered from the driver through
4668  * the share capability.
4669  *
4670  * The foreseable evolution of Rx rings will handle v12n level 2 and higher
4671  * to allocate individual rings out of a group and program the hw classifier
4672  * based on IP address or higher level criteria.
4673  */
4674 
4675 /*
4676  * mac_reserve_tx_ring()
4677  * Reserve a unused ring by marking it with MR_INUSE state.
4678  * As reserved, the ring is ready to function.
4679  *
4680  * Notes for Hybrid I/O:
4681  *
4682  * If a specific ring is needed, it is specified through the desired_ring
4683  * argument. Otherwise that argument is set to NULL.
4684  * If the desired ring was previous allocated to another client, this
4685  * function swaps it with a new ring from the group of unassigned rings.
4686  */
4687 mac_ring_t *
4688 mac_reserve_tx_ring(mac_impl_t *mip, mac_ring_t *desired_ring)
4689 {
4690 	mac_group_t *group;
4691 	mac_ring_t *ring;
4692 
4693 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
4694 
4695 	if (mip->mi_tx_groups == NULL)
4696 		return (NULL);
4697 
4698 	/*
4699 	 * Find an available ring and start it before changing its status.
4700 	 * The unassigned rings are at the end of the mi_tx_groups
4701 	 * array.
4702 	 */
4703 	group = mip->mi_tx_groups + mip->mi_tx_group_count;
4704 
4705 	for (ring = group->mrg_rings; ring != NULL;
4706 	    ring = ring->mr_next) {
4707 		if (desired_ring == NULL) {
4708 			if (ring->mr_state == MR_FREE)
4709 				/* wanted any free ring and found one */
4710 				break;
4711 		} else {
4712 			mac_ring_t *sring;
4713 			mac_client_impl_t *client;
4714 			mac_soft_ring_set_t *srs;
4715 
4716 			if (ring != desired_ring)
4717 				/* wants a desired ring but this one ain't it */
4718 				continue;
4719 
4720 			if (ring->mr_state == MR_FREE)
4721 				break;
4722 
4723 			/*
4724 			 * Found the desired ring but it's already in use.
4725 			 * Swap it with a new ring.
4726 			 */
4727 
4728 			/* find the client which owns that ring */
4729 			for (client = mip->mi_clients_list; client != NULL;
4730 			    client = client->mci_client_next) {
4731 				srs = MCIP_TX_SRS(client);
4732 				if (srs != NULL && mac_tx_srs_ring_present(srs,
4733 				    desired_ring)) {
4734 					/* found our ring */
4735 					break;
4736 				}
4737 			}
4738 			if (client == NULL) {
4739 				/*
4740 				 * The TX ring is in use, but it's not
4741 				 * associated with any clients, so it
4742 				 * has to be the default ring. In that
4743 				 * case we can simply assign a new ring
4744 				 * as the default ring, and we're done.
4745 				 */
4746 				ASSERT(mip->mi_default_tx_ring ==
4747 				    (mac_ring_handle_t)desired_ring);
4748 
4749 				/*
4750 				 * Quiesce all clients on top of
4751 				 * the NIC to make sure there are no
4752 				 * pending threads still relying on
4753 				 * that default ring, for example
4754 				 * the multicast path.
4755 				 */
4756 				for (client = mip->mi_clients_list;
4757 				    client != NULL;
4758 				    client = client->mci_client_next) {
4759 					mac_tx_client_quiesce(client,
4760 					    SRS_QUIESCE);
4761 				}
4762 
4763 				mip->mi_default_tx_ring = (mac_ring_handle_t)
4764 				    mac_reserve_tx_ring(mip, NULL);
4765 
4766 				/* resume the clients */
4767 				for (client = mip->mi_clients_list;
4768 				    client != NULL;
4769 				    client = client->mci_client_next)
4770 					mac_tx_client_restart(client);
4771 
4772 				break;
4773 			}
4774 
4775 			/*
4776 			 * Note that we cannot simply invoke the group
4777 			 * add/rem routines since the client doesn't have a
4778 			 * TX group. So we need to instead add/remove
4779 			 * the rings from the SRS.
4780 			 */
4781 			ASSERT(client->mci_share == NULL);
4782 
4783 			/* first quiece the client */
4784 			mac_tx_client_quiesce(client, SRS_QUIESCE);
4785 
4786 			/* give a new ring to the client... */
4787 			sring = mac_reserve_tx_ring(mip, NULL);
4788 			if (sring != NULL) {
4789 				/*
4790 				 * There are no other available ring
4791 				 * on that MAC instance. The client
4792 				 * will fallback to the shared TX
4793 				 * ring.
4794 				 */
4795 				mac_tx_srs_add_ring(srs, sring);
4796 			}
4797 
4798 			/* ... in exchange for our desired ring */
4799 			mac_tx_srs_del_ring(srs, desired_ring);
4800 
4801 			/* restart the client */
4802 			mac_tx_client_restart(client);
4803 
4804 			if (mip->mi_default_tx_ring ==
4805 			    (mac_ring_handle_t)desired_ring) {
4806 				/*
4807 				 * The desired ring is the default ring,
4808 				 * and there are one or more clients
4809 				 * using that default ring directly.
4810 				 */
4811 				mip->mi_default_tx_ring =
4812 				    (mac_ring_handle_t)sring;
4813 				/*
4814 				 * Find clients using default ring and
4815 				 * swap it with the new default ring.
4816 				 */
4817 				for (client = mip->mi_clients_list;
4818 				    client != NULL;
4819 				    client = client->mci_client_next) {
4820 					srs = MCIP_TX_SRS(client);
4821 					if (srs != NULL &&
4822 					    mac_tx_srs_ring_present(srs,
4823 					    desired_ring)) {
4824 						/* first quiece the client */
4825 						mac_tx_client_quiesce(client,
4826 						    SRS_QUIESCE);
4827 
4828 						/*
4829 						 * Give it the new default
4830 						 * ring, and remove the old
4831 						 * one.
4832 						 */
4833 						if (sring != NULL) {
4834 							mac_tx_srs_add_ring(srs,
4835 							    sring);
4836 						}
4837 						mac_tx_srs_del_ring(srs,
4838 						    desired_ring);
4839 
4840 						/* restart the client */
4841 						mac_tx_client_restart(client);
4842 					}
4843 				}
4844 			}
4845 			break;
4846 		}
4847 	}
4848 
4849 	if (ring != NULL) {
4850 		if (mac_start_ring(ring) != 0)
4851 			return (NULL);
4852 		ring->mr_state = MR_INUSE;
4853 	}
4854 
4855 	return (ring);
4856 }
4857 
4858 /*
4859  * Minimum number of rings to leave in the default TX group when allocating
4860  * rings to new clients.
4861  */
4862 static uint_t mac_min_rx_default_rings = 1;
4863 
4864 /*
4865  * Populate a zero-ring group with rings. If the share is non-NULL,
4866  * the rings are chosen according to that share.
4867  * Invoked after allocating a new RX or TX group through
4868  * mac_reserve_rx_group() or mac_reserve_tx_group(), respectively.
4869  * Returns zero on success, an errno otherwise.
4870  */
4871 int
4872 i_mac_group_allocate_rings(mac_impl_t *mip, mac_ring_type_t ring_type,
4873     mac_group_t *src_group, mac_group_t *new_group, mac_share_handle_t share)
4874 {
4875 	mac_ring_t **rings, *tmp_ring[1], *ring;
4876 	uint_t nrings;
4877 	int rv, i, j;
4878 
4879 	ASSERT(mip->mi_rx_group_type == MAC_GROUP_TYPE_DYNAMIC &&
4880 	    mip->mi_tx_group_type == MAC_GROUP_TYPE_DYNAMIC);
4881 	ASSERT(new_group->mrg_cur_count == 0);
4882 
4883 	/*
4884 	 * First find the rings to allocate to the group.
4885 	 */
4886 	if (share != NULL) {
4887 		/* get rings through ms_squery() */
4888 		mip->mi_share_capab.ms_squery(share, ring_type, NULL, &nrings);
4889 		ASSERT(nrings != 0);
4890 		rings = kmem_alloc(nrings * sizeof (mac_ring_handle_t),
4891 		    KM_SLEEP);
4892 		mip->mi_share_capab.ms_squery(share, ring_type,
4893 		    (mac_ring_handle_t *)rings, &nrings);
4894 	} else {
4895 		/* this function is called for TX only with a share */
4896 		ASSERT(ring_type == MAC_RING_TYPE_RX);
4897 		/*
4898 		 * Pick one ring from default group.
4899 		 *
4900 		 * for now pick the second ring which requires the first ring
4901 		 * at index 0 to stay in the default group, since it is the
4902 		 * ring which carries the multicast traffic.
4903 		 * We need a better way for a driver to indicate this,
4904 		 * for example a per-ring flag.
4905 		 */
4906 		for (ring = src_group->mrg_rings; ring != NULL;
4907 		    ring = ring->mr_next) {
4908 			if (ring->mr_index != 0)
4909 				break;
4910 		}
4911 		ASSERT(ring != NULL);
4912 		nrings = 1;
4913 		tmp_ring[0] = ring;
4914 		rings = tmp_ring;
4915 	}
4916 
4917 	switch (ring_type) {
4918 	case MAC_RING_TYPE_RX:
4919 		if (src_group->mrg_cur_count - nrings <
4920 		    mac_min_rx_default_rings) {
4921 			/* we ran out of rings */
4922 			return (ENOSPC);
4923 		}
4924 
4925 		/* move receive rings to new group */
4926 		for (i = 0; i < nrings; i++) {
4927 			rv = mac_group_mov_ring(mip, new_group, rings[i]);
4928 			if (rv != 0) {
4929 				/* move rings back on failure */
4930 				for (j = 0; j < i; j++) {
4931 					(void) mac_group_mov_ring(mip,
4932 					    src_group, rings[j]);
4933 				}
4934 				return (rv);
4935 			}
4936 		}
4937 		break;
4938 
4939 	case MAC_RING_TYPE_TX: {
4940 		mac_ring_t *tmp_ring;
4941 
4942 		/* move the TX rings to the new group */
4943 		ASSERT(src_group == NULL);
4944 		for (i = 0; i < nrings; i++) {
4945 			/* get the desired ring */
4946 			tmp_ring = mac_reserve_tx_ring(mip, rings[i]);
4947 			ASSERT(tmp_ring == rings[i]);
4948 			rv = mac_group_mov_ring(mip, new_group, rings[i]);
4949 			if (rv != 0) {
4950 				/* cleanup on failure */
4951 				for (j = 0; j < i; j++) {
4952 					(void) mac_group_mov_ring(mip,
4953 					    mip->mi_tx_groups +
4954 					    mip->mi_tx_group_count, rings[j]);
4955 				}
4956 			}
4957 		}
4958 		break;
4959 	}
4960 	}
4961 
4962 	if (share != NULL) {
4963 		/* add group to share */
4964 		mip->mi_share_capab.ms_sadd(share, new_group->mrg_driver);
4965 		/* free temporary array of rings */
4966 		kmem_free(rings, nrings * sizeof (mac_ring_handle_t));
4967 	}
4968 
4969 	return (0);
4970 }
4971 
4972 void
4973 mac_rx_group_add_client(mac_group_t *grp, mac_client_impl_t *mcip)
4974 {
4975 	mac_grp_client_t *mgcp;
4976 
4977 	for (mgcp = grp->mrg_clients; mgcp != NULL; mgcp = mgcp->mgc_next) {
4978 		if (mgcp->mgc_client == mcip)
4979 			break;
4980 	}
4981 
4982 	VERIFY(mgcp == NULL);
4983 
4984 	mgcp = kmem_zalloc(sizeof (mac_grp_client_t), KM_SLEEP);
4985 	mgcp->mgc_client = mcip;
4986 	mgcp->mgc_next = grp->mrg_clients;
4987 	grp->mrg_clients = mgcp;
4988 
4989 }
4990 
4991 void
4992 mac_rx_group_remove_client(mac_group_t *grp, mac_client_impl_t *mcip)
4993 {
4994 	mac_grp_client_t *mgcp, **pprev;
4995 
4996 	for (pprev = &grp->mrg_clients, mgcp = *pprev; mgcp != NULL;
4997 	    pprev = &mgcp->mgc_next, mgcp = *pprev) {
4998 		if (mgcp->mgc_client == mcip)
4999 			break;
5000 	}
5001 
5002 	ASSERT(mgcp != NULL);
5003 
5004 	*pprev = mgcp->mgc_next;
5005 	kmem_free(mgcp, sizeof (mac_grp_client_t));
5006 }
5007 
5008 /*
5009  * mac_reserve_rx_group()
5010  *
5011  * Finds an available group and exclusively reserves it for a client.
5012  * The group is chosen to suit the flow's resource controls (bandwidth and
5013  * fanout requirements) and the address type.
5014  * If the requestor is the pimary MAC then return the group with the
5015  * largest number of rings, otherwise the default ring when available.
5016  */
5017 mac_group_t *
5018 mac_reserve_rx_group(mac_client_impl_t *mcip, uint8_t *mac_addr,
5019     mac_rx_group_reserve_type_t rtype)
5020 {
5021 	mac_share_handle_t	share = mcip->mci_share;
5022 	mac_impl_t		*mip = mcip->mci_mip;
5023 	mac_group_t		*grp = NULL;
5024 	int			i, start, loopcount;
5025 	int			err;
5026 	mac_address_t		*map;
5027 
5028 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mip));
5029 
5030 	/* Check if a group already has this mac address (case of VLANs) */
5031 	if ((map = mac_find_macaddr(mip, mac_addr)) != NULL)
5032 		return (map->ma_group);
5033 
5034 	if (mip->mi_rx_groups == NULL || mip->mi_rx_group_count == 0 ||
5035 	    rtype == MAC_RX_NO_RESERVE)
5036 		return (NULL);
5037 
5038 	/*
5039 	 * Try to exclusively reserve a RX group.
5040 	 *
5041 	 * For flows requires SW_RING it always goes to the default group
5042 	 * (Until we can explicitely call out default groups (CR 6695600),
5043 	 * we assume that the default group is always at position zero);
5044 	 *
5045 	 * For flows requires HW_DEFAULT_RING (unicast flow of the primary
5046 	 * client), try to reserve the default RX group only.
5047 	 *
5048 	 * For flows requires HW_RING (unicast flow of other clients), try
5049 	 * to reserve non-default RX group then the default group.
5050 	 */
5051 	switch (rtype) {
5052 	case MAC_RX_RESERVE_DEFAULT:
5053 		start = 0;
5054 		loopcount = 1;
5055 		break;
5056 	case MAC_RX_RESERVE_NONDEFAULT:
5057 		start = 1;
5058 		loopcount = mip->mi_rx_group_count;
5059 	}
5060 
5061 	for (i = start; i < start + loopcount; i++) {
5062 		grp = &mip->mi_rx_groups[i % mip->mi_rx_group_count];
5063 
5064 		DTRACE_PROBE3(rx__group__trying, char *, mip->mi_name,
5065 		    int, grp->mrg_index, mac_group_state_t, grp->mrg_state);
5066 
5067 		/*
5068 		 * Check to see whether this mac client is the only client
5069 		 * on this RX group. If not, we cannot exclusively reserve
5070 		 * this RX group.
5071 		 */
5072 		if (!MAC_RX_GROUP_NO_CLIENT(grp) &&
5073 		    (MAC_RX_GROUP_ONLY_CLIENT(grp) != mcip)) {
5074 			continue;
5075 		}
5076 
5077 		/*
5078 		 * This group could already be SHARED by other multicast
5079 		 * flows on this client. In that case, the group would
5080 		 * be shared and has already been started.
5081 		 */
5082 		ASSERT(grp->mrg_state != MAC_GROUP_STATE_UNINIT);
5083 
5084 		if ((grp->mrg_state == MAC_GROUP_STATE_REGISTERED) &&
5085 		    (mac_start_group(grp) != 0)) {
5086 			continue;
5087 		}
5088 
5089 		if ((i % mip->mi_rx_group_count) == 0 ||
5090 		    mip->mi_rx_group_type != MAC_GROUP_TYPE_DYNAMIC) {
5091 			break;
5092 		}
5093 
5094 		ASSERT(grp->mrg_cur_count == 0);
5095 
5096 		/*
5097 		 * Populate the group. Rings should be taken
5098 		 * from the default group at position 0 for now.
5099 		 */
5100 
5101 		err = i_mac_group_allocate_rings(mip, MAC_RING_TYPE_RX,
5102 		    &mip->mi_rx_groups[0], grp, share);
5103 		if (err == 0)
5104 			break;
5105 
5106 		DTRACE_PROBE3(rx__group__reserve__alloc__rings, char *,
5107 		    mip->mi_name, int, grp->mrg_index, int, err);
5108 
5109 		/*
5110 		 * It's a dynamic group but the grouping operation failed.
5111 		 */
5112 		mac_stop_group(grp);
5113 	}
5114 
5115 	if (i == start + loopcount)
5116 		return (NULL);
5117 
5118 	ASSERT(grp != NULL);
5119 
5120 	DTRACE_PROBE2(rx__group__reserved,
5121 	    char *, mip->mi_name, int, grp->mrg_index);
5122 	return (grp);
5123 }
5124 
5125 /*
5126  * mac_rx_release_group()
5127  *
5128  * This is called when there are no clients left for the group.
5129  * The group is stopped and marked MAC_GROUP_STATE_REGISTERED,
5130  * and if it is a non default group, the shares are removed and
5131  * all rings are assigned back to default group.
5132  */
5133 void
5134 mac_release_rx_group(mac_client_impl_t *mcip, mac_group_t *group)
5135 {
5136 	mac_impl_t	*mip = mcip->mci_mip;
5137 	mac_ring_t	*ring;
5138 
5139 	ASSERT(group != &mip->mi_rx_groups[0]);
5140 
5141 	/*
5142 	 * This is the case where there are no clients left. Any
5143 	 * SRS etc on this group have also be quiesced.
5144 	 */
5145 	for (ring = group->mrg_rings; ring != NULL; ring = ring->mr_next) {
5146 		if (ring->mr_classify_type == MAC_HW_CLASSIFIER) {
5147 			ASSERT(group->mrg_state == MAC_GROUP_STATE_RESERVED);
5148 			/*
5149 			 * Remove the SRS associated with the HW ring.
5150 			 * As a result, polling will be disabled.
5151 			 */
5152 			ring->mr_srs = NULL;
5153 		}
5154 		ASSERT(ring->mr_state == MR_INUSE);
5155 		mac_stop_ring(ring);
5156 		ring->mr_state = MR_FREE;
5157 		ring->mr_flag = 0;
5158 	}
5159 
5160 	/* remove group from share */
5161 	if (mcip->mci_share != NULL) {
5162 		mip->mi_share_capab.ms_sremove(mcip->mci_share,
5163 		    group->mrg_driver);
5164 	}
5165 
5166 	if (mip->mi_rx_group_type == MAC_GROUP_TYPE_DYNAMIC) {
5167 		mac_ring_t *ring;
5168 
5169 		/*
5170 		 * Rings were dynamically allocated to group.
5171 		 * Move rings back to default group.
5172 		 */
5173 		while ((ring = group->mrg_rings) != NULL) {
5174 			(void) mac_group_mov_ring(mip,
5175 			    &mip->mi_rx_groups[0], ring);
5176 		}
5177 	}
5178 	mac_stop_group(group);
5179 	/*
5180 	 * Possible improvement: See if we can assign the group just released
5181 	 * to a another client of the mip
5182 	 */
5183 }
5184 
5185 /*
5186  * Reserves a TX group for the specified share. Invoked by mac_tx_srs_setup()
5187  * when a share was allocated to the client.
5188  */
5189 mac_group_t *
5190 mac_reserve_tx_group(mac_impl_t *mip, mac_share_handle_t share)
5191 {
5192 	mac_group_t *grp;
5193 	int rv, i;
5194 
5195 	/*
5196 	 * TX groups are currently allocated only to MAC clients
5197 	 * which are associated with a share. Since we have a fixed
5198 	 * number of share and groups, and we already successfully
5199 	 * allocated a share, find an available TX group.
5200 	 */
5201 	ASSERT(share != NULL);
5202 	ASSERT(mip->mi_tx_group_free > 0);
5203 
5204 	for (i = 0; i <  mip->mi_tx_group_count; i++) {
5205 		grp = &mip->mi_tx_groups[i];
5206 
5207 		if ((grp->mrg_state == MAC_GROUP_STATE_RESERVED) ||
5208 		    (grp->mrg_state == MAC_GROUP_STATE_UNINIT))
5209 			continue;
5210 
5211 		rv = mac_start_group(grp);
5212 		ASSERT(rv == 0);
5213 
5214 		grp->mrg_state = MAC_GROUP_STATE_RESERVED;
5215 		break;
5216 	}
5217 
5218 	ASSERT(grp != NULL);
5219 
5220 	/*
5221 	 * Populate the group. Rings should be taken from the group
5222 	 * of unassigned rings, which is past the array of TX
5223 	 * groups adversized by the driver.
5224 	 */
5225 	rv = i_mac_group_allocate_rings(mip, MAC_RING_TYPE_TX, NULL,
5226 	    grp, share);
5227 	if (rv != 0) {
5228 		DTRACE_PROBE3(tx__group__reserve__alloc__rings,
5229 		    char *, mip->mi_name, int, grp->mrg_index, int, rv);
5230 
5231 		mac_stop_group(grp);
5232 		grp->mrg_state = MAC_GROUP_STATE_UNINIT;
5233 
5234 		return (NULL);
5235 	}
5236 
5237 	mip->mi_tx_group_free--;
5238 
5239 	return (grp);
5240 }
5241 
5242 void
5243 mac_release_tx_group(mac_impl_t *mip, mac_group_t *grp)
5244 {
5245 	mac_client_impl_t *mcip = grp->mrg_tx_client;
5246 	mac_share_handle_t share = mcip->mci_share;
5247 	mac_ring_t *ring;
5248 
5249 	ASSERT(mip->mi_tx_group_type == MAC_GROUP_TYPE_DYNAMIC);
5250 	ASSERT(share != NULL);
5251 	ASSERT(grp->mrg_state == MAC_GROUP_STATE_RESERVED);
5252 
5253 	mip->mi_share_capab.ms_sremove(share, grp->mrg_driver);
5254 	while ((ring = grp->mrg_rings) != NULL) {
5255 		/* move the ring back to the pool */
5256 		(void) mac_group_mov_ring(mip, mip->mi_tx_groups +
5257 		    mip->mi_tx_group_count, ring);
5258 	}
5259 	mac_stop_group(grp);
5260 	mac_set_rx_group_state(grp, MAC_GROUP_STATE_REGISTERED);
5261 	grp->mrg_tx_client = NULL;
5262 	mip->mi_tx_group_free++;
5263 }
5264 
5265 /*
5266  * This is a 1-time control path activity initiated by the client (IP).
5267  * The mac perimeter protects against other simultaneous control activities,
5268  * for example an ioctl that attempts to change the degree of fanout and
5269  * increase or decrease the number of softrings associated with this Tx SRS.
5270  */
5271 static mac_tx_notify_cb_t *
5272 mac_client_tx_notify_add(mac_client_impl_t *mcip,
5273     mac_tx_notify_t notify, void *arg)
5274 {
5275 	mac_cb_info_t *mcbi;
5276 	mac_tx_notify_cb_t *mtnfp;
5277 
5278 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
5279 
5280 	mtnfp = kmem_zalloc(sizeof (mac_tx_notify_cb_t), KM_SLEEP);
5281 	mtnfp->mtnf_fn = notify;
5282 	mtnfp->mtnf_arg = arg;
5283 	mtnfp->mtnf_link.mcb_objp = mtnfp;
5284 	mtnfp->mtnf_link.mcb_objsize = sizeof (mac_tx_notify_cb_t);
5285 	mtnfp->mtnf_link.mcb_flags = MCB_TX_NOTIFY_CB_T;
5286 
5287 	mcbi = &mcip->mci_tx_notify_cb_info;
5288 	mutex_enter(mcbi->mcbi_lockp);
5289 	mac_callback_add(mcbi, &mcip->mci_tx_notify_cb_list, &mtnfp->mtnf_link);
5290 	mutex_exit(mcbi->mcbi_lockp);
5291 	return (mtnfp);
5292 }
5293 
5294 static void
5295 mac_client_tx_notify_remove(mac_client_impl_t *mcip, mac_tx_notify_cb_t *mtnfp)
5296 {
5297 	mac_cb_info_t	*mcbi;
5298 	mac_cb_t	**cblist;
5299 
5300 	ASSERT(MAC_PERIM_HELD((mac_handle_t)mcip->mci_mip));
5301 
5302 	if (!mac_callback_find(&mcip->mci_tx_notify_cb_info,
5303 	    &mcip->mci_tx_notify_cb_list, &mtnfp->mtnf_link)) {
5304 		cmn_err(CE_WARN,
5305 		    "mac_client_tx_notify_remove: callback not "
5306 		    "found, mcip 0x%p mtnfp 0x%p", (void *)mcip, (void *)mtnfp);
5307 		return;
5308 	}
5309 
5310 	mcbi = &mcip->mci_tx_notify_cb_info;
5311 	cblist = &mcip->mci_tx_notify_cb_list;
5312 	mutex_enter(mcbi->mcbi_lockp);
5313 	if (mac_callback_remove(mcbi, cblist, &mtnfp->mtnf_link))
5314 		kmem_free(mtnfp, sizeof (mac_tx_notify_cb_t));
5315 	else
5316 		mac_callback_remove_wait(&mcip->mci_tx_notify_cb_info);
5317 	mutex_exit(mcbi->mcbi_lockp);
5318 }
5319 
5320 /*
5321  * mac_client_tx_notify():
5322  * call to add and remove flow control callback routine.
5323  */
5324 mac_tx_notify_handle_t
5325 mac_client_tx_notify(mac_client_handle_t mch, mac_tx_notify_t callb_func,
5326     void *ptr)
5327 {
5328 	mac_client_impl_t	*mcip = (mac_client_impl_t *)mch;
5329 	mac_tx_notify_cb_t	*mtnfp = NULL;
5330 
5331 	i_mac_perim_enter(mcip->mci_mip);
5332 
5333 	if (callb_func != NULL) {
5334 		/* Add a notify callback */
5335 		mtnfp = mac_client_tx_notify_add(mcip, callb_func, ptr);
5336 	} else {
5337 		mac_client_tx_notify_remove(mcip, (mac_tx_notify_cb_t *)ptr);
5338 	}
5339 	i_mac_perim_exit(mcip->mci_mip);
5340 
5341 	return ((mac_tx_notify_handle_t)mtnfp);
5342 }
5343 
5344 void
5345 mac_bridge_vectors(mac_bridge_tx_t txf, mac_bridge_rx_t rxf,
5346     mac_bridge_ref_t reff, mac_bridge_ls_t lsf)
5347 {
5348 	mac_bridge_tx_cb = txf;
5349 	mac_bridge_rx_cb = rxf;
5350 	mac_bridge_ref_cb = reff;
5351 	mac_bridge_ls_cb = lsf;
5352 }
5353 
5354 int
5355 mac_bridge_set(mac_handle_t mh, mac_handle_t link)
5356 {
5357 	mac_impl_t *mip = (mac_impl_t *)mh;
5358 	int retv;
5359 
5360 	mutex_enter(&mip->mi_bridge_lock);
5361 	if (mip->mi_bridge_link == NULL) {
5362 		mip->mi_bridge_link = link;
5363 		retv = 0;
5364 	} else {
5365 		retv = EBUSY;
5366 	}
5367 	mutex_exit(&mip->mi_bridge_lock);
5368 	if (retv == 0) {
5369 		mac_poll_state_change(mh, B_FALSE);
5370 		mac_capab_update(mh);
5371 	}
5372 	return (retv);
5373 }
5374 
5375 /*
5376  * Disable bridging on the indicated link.
5377  */
5378 void
5379 mac_bridge_clear(mac_handle_t mh, mac_handle_t link)
5380 {
5381 	mac_impl_t *mip = (mac_impl_t *)mh;
5382 
5383 	mutex_enter(&mip->mi_bridge_lock);
5384 	ASSERT(mip->mi_bridge_link == link);
5385 	mip->mi_bridge_link = NULL;
5386 	mutex_exit(&mip->mi_bridge_lock);
5387 	mac_poll_state_change(mh, B_TRUE);
5388 	mac_capab_update(mh);
5389 }
5390 
5391 void
5392 mac_no_active(mac_handle_t mh)
5393 {
5394 	mac_impl_t *mip = (mac_impl_t *)mh;
5395 
5396 	i_mac_perim_enter(mip);
5397 	mip->mi_state_flags |= MIS_NO_ACTIVE;
5398 	i_mac_perim_exit(mip);
5399 }
5400