1/*	$NetBSD: packet.c,v 1.1 2008/08/17 13:20:57 plunky Exp $	*/
2
3/*-
4 * Copyright (c) 2008 Iain Hibbert
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28/* $FreeBSD$ */
29
30#include <sys/cdefs.h>
31__RCSID("$NetBSD: packet.c,v 1.1 2008/08/17 13:20:57 plunky Exp $");
32
33#include "btpand.h"
34
35packet_t *
36packet_alloc(channel_t *chan)
37{
38	packet_t *pkt;
39
40	pkt = malloc(sizeof(packet_t) + chan->mru);
41	if (pkt == NULL) {
42		log_err("%s() failed: %m", __func__);
43		return NULL;
44	}
45
46	memset(pkt, 0, sizeof(packet_t));
47	STAILQ_INIT(&pkt->extlist);
48	pkt->ptr = pkt->buf;
49
50	pkt->chan = chan;
51	chan->refcnt++;
52
53	return pkt;
54}
55
56void
57packet_free(packet_t *pkt)
58{
59	exthdr_t *eh;
60
61	if (pkt->refcnt-- > 0)
62		return;
63
64	while ((eh = STAILQ_FIRST(&pkt->extlist)) != NULL) {
65		STAILQ_REMOVE_HEAD(&pkt->extlist, next);
66		free(eh);
67	}
68
69	pkt->chan->refcnt--;
70	if (pkt->chan->refcnt == 0)
71		channel_free(pkt->chan);
72
73	free(pkt);
74}
75
76void
77packet_adj(packet_t *pkt, size_t size)
78{
79
80	assert(pkt->refcnt == 0);
81	assert(pkt->len >= size);
82
83	pkt->ptr += size;
84	pkt->len -= size;
85}
86
87pkthdr_t *
88pkthdr_alloc(packet_t *pkt)
89{
90	pkthdr_t *ph;
91
92	ph = malloc(sizeof(pkthdr_t));
93	if (ph == NULL) {
94		log_err("%s() failed: %m", __func__);
95		return NULL;
96	}
97
98	ph->data = pkt;
99	pkt->refcnt++;
100
101	return ph;
102}
103
104void
105pkthdr_free(pkthdr_t *ph)
106{
107
108	packet_free(ph->data);
109	free(ph);
110}
111