+/**
+ * Used for qsort, this function compares two RxBufPools by size.
+ */
+static int rx_pool_size_compare(const void *p1, const void *p2)
+{
+ const RxBufPool *pool1 = *(RxBufPool **)p1;
+ const RxBufPool *pool2 = *(RxBufPool **)p2;
+
+ if (pool1->bufsize < pool2->bufsize) {
+ return -1;
+ }
+ return pool1->bufsize > pool2->bufsize;
+}
+
+/**
+ * Search for a matching buffer pool with exact matching size,
+ * or return -1 if no matching pool has been found.
+ */
+static int spapr_vlan_get_rx_pool_id(VIOsPAPRVLANDevice *dev, int size)
+{
+ int pool;
+
+ for (pool = 0; pool < RX_MAX_POOLS; pool++) {
+ if (dev->rx_pool[pool]->bufsize == size) {
+ return pool;
+ }
+ }
+
+ return -1;
+}
+
+/**
+ * Enqueuing receive buffer by adding it to one of our receive buffer pools
+ */
+static target_long spapr_vlan_add_rxbuf_to_pool(VIOsPAPRVLANDevice *dev,
+ target_ulong buf)
+{
+ int size = VLAN_BD_LEN(buf);
+ int pool;
+
+ pool = spapr_vlan_get_rx_pool_id(dev, size);
+ if (pool < 0) {
+ /*
+ * No matching pool found? Try to use a new one. If the guest used all
+ * pools before, but changed the size of one pool inbetween, we might
+ * need to recycle that pool here (if it's empty already). Thus scan
+ * all buffer pools now, starting with the last (likely empty) one.
+ */
+ for (pool = RX_MAX_POOLS - 1; pool >= 0 ; pool--) {
+ if (dev->rx_pool[pool]->count == 0) {
+ dev->rx_pool[pool]->bufsize = size;
+ /*
+ * Sort pools by size so that spapr_vlan_receive()
+ * can later find the smallest buffer pool easily.
+ */
+ qsort(dev->rx_pool, RX_MAX_POOLS, sizeof(dev->rx_pool[0]),
+ rx_pool_size_compare);
+ pool = spapr_vlan_get_rx_pool_id(dev, size);
+ DPRINTF("created RX pool %d for size %lld\n", pool,
+ VLAN_BD_LEN(buf));
+ break;
+ }
+ }
+ }
+ /* Still no usable pool? Give up */
+ if (pool < 0 || dev->rx_pool[pool]->count >= RX_POOL_MAX_BDS) {
+ return H_RESOURCE;
+ }
+
+ DPRINTF("h_add_llan_buf(): Add buf using pool %i (size %lli, count=%i)\n",
+ pool, VLAN_BD_LEN(buf), dev->rx_pool[pool]->count);
+
+ dev->rx_pool[pool]->bds[dev->rx_pool[pool]->count++] = buf;
+
+ return 0;
+}
+
+/**
+ * This is the old way of enqueuing receive buffers: Add it to the rx queue
+ * page that has been supplied by the guest (which is quite limited in size).
+ */
+static target_long spapr_vlan_add_rxbuf_to_page(VIOsPAPRVLANDevice *dev,
+ target_ulong buf)
+{
+ vlan_bd_t bd;
+
+ if (dev->rx_bufs >= VLAN_MAX_BUFS) {
+ return H_RESOURCE;
+ }
+
+ do {
+ dev->add_buf_ptr += 8;
+ if (dev->add_buf_ptr >= VLAN_RX_BDS_LEN + VLAN_RX_BDS_OFF) {
+ dev->add_buf_ptr = VLAN_RX_BDS_OFF;
+ }
+
+ bd = vio_ldq(&dev->sdev, dev->buf_list + dev->add_buf_ptr);
+ } while (bd & VLAN_BD_VALID);
+
+ vio_stq(&dev->sdev, dev->buf_list + dev->add_buf_ptr, buf);
+
+ DPRINTF("h_add_llan_buf(): Added buf ptr=%d rx_bufs=%d bd=0x%016llx\n",
+ dev->add_buf_ptr, dev->rx_bufs, (unsigned long long)buf);
+
+ return 0;
+}
+