ng_source.c revision 167160
1/*
2 * ng_source.c
3 */
4
5/*-
6 * Copyright (c) 2005 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Copyright 2002 Sandvine Inc.
8 * All rights reserved.
9 *
10 * Subject to the following obligations and disclaimer of warranty, use and
11 * redistribution of this software, in source or object code forms, with or
12 * without modifications are expressly permitted by Sandvine Inc.; provided,
13 * however, that:
14 * 1. Any and all reproductions of the source or object code must include the
15 *    copyright notice above and the following disclaimer of warranties; and
16 * 2. No rights are granted, in any manner or form, to use Sandvine Inc.
17 *    trademarks, including the mark "SANDVINE" on advertising, endorsements,
18 *    or otherwise except as such appears in the above copyright notice or in
19 *    the software.
20 *
21 * THIS SOFTWARE IS BEING PROVIDED BY SANDVINE "AS IS", AND TO THE MAXIMUM
22 * EXTENT PERMITTED BY LAW, SANDVINE MAKES NO REPRESENTATIONS OR WARRANTIES,
23 * EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE, INCLUDING WITHOUT LIMITATION,
24 * ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
25 * PURPOSE, OR NON-INFRINGEMENT.  SANDVINE DOES NOT WARRANT, GUARANTEE, OR
26 * MAKE ANY REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE
27 * USE OF THIS SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY
28 * OR OTHERWISE.  IN NO EVENT SHALL SANDVINE BE LIABLE FOR ANY DAMAGES
29 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
30 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
31 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
32 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF SANDVINE IS ADVISED OF THE POSSIBILITY OF SUCH
36 * DAMAGE.
37 *
38 * Author: Dave Chapeskie <dchapeskie@sandvine.com>
39 */
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/sys/netgraph/ng_source.c 167160 2007-03-02 01:44:04Z emaste $");
43
44/*
45 * This node is used for high speed packet geneneration.  It queues
46 * all data recieved on its 'input' hook and when told to start via
47 * a control message it sends the packets out its 'output' hook.  In
48 * this way this node can be preloaded with a packet stream which it
49 * can then send continuously as fast as possible.
50 *
51 * Currently it just copies the mbufs as required.  It could do various
52 * tricks to try and avoid this.  Probably the best performance would
53 * be achieved by modifying the appropriate drivers to be told to
54 * self-re-enqueue packets (e.g. the if_bge driver could reuse the same
55 * transmit descriptors) under control of this node; perhaps via some
56 * flag in the mbuf or some such.  The node could peek at an appropriate
57 * ifnet flag to see if such support is available for the connected
58 * interface.
59 */
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/errno.h>
64#include <sys/kernel.h>
65#include <sys/malloc.h>
66#include <sys/mbuf.h>
67#include <sys/socket.h>
68#include <sys/syslog.h>
69#include <net/if.h>
70#include <net/if_var.h>
71#include <netgraph/ng_message.h>
72#include <netgraph/netgraph.h>
73#include <netgraph/ng_parse.h>
74#include <netgraph/ng_ether.h>
75#include <netgraph/ng_source.h>
76
77#define NG_SOURCE_INTR_TICKS		1
78#define NG_SOURCE_DRIVER_IFQ_MAXLEN	(4*1024)
79
80#define	mtod_off(m,off,t)	((t)(mtod((m),caddr_t)+(off)))
81
82/* Per node info */
83struct privdata {
84	node_p				node;
85	hook_p				input;
86	hook_p				output;
87	struct ng_source_stats		stats;
88	struct ifqueue			snd_queue;	/* packets to send */
89	struct mbuf			*last_packet;	/* last pkt in queue */
90	struct ifnet			*output_ifp;
91	struct callout			intr_ch;
92	uint64_t			packets;	/* packets to send */
93	uint32_t			queueOctets;
94	struct ng_source_embed_info	embed_timestamp;
95	struct ng_source_embed_cnt_info	embed_counter[NG_SOURCE_COUNTERS];
96};
97typedef struct privdata *sc_p;
98
99/* Node flags */
100#define NG_SOURCE_ACTIVE	(NGF_TYPE1)
101
102/* Netgraph methods */
103static ng_constructor_t	ng_source_constructor;
104static ng_rcvmsg_t	ng_source_rcvmsg;
105static ng_shutdown_t	ng_source_rmnode;
106static ng_newhook_t	ng_source_newhook;
107static ng_connect_t	ng_source_connect;
108static ng_rcvdata_t	ng_source_rcvdata;
109static ng_disconnect_t	ng_source_disconnect;
110
111/* Other functions */
112static void		ng_source_intr(node_p, hook_p, void *, int);
113static void		ng_source_clr_data (sc_p);
114static int		ng_source_start (sc_p, uint64_t);
115static void		ng_source_stop (sc_p);
116static int		ng_source_send (sc_p, int, int *);
117static int		ng_source_store_output_ifp(sc_p, char *);
118static void		ng_source_packet_mod(sc_p, struct mbuf *,
119			    int, int, caddr_t, int);
120static void		ng_source_mod_counter(sc_p sc,
121			    struct ng_source_embed_cnt_info *cnt,
122			    struct mbuf *m, int increment);
123static int		ng_source_dup_mod(sc_p, struct mbuf *,
124			    struct mbuf **);
125
126/* Parse type for timeval */
127static const struct ng_parse_struct_field ng_source_timeval_type_fields[] = {
128	{ "tv_sec",		&ng_parse_int32_type	},
129	{ "tv_usec",		&ng_parse_int32_type	},
130	{ NULL }
131};
132const struct ng_parse_type ng_source_timeval_type = {
133	&ng_parse_struct_type,
134	&ng_source_timeval_type_fields
135};
136
137/* Parse type for struct ng_source_stats */
138static const struct ng_parse_struct_field ng_source_stats_type_fields[]
139	= NG_SOURCE_STATS_TYPE_INFO;
140static const struct ng_parse_type ng_source_stats_type = {
141	&ng_parse_struct_type,
142	&ng_source_stats_type_fields
143};
144
145/* Parse type for struct ng_source_embed_info */
146static const struct ng_parse_struct_field ng_source_embed_type_fields[] =
147	NG_SOURCE_EMBED_TYPE_INFO;
148static const struct ng_parse_type ng_source_embed_type = {
149	&ng_parse_struct_type,
150	&ng_source_embed_type_fields
151};
152
153/* Parse type for struct ng_source_embed_cnt_info */
154static const struct ng_parse_struct_field ng_source_embed_cnt_type_fields[] =
155	NG_SOURCE_EMBED_CNT_TYPE_INFO;
156static const struct ng_parse_type ng_source_embed_cnt_type = {
157	&ng_parse_struct_type,
158	&ng_source_embed_cnt_type_fields
159};
160
161/* List of commands and how to convert arguments to/from ASCII */
162static const struct ng_cmdlist ng_source_cmds[] = {
163	{
164	  NGM_SOURCE_COOKIE,
165	  NGM_SOURCE_GET_STATS,
166	  "getstats",
167	  NULL,
168	  &ng_source_stats_type
169	},
170	{
171	  NGM_SOURCE_COOKIE,
172	  NGM_SOURCE_CLR_STATS,
173	  "clrstats",
174	  NULL,
175	  NULL
176	},
177	{
178	  NGM_SOURCE_COOKIE,
179	  NGM_SOURCE_GETCLR_STATS,
180	  "getclrstats",
181	  NULL,
182	  &ng_source_stats_type
183	},
184	{
185	  NGM_SOURCE_COOKIE,
186	  NGM_SOURCE_START,
187	  "start",
188	  &ng_parse_uint64_type,
189	  NULL
190	},
191	{
192	  NGM_SOURCE_COOKIE,
193	  NGM_SOURCE_STOP,
194	  "stop",
195	  NULL,
196	  NULL
197	},
198	{
199	  NGM_SOURCE_COOKIE,
200	  NGM_SOURCE_CLR_DATA,
201	  "clrdata",
202	  NULL,
203	  NULL
204	},
205	{
206	  NGM_SOURCE_COOKIE,
207	  NGM_SOURCE_SETIFACE,
208	  "setiface",
209	  &ng_parse_string_type,
210	  NULL
211	},
212	{
213	  NGM_SOURCE_COOKIE,
214	  NGM_SOURCE_SETPPS,
215	  "setpps",
216	  &ng_parse_uint32_type,
217	  NULL
218	},
219	{
220	  NGM_SOURCE_COOKIE,
221	  NGM_SOURCE_SET_TIMESTAMP,
222	  "settimestamp",
223	  &ng_source_embed_type,
224	  NULL
225	},
226	{
227	  NGM_SOURCE_COOKIE,
228	  NGM_SOURCE_GET_TIMESTAMP,
229	  "gettimestamp",
230	  NULL,
231	  &ng_source_embed_type
232	},
233	{
234	  NGM_SOURCE_COOKIE,
235	  NGM_SOURCE_SET_COUNTER,
236	  "setcounter",
237	  &ng_source_embed_cnt_type,
238	  NULL
239	},
240	{
241	  NGM_SOURCE_COOKIE,
242	  NGM_SOURCE_GET_COUNTER,
243	  "getcounter",
244	  &ng_parse_uint8_type,
245	  &ng_source_embed_cnt_type
246	},
247	{ 0 }
248};
249
250/* Netgraph type descriptor */
251static struct ng_type ng_source_typestruct = {
252	.version =	NG_ABI_VERSION,
253	.name =		NG_SOURCE_NODE_TYPE,
254	.constructor =	ng_source_constructor,
255	.rcvmsg =	ng_source_rcvmsg,
256	.shutdown =	ng_source_rmnode,
257	.newhook =	ng_source_newhook,
258	.connect =	ng_source_connect,
259	.rcvdata =	ng_source_rcvdata,
260	.disconnect =	ng_source_disconnect,
261	.cmdlist =	ng_source_cmds,
262};
263NETGRAPH_INIT(source, &ng_source_typestruct);
264
265static int ng_source_set_autosrc(sc_p, uint32_t);
266
267/*
268 * Node constructor
269 */
270static int
271ng_source_constructor(node_p node)
272{
273	sc_p sc;
274
275	sc = malloc(sizeof(*sc), M_NETGRAPH, M_NOWAIT | M_ZERO);
276	if (sc == NULL)
277		return (ENOMEM);
278
279	NG_NODE_SET_PRIVATE(node, sc);
280	sc->node = node;
281	sc->snd_queue.ifq_maxlen = 2048;	/* XXX not checked */
282	ng_callout_init(&sc->intr_ch);
283
284	return (0);
285}
286
287/*
288 * Add a hook
289 */
290static int
291ng_source_newhook(node_p node, hook_p hook, const char *name)
292{
293	sc_p sc = NG_NODE_PRIVATE(node);
294
295	if (strcmp(name, NG_SOURCE_HOOK_INPUT) == 0) {
296		sc->input = hook;
297	} else if (strcmp(name, NG_SOURCE_HOOK_OUTPUT) == 0) {
298		sc->output = hook;
299		sc->output_ifp = 0;
300		bzero(&sc->stats, sizeof(sc->stats));
301	} else
302		return (EINVAL);
303
304	return (0);
305}
306
307/*
308 * Hook has been added
309 */
310static int
311ng_source_connect(hook_p hook)
312{
313	sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
314	struct ng_mesg *msg;
315	int dummy_error = 0;
316
317	/*
318	 * If this is "output" hook, then request information
319	 * from our downstream.
320	 */
321	if (hook == sc->output) {
322		NG_MKMESSAGE(msg, NGM_ETHER_COOKIE, NGM_ETHER_GET_IFNAME,
323		    0, M_NOWAIT);
324		if (msg == NULL)
325			return (ENOBUFS);
326
327		/*
328		 * Our hook and peer hook have HK_INVALID flag set,
329		 * so we can't use NG_SEND_MSG_HOOK() macro here.
330		 */
331		NG_SEND_MSG_ID(dummy_error, sc->node, msg,
332		    NG_NODE_ID(NG_PEER_NODE(sc->output)), NG_NODE_ID(sc->node));
333	}
334
335	return (0);
336}
337
338/*
339 * Receive a control message
340 */
341static int
342ng_source_rcvmsg(node_p node, item_p item, hook_p lasthook)
343{
344	sc_p sc = NG_NODE_PRIVATE(node);
345	struct ng_mesg *msg, *resp = NULL;
346	int error = 0;
347
348	NGI_GET_MSG(item, msg);
349
350	switch (msg->header.typecookie) {
351	case NGM_SOURCE_COOKIE:
352		if (msg->header.flags & NGF_RESP) {
353			error = EINVAL;
354			break;
355		}
356		switch (msg->header.cmd) {
357		case NGM_SOURCE_GET_STATS:
358		case NGM_SOURCE_CLR_STATS:
359		case NGM_SOURCE_GETCLR_STATS:
360                    {
361			struct ng_source_stats *stats;
362
363                        if (msg->header.cmd != NGM_SOURCE_CLR_STATS) {
364                                NG_MKRESPONSE(resp, msg,
365                                    sizeof(*stats), M_NOWAIT);
366				if (resp == NULL) {
367					error = ENOMEM;
368					goto done;
369				}
370				sc->stats.queueOctets = sc->queueOctets;
371				sc->stats.queueFrames = sc->snd_queue.ifq_len;
372				if ((sc->node->nd_flags & NG_SOURCE_ACTIVE)
373				    && !timevalisset(&sc->stats.endTime)) {
374					getmicrotime(&sc->stats.elapsedTime);
375					timevalsub(&sc->stats.elapsedTime,
376					    &sc->stats.startTime);
377				}
378				stats = (struct ng_source_stats *)resp->data;
379				bcopy(&sc->stats, stats, sizeof(* stats));
380                        }
381                        if (msg->header.cmd != NGM_SOURCE_GET_STATS)
382				bzero(&sc->stats, sizeof(sc->stats));
383		    }
384		    break;
385		case NGM_SOURCE_START:
386		    {
387			uint64_t packets;
388
389			if (msg->header.arglen != sizeof(uint64_t)) {
390				error = EINVAL;
391				break;
392			}
393
394			packets = *(uint64_t *)msg->data;
395
396			error = ng_source_start(sc, packets);
397
398		    	break;
399		    }
400		case NGM_SOURCE_STOP:
401			ng_source_stop(sc);
402			break;
403		case NGM_SOURCE_CLR_DATA:
404			ng_source_clr_data(sc);
405			break;
406		case NGM_SOURCE_SETIFACE:
407		    {
408			char *ifname = (char *)msg->data;
409
410			if (msg->header.arglen < 2) {
411				error = EINVAL;
412				break;
413			}
414
415			ng_source_store_output_ifp(sc, ifname);
416			break;
417		    }
418		case NGM_SOURCE_SETPPS:
419		    {
420			uint32_t pps;
421
422			if (msg->header.arglen != sizeof(uint32_t)) {
423				error = EINVAL;
424				break;
425			}
426
427			pps = *(uint32_t *)msg->data;
428
429			sc->stats.maxPps = pps;
430
431			break;
432		    }
433		case NGM_SOURCE_SET_TIMESTAMP:
434		    {
435			struct ng_source_embed_info *embed;
436
437			embed = (struct ng_source_embed_info *)msg->data;
438			bcopy(embed, &sc->embed_timestamp, sizeof(*embed));
439
440			break;
441		    }
442		case NGM_SOURCE_GET_TIMESTAMP:
443		    {
444			struct ng_source_embed_info *embed;
445
446			NG_MKRESPONSE(resp, msg, sizeof(*embed), M_DONTWAIT);
447			if (resp == NULL) {
448				error = ENOMEM;
449				goto done;
450			}
451			embed = (struct ng_source_embed_info *)resp->data;
452			bcopy(&sc->embed_timestamp, embed, sizeof(*embed));
453
454			break;
455		    }
456		case NGM_SOURCE_SET_COUNTER:
457		    {
458			struct ng_source_embed_cnt_info *embed;
459
460			embed = (struct ng_source_embed_cnt_info *)msg->data;
461			if (embed->index >= NG_SOURCE_COUNTERS ||
462			    !(embed->width == 1 || embed->width == 2 ||
463			    embed->width == 4)) {
464				error = EINVAL;
465				goto done;
466			}
467			bcopy(embed, &sc->embed_counter[embed->index],
468			    sizeof(*embed));
469
470			break;
471		    }
472		case NGM_SOURCE_GET_COUNTER:
473		    {
474			uint8_t index = *(uint8_t *)msg->data;
475			struct ng_source_embed_cnt_info *embed;
476
477			if (index >= NG_SOURCE_COUNTERS) {
478				error = EINVAL;
479				goto done;
480			}
481			NG_MKRESPONSE(resp, msg, sizeof(*embed), M_DONTWAIT);
482			if (resp == NULL) {
483				error = ENOMEM;
484				goto done;
485			}
486			embed = (struct ng_source_embed_cnt_info *)resp->data;
487			bcopy(&sc->embed_counter[index], embed, sizeof(*embed));
488
489			break;
490		    }
491		default:
492			error = EINVAL;
493			break;
494		}
495		break;
496	case NGM_ETHER_COOKIE:
497		if (!(msg->header.flags & NGF_RESP)) {
498			error = EINVAL;
499			break;
500		}
501		switch (msg->header.cmd) {
502		case NGM_ETHER_GET_IFNAME:
503		    {
504			char *ifname = (char *)msg->data;
505
506			if (msg->header.arglen < 2) {
507				error = EINVAL;
508				break;
509			}
510
511			if (ng_source_store_output_ifp(sc, ifname) == 0)
512				ng_source_set_autosrc(sc, 0);
513			break;
514		    }
515		default:
516			error = EINVAL;
517		}
518		break;
519	default:
520		error = EINVAL;
521		break;
522	}
523
524done:
525	/* Take care of synchronous response, if any. */
526	NG_RESPOND_MSG(error, node, item, resp);
527	/* Free the message and return. */
528	NG_FREE_MSG(msg);
529	return (error);
530}
531
532/*
533 * Receive data on a hook
534 *
535 * If data comes in the input hook, enqueue it on the send queue.
536 * If data comes in the output hook, discard it.
537 */
538static int
539ng_source_rcvdata(hook_p hook, item_p item)
540{
541	sc_p sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
542	struct mbuf *m;
543	int error = 0;
544
545	NGI_GET_M(item, m);
546	NG_FREE_ITEM(item);
547
548	/* Which hook? */
549	if (hook == sc->output) {
550		/* discard */
551		NG_FREE_M(m);
552		return (error);
553	}
554	KASSERT(hook == sc->input, ("%s: no hook!", __func__));
555
556	/* Enqueue packet. */
557	/* XXX should we check IF_QFULL() ? */
558	_IF_ENQUEUE(&sc->snd_queue, m);
559	sc->queueOctets += m->m_pkthdr.len;
560	sc->last_packet = m;
561
562	return (0);
563}
564
565/*
566 * Shutdown processing
567 */
568static int
569ng_source_rmnode(node_p node)
570{
571	sc_p sc = NG_NODE_PRIVATE(node);
572
573	ng_source_stop(sc);
574	ng_source_clr_data(sc);
575	NG_NODE_SET_PRIVATE(node, NULL);
576	NG_NODE_UNREF(node);
577	free(sc, M_NETGRAPH);
578
579	return (0);
580}
581
582/*
583 * Hook disconnection
584 */
585static int
586ng_source_disconnect(hook_p hook)
587{
588	sc_p sc;
589
590	sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
591	KASSERT(sc != NULL, ("%s: null node private", __func__));
592	if (NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0 || hook == sc->output)
593		ng_rmnode_self(NG_HOOK_NODE(hook));
594	return (0);
595}
596
597/*
598 * Set sc->output_ifp to point to the the struct ifnet of the interface
599 * reached via our output hook.
600 */
601static int
602ng_source_store_output_ifp(sc_p sc, char *ifname)
603{
604	struct ifnet *ifp;
605	int s;
606
607	ifp = ifunit(ifname);
608
609	if (ifp == NULL) {
610		printf("%s: can't find interface %d\n", __func__, if_index);
611		return (EINVAL);
612	}
613	sc->output_ifp = ifp;
614
615#if 1
616	/* XXX mucking with a drivers ifqueue size is ugly but we need it
617	 * to queue a lot of packets to get close to line rate on a gigabit
618	 * interface with small packets.
619	 * XXX we should restore the original value at stop or disconnect
620	 */
621	s = splimp();		/* XXX is this required? */
622	if (ifp->if_snd.ifq_maxlen < NG_SOURCE_DRIVER_IFQ_MAXLEN) {
623		printf("ng_source: changing ifq_maxlen from %d to %d\n",
624		    ifp->if_snd.ifq_maxlen, NG_SOURCE_DRIVER_IFQ_MAXLEN);
625		ifp->if_snd.ifq_maxlen = NG_SOURCE_DRIVER_IFQ_MAXLEN;
626	}
627	splx(s);
628#endif
629	return (0);
630}
631
632/*
633 * Set the attached ethernet node's ethernet source address override flag.
634 */
635static int
636ng_source_set_autosrc(sc_p sc, uint32_t flag)
637{
638	struct ng_mesg *msg;
639	int error = 0;
640
641	NG_MKMESSAGE(msg, NGM_ETHER_COOKIE, NGM_ETHER_SET_AUTOSRC,
642	    sizeof (uint32_t), M_NOWAIT);
643	if (msg == NULL)
644		return(ENOBUFS);
645
646	*(uint32_t *)msg->data = flag;
647	NG_SEND_MSG_HOOK(error, sc->node, msg, sc->output, 0);
648	return (error);
649}
650
651/*
652 * Clear out the data we've queued
653 */
654static void
655ng_source_clr_data (sc_p sc)
656{
657	struct mbuf *m;
658
659	for (;;) {
660		_IF_DEQUEUE(&sc->snd_queue, m);
661		if (m == NULL)
662			break;
663		NG_FREE_M(m);
664	}
665	sc->queueOctets = 0;
666	sc->last_packet = 0;
667}
668
669/*
670 * Start sending queued data out the output hook
671 */
672static int
673ng_source_start(sc_p sc, uint64_t packets)
674{
675	if (sc->output_ifp == NULL) {
676		printf("ng_source: start without iface configured\n");
677		return (ENXIO);
678	}
679
680	if (sc->node->nd_flags & NG_SOURCE_ACTIVE)
681		return (EBUSY);
682
683	sc->node->nd_flags |= NG_SOURCE_ACTIVE;
684
685	sc->packets = packets;
686	timevalclear(&sc->stats.elapsedTime);
687	timevalclear(&sc->stats.endTime);
688	getmicrotime(&sc->stats.startTime);
689	getmicrotime(&sc->stats.lastTime);
690	ng_callout(&sc->intr_ch, sc->node, NULL, 0,
691	    ng_source_intr, sc, 0);
692
693	return (0);
694}
695
696/*
697 * Stop sending queued data out the output hook
698 */
699static void
700ng_source_stop(sc_p sc)
701{
702	ng_uncallout(&sc->intr_ch, sc->node);
703	sc->node->nd_flags &= ~NG_SOURCE_ACTIVE;
704	getmicrotime(&sc->stats.endTime);
705	sc->stats.elapsedTime = sc->stats.endTime;
706	timevalsub(&sc->stats.elapsedTime, &sc->stats.startTime);
707}
708
709/*
710 * While active called every NG_SOURCE_INTR_TICKS ticks.
711 * Sends as many packets as the interface connected to our
712 * output hook is able to enqueue.
713 */
714static void
715ng_source_intr(node_p node, hook_p hook, void *arg1, int arg2)
716{
717	sc_p sc = (sc_p)arg1;
718	struct ifqueue *ifq;
719	int packets;
720
721	KASSERT(sc != NULL, ("%s: null node private", __func__));
722
723	if (sc->packets == 0 || sc->output == NULL
724	    || (sc->node->nd_flags & NG_SOURCE_ACTIVE) == 0) {
725		ng_source_stop(sc);
726		return;
727	}
728
729	if (sc->output_ifp != NULL) {
730		ifq = (struct ifqueue *)&sc->output_ifp->if_snd;
731		packets = ifq->ifq_maxlen - ifq->ifq_len;
732	} else
733		packets = sc->snd_queue.ifq_len;
734
735	if (sc->stats.maxPps != 0) {
736		struct timeval	now, elapsed;
737		uint64_t	usec;
738		int		maxpkt;
739
740		getmicrotime(&now);
741		elapsed = now;
742		timevalsub(&elapsed, &sc->stats.lastTime);
743		usec = elapsed.tv_sec * 1000000 + elapsed.tv_usec;
744		maxpkt = (uint64_t)sc->stats.maxPps * usec / 1000000;
745		sc->stats.lastTime = now;
746		if (packets > maxpkt)
747			packets = maxpkt;
748	}
749
750	ng_source_send(sc, packets, NULL);
751	if (sc->packets == 0)
752		ng_source_stop(sc);
753	else
754		ng_callout(&sc->intr_ch, node, NULL, NG_SOURCE_INTR_TICKS,
755		    ng_source_intr, sc, 0);
756}
757
758/*
759 * Send packets out our output hook.
760 */
761static int
762ng_source_send(sc_p sc, int tosend, int *sent_p)
763{
764	struct mbuf *m, *m2;
765	int sent;
766	int error = 0;
767
768	KASSERT(tosend >= 0, ("%s: negative tosend param", __func__));
769	KASSERT(sc->node->nd_flags & NG_SOURCE_ACTIVE,
770	    ("%s: inactive node", __func__));
771
772	if ((uint64_t)tosend > sc->packets)
773		tosend = sc->packets;
774
775	/* Go through the queue sending packets one by one. */
776	for (sent = 0; error == 0 && sent < tosend; ++sent) {
777		_IF_DEQUEUE(&sc->snd_queue, m);
778		if (m == NULL)
779			break;
780
781		/* Duplicate and modify the packet. */
782		error = ng_source_dup_mod(sc, m, &m2);
783		if (error) {
784			if (error == ENOBUFS)
785				_IF_PREPEND(&sc->snd_queue, m);
786			else
787				_IF_ENQUEUE(&sc->snd_queue, m);
788			break;
789		}
790
791		/* Re-enqueue the original packet for us. */
792		_IF_ENQUEUE(&sc->snd_queue, m);
793
794		sc->stats.outFrames++;
795		sc->stats.outOctets += m2->m_pkthdr.len;
796		NG_SEND_DATA_ONLY(error, sc->output, m2);
797		if (error)
798			break;
799	}
800
801	sc->packets -= sent;
802	if (sent_p != NULL)
803		*sent_p = sent;
804	return (error);
805}
806
807/*
808 * Modify packet in 'm' by changing 'len' bytes starting at 'offset'
809 * to data in 'cp'.
810 *
811 * The packet data in 'm' must be in a contiguous buffer in a single mbuf.
812 */
813static void
814ng_source_packet_mod(sc_p sc, struct mbuf *m, int offset, int len, caddr_t cp,
815    int flags)
816{
817	if (len == 0)
818		return;
819
820	/* Can't modify beyond end of packet. */
821	/* TODO: Pad packet for this case. */
822	if (offset + len > m->m_len)
823		return;
824
825	bcopy(cp, mtod_off(m, offset, caddr_t), len);
826}
827
828static void
829ng_source_mod_counter(sc_p sc, struct ng_source_embed_cnt_info *cnt,
830    struct mbuf *m, int increment)
831{
832	caddr_t cp;
833	uint32_t val;
834
835	val = htonl(cnt->next_val);
836	cp = (caddr_t)&val + sizeof(val) - cnt->width;
837	ng_source_packet_mod(sc, m, cnt->offset, cnt->width, cp, cnt->flags);
838
839	if (increment) {
840		cnt->next_val += increment;
841
842		if (increment > 0 && cnt->next_val > cnt->max_val) {
843			cnt->next_val = cnt->min_val - 1 +
844			    (cnt->next_val - cnt->max_val);
845			if (cnt->next_val > cnt->max_val)
846				cnt->next_val = cnt->max_val;
847		} else if (increment < 0 && cnt->next_val < cnt->min_val) {
848			cnt->next_val = cnt->max_val + 1 +
849			    (cnt->next_val - cnt->min_val);
850			if (cnt->next_val < cnt->min_val)
851				cnt->next_val = cnt->max_val;
852		}
853	}
854}
855
856static int
857ng_source_dup_mod(sc_p sc, struct mbuf *m0, struct mbuf **m_ptr)
858{
859	struct mbuf *m;
860	struct ng_source_embed_cnt_info *cnt;
861	struct ng_source_embed_info *ts;
862	int modify;
863	int error = 0;
864	int i, increment;
865
866	/* Are we going to modify packets? */
867	modify = sc->embed_timestamp.flags & NGM_SOURCE_EMBED_ENABLE;
868	for (i = 0; !modify && i < NG_SOURCE_COUNTERS; ++i)
869		modify = sc->embed_counter[i].flags & NGM_SOURCE_EMBED_ENABLE;
870
871	/* Duplicate the packet. */
872	if (modify)
873		m = m_dup(m0, M_DONTWAIT);
874	else
875		m = m_copypacket(m0, M_DONTWAIT);
876	if (m == NULL) {
877		error = ENOBUFS;
878		goto done;
879	}
880	*m_ptr = m;
881
882	if (!modify)
883		goto done;
884
885	/* Modify the copied packet for sending. */
886	KASSERT(M_WRITABLE(m), ("%s: packet not writable", __func__));
887
888	for (i = 0; i < NG_SOURCE_COUNTERS; ++i) {
889		cnt = &sc->embed_counter[i];
890		if (cnt->flags & NGM_SOURCE_EMBED_ENABLE) {
891			if ((cnt->flags & NGM_SOURCE_INC_CNT_PER_LIST) == 0 ||
892			    sc->last_packet == m0)
893				increment = cnt->increment;
894			else
895				increment = 0;
896			ng_source_mod_counter(sc, cnt, m, increment);
897		}
898	}
899
900	ts = &sc->embed_timestamp;
901	if (ts->flags & NGM_SOURCE_EMBED_ENABLE) {
902		struct timeval now;
903		getmicrotime(&now);
904		now.tv_sec = htonl(now.tv_sec);
905		now.tv_usec = htonl(now.tv_usec);
906		ng_source_packet_mod(sc, m, ts->offset, sizeof (now),
907		    (caddr_t)&now, ts->flags);
908	}
909
910done:
911	return(error);
912}
913