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