summaryrefslogtreecommitdiff
path: root/libpipe/pq.c
blob: fe7dd8ae279e2f402706f899c8688d35f0bfa652 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/* Packet queues

   Copyright (C) 1995, 1996, 1998, 1999, 2002, 2006
     Free Software Foundation, Inc.

   Written by Miles Bader <miles@gnu.ai.mit.edu>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2, or (at
   your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */

#include <malloc.h>
#include <string.h>
#include <stddef.h>
#include <sys/mman.h>

#include "pq.h"

/* ---------------------------------------------------------------- */

/* Create a new packet queue, returning it in PQ.  The only possible error is
   ENOMEM.  */
error_t
pq_create (struct pq **pq)
{
  *pq = malloc (sizeof (struct pq));

  if (! *pq)
    return ENOMEM;

  (*pq)->head = (*pq)->tail = 0;
  (*pq)->free = 0;

  return 0;
}

/* Free every packet (and its contents) in the linked list rooted at HEAD.  */
static void
free_packets (struct packet *head)
{
  if (head)
    {
      struct packet *next = head->next;
      if (head->ports)
	free (head->ports);
      if (head->buf_len > 0)
	{
	  if (head->buf_vm_alloced)
	    munmap (head->buf, head->buf_len);
	  else
	    free (head->buf);
	}
      free (head);
      free_packets (next);
    }
}

/* Frees PQ and any resources it holds, including deallocating any ports in
   packets left in the queue.  */
void
pq_free (struct pq *pq)
{
  pq_drain (pq);
  free_packets (pq->free);
  free (pq);
}

/* ---------------------------------------------------------------- */

/* Remove the first packet (if any) in PQ, deallocating any resources it
   holds.  True is returned if a packet was found, false otherwise.  */
int
pq_dequeue (struct pq *pq)
{
  extern void pipe_dealloc_addr (void *addr);
  struct packet *packet = pq->head;

  if (! packet)
    return 0;

  /* Deallocate any resource in PACKET.  */
  if (packet->num_ports)
    packet_dealloc_ports (packet);
  if (packet->source)
    pipe_dealloc_addr (packet->source);

  pq->head = packet->next;
  packet->next = pq->free;
  pq->free = packet;
  if (pq->head)
    pq->head->prev = 0;
  else
    pq->tail = 0;

  return 1;
}

/* Empties out PQ.  This *will* deallocate any ports in any of the packets.  */
void
pq_drain (struct pq *pq)
{
  while (pq_dequeue (pq))
    ;
}

/* Pushes a new packet of type TYPE and source SOURCE onto the tail of the
   queue, and returns it, or 0 if there was an allocation error. */
struct packet *
pq_queue (struct pq *pq, unsigned type, void *source)
{
  struct packet *packet = pq->free;

  if (!packet)
    {
      packet = malloc (sizeof (struct packet));
      if (!packet)
	return 0;
      packet->buf = 0;
      packet->buf_len = 0;
      packet->ports = 0;
      packet->ports_alloced = 0;
      packet->buf_vm_alloced = 0;
    }
  else
    pq->free = packet->next;

  packet->num_ports = 0;
  packet->buf_start = packet->buf_end = packet->buf;

  packet->type = type;
  packet->source = source;
  packet->next = 0;
  packet->prev = pq->tail;
  if (pq->tail)
    pq->tail->next = packet;
  pq->tail = packet;
  if (!pq->head)
    pq->head = packet;

  return packet;
}

/* ---------------------------------------------------------------- */

/* Returns a legal size to which PACKET can be set allowing enough room for
   EXTRA bytes more than what's already in it, and perhaps more.  */
size_t
packet_new_size (struct packet *packet, size_t extra)
{
  size_t new_len = (packet->buf_end - packet->buf) + extra;
  if (packet->buf_vm_alloced || new_len >= PACKET_SIZE_LARGE)
    /* Round NEW_LEN up to a page boundary (OLD_LEN should already be).  */
    return round_page (new_len);
  else
    /* Otherwise, just round up to a multiple of 512 bytes.  */
    return (new_len + 511) & ~511;
}

/* Try to extend PACKET to be NEW_LEN bytes long, which should be greater
   than the current packet size.  This should be a valid length -- i.e., if
   it's greater than PACKET_SIZE_LARGE, it should be a mulitple of
   VM_PAGE_SIZE.  If PACKET cannot be extended for some reason, false is
   returned, otherwise true.  */
int
packet_extend (struct packet *packet, size_t new_len)
{
  size_t old_len = packet->buf_len;

  if (old_len == 0)
    /* No existing buffer to extend.  */
    return 0;

  if (packet->buf_vm_alloced)
    /* A vm_alloc'd packet.  */
    {
      char *extension = packet->buf + old_len;
      /* Try to allocate memory at the end of our current buffer.  */
      if (vm_allocate (mach_task_self (),
		       (vm_address_t *)&extension, new_len - old_len, 0) != 0)
	return 0;
    }
  else
    /* A malloc'd packet.  */
    {
      char *new_buf;
      char *old_buf = packet->buf;

      if (new_len >= PACKET_SIZE_LARGE)
	/* The old packet length is malloc'd, but we want to vm_allocate the
	   new length, so we'd have to copy the old contents.  */
	return 0;

      new_buf = realloc (old_buf, new_len);
      if (! new_buf)
	return 0;

      packet->buf = new_buf;
      packet->buf_start = new_buf + (packet->buf_start  - old_buf);
      packet->buf_end = new_buf + (packet->buf_end  - old_buf);
    }

  packet->buf_len = new_len;

  return 1;
}

/* Reallocate PACKET to have NEW_LEN bytes of buffer space, which should be
   greater than the current packet size.  This should be a valid length --
   i.e., if it's greater than PACKET_SIZE_LARGE, it should be a multiple of
   VM_PAGE_SIZE.  If an error occurs, PACKET is not modified and the error is
   returned.  */
error_t
packet_realloc (struct packet *packet, size_t new_len)
{
  error_t err;
  char *new_buf;
  char *old_buf = packet->buf;
  int vm_alloc = (new_len >= PACKET_SIZE_LARGE);

  /* Make a new buffer.  */
  if (vm_alloc)
    {
      new_buf = mmap (0, new_len, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
      err = (new_buf == (char *) -1) ? errno : 0;
    }
  else
    {
      new_buf = malloc (new_len);
      err = (new_buf ? 0 : ENOMEM);
    }

  if (! err)
    {
      size_t old_len = packet->buf_len;
      char *start = packet->buf_start, *end = packet->buf_end;

      /* Copy what we must.  */
      if (end != start)
	/* If there was an operation like vm_move, we could use that in the
	   case where both the old and the new buffers were vm_alloced (on
	   the assumption that creating COW pages is somewhat more costly).
	   But there's not, and memcpy may do vm_copy where it can.  Will we
	   still takes faults on the new copy, even though we've deallocated
	   the old one???  XXX */
	memcpy (new_buf, start, end - start);

      /* And get rid of the old buffer.  */
      if (old_len > 0)
	{
	  if (packet->buf_vm_alloced)
	    vm_deallocate (mach_task_self (), (vm_address_t)old_buf, old_len);
	  else
	    free (old_buf);
	}

      packet->buf = new_buf;
      packet->buf_len = new_len;
      packet->buf_vm_alloced = vm_alloc;
      packet->buf_start = new_buf;
      packet->buf_end = new_buf + (end - start);
    }

  return err;
}

/* ---------------------------------------------------------------- */

/* If PACKET has any ports, deallocates them.  */
void
packet_dealloc_ports (struct packet *packet)
{
  unsigned i;
  for (i = 0; i < packet->num_ports; i++)
    {
      mach_port_t port = packet->ports[i];
      if (port != MACH_PORT_NULL)
	mach_port_deallocate (mach_task_self (), port);
    }
}

/* Sets PACKET's ports to be PORTS, of length NUM_PORTS.  ENOMEM is returned
   if a memory allocation error occurred, otherwise, 0.  */
error_t
packet_set_ports (struct packet *packet,
		  mach_port_t *ports, size_t num_ports)
{
  if (packet->num_ports > 0)
    packet_dealloc_ports (packet);
  if (num_ports > packet->ports_alloced)
    {
      mach_port_t *new_ports = malloc (sizeof (mach_port_t) * num_ports);
      if (! new_ports)
	return ENOMEM;
      free (packet->ports);
      packet->ports = new_ports;
      packet->ports_alloced = num_ports;
    }
  memcpy (packet->ports, ports, sizeof (mach_port_t) * num_ports);
  packet->num_ports = num_ports;
  return 0;
}

/* Returns any ports in PACKET in PORTS and NUM_PORTS, and removes them from
   PACKET.  */
error_t
packet_read_ports (struct packet *packet,
		   mach_port_t **ports, size_t *num_ports)
{
  int length = packet->num_ports * sizeof (mach_port_t);
  if (*num_ports < packet->num_ports)
    {
      *ports = mmap (0, length, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);
      if (*ports == (mach_port_t *) -1)
	return errno;
    }
  *num_ports = packet->num_ports;
  memcpy (*ports, packet->ports, length);
  packet->num_ports = 0;
  return 0;
}

/* Append the bytes in DATA, of length DATA_LEN, to what's already in PACKET,
   and return the amount appended in AMOUNT if that's not the null pointer.  */
error_t
packet_write (struct packet *packet,
	      char *data, size_t data_len, size_t *amount)
{
  error_t err = packet_ensure (packet, data_len);

  if (err)
    return err;

  /* Add the new data.  */
  memcpy (packet->buf_end, data, data_len);
  packet->buf_end += data_len;
  if (amount != NULL)
    *amount = data_len;

  return 0;
}

/* Remove or peek up to AMOUNT bytes from the beginning of the data in PACKET, and
   puts it into *DATA, and the amount read into DATA_LEN.  If more than the
   original *DATA_LEN bytes are available, new memory is vm_allocated, and
   the address and length of this array put into DATA and DATA_LEN.  */
static error_t
packet_fetch (struct packet *packet,
	     char **data, size_t *data_len, size_t amount, int remove)
{
  char *start = packet->buf_start;
  char *end = packet->buf_end;

  if (amount > end - start)
    amount = end - start;

  if (amount > 0)
    {
      char *buf = packet->buf;

      if (remove && packet->buf_vm_alloced && amount >= vm_page_size)
	/* We can return memory from BUF directly without copying.  */
	{
	  if (buf + vm_page_size <= start)
	    /* BUF_START has been advanced past the start of the buffer
	       (perhaps by a series of small reads); as we're going to assume
	       everything before START is gone, make sure we deallocate any
	       memory on pages before those we return to the user.  */
	    vm_deallocate (mach_task_self (),
			   (vm_address_t)buf,
			   trunc_page (start) - (vm_address_t)buf);

	  *data = start;	/* Return the buffer directly.  */
	  start += amount;	/* Advance the read point.  */

	  if (start < end)
	    /* Since returning a partial page actually means returning the
	       whole page, we have to be careful not to grab past the page
	       boundary before the end of the data we want.  */
	    {
	      char *non_aligned_start = start;
	      start = (char *)trunc_page (start);
	      amount -= non_aligned_start - start;
	    }
	  else
	    /* This read will be up to the end of the buffer, so we can just
	       consume any space on the page following BUF_END (vm_alloced
	       buffers are always allocated in whole pages).  */
	    {
	      start = (char *)round_page (start);
	      packet->buf_end = start; /* Ensure BUF_START <= BUF_END.  */
	    }

	  /* We've actually consumed the memory at the start of BUF.  */
	  packet->buf = start;
	  packet->buf_start = start;
	  packet->buf_len -= start - buf;
	}
      else
	/* Just copy the data the old fashioned way....  */
	{
	  if (*data_len < amount)
	    *data = mmap (0, amount, PROT_READ|PROT_WRITE, MAP_ANON, 0, 0);

	  memcpy (*data, start, amount);
	  start += amount;

	  if (remove && start - buf > 2 * PACKET_SIZE_LARGE)
	    /* Get rid of unused space at the beginning of the buffer -- we
	       know it's vm_alloced because of the size, and this will allow
	       the buffer to just slide through memory.  Because we wait for
	       a relatively large amount of free space before doing this, and
	       packet_write() would have gotten rid the free space if it
	       didn't require copying much data, it's unlikely that this will
	       happen if it would have been cheaper to just move the packet
	       contents around to make space for the next write.  */
	    {
	      vm_size_t dealloc = trunc_page (start) - (vm_address_t)buf;
	      vm_deallocate (mach_task_self (), (vm_address_t)buf, dealloc);
	      packet->buf = buf + dealloc;
	      packet->buf_len -= dealloc;
	    }

	  if (remove)
	    packet->buf_start = start;
	}
    }
  *data_len = amount;

  return 0;
}

/* Removes up to AMOUNT bytes from the beginning of the data in PACKET, and
   puts it into *DATA, and the amount read into DATA_LEN.  If more than the
   original *DATA_LEN bytes are available, new memory is vm_allocated, and
   the address and length of this array put into DATA and DATA_LEN.  */
error_t
packet_read (struct packet *packet,
	     char **data, size_t *data_len, size_t amount)
{
  return packet_fetch (packet, data, data_len, amount, 1);
}

/* Peek up to AMOUNT bytes from the beginning of the data in PACKET, and
   puts it into *DATA, and the amount read into DATA_LEN.  If more than the
   original *DATA_LEN bytes are available, new memory is vm_allocated, and
   the address and length of this array put into DATA and DATA_LEN.  */
error_t
packet_peek (struct packet *packet,
	     char **data, size_t *data_len, size_t amount)
{
  return packet_fetch (packet, data, data_len, amount, 0);
}