Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * Virtio balloon implementation, inspired by Dor Laor and Marcelo
0004  * Tosatti's implementations.
0005  *
0006  *  Copyright 2008 Rusty Russell IBM Corporation
0007  */
0008 
0009 #include <linux/virtio.h>
0010 #include <linux/virtio_balloon.h>
0011 #include <linux/swap.h>
0012 #include <linux/workqueue.h>
0013 #include <linux/delay.h>
0014 #include <linux/slab.h>
0015 #include <linux/module.h>
0016 #include <linux/balloon_compaction.h>
0017 #include <linux/oom.h>
0018 #include <linux/wait.h>
0019 #include <linux/mm.h>
0020 #include <linux/page_reporting.h>
0021 
0022 /*
0023  * Balloon device works in 4K page units.  So each page is pointed to by
0024  * multiple balloon pages.  All memory counters in this driver are in balloon
0025  * page units.
0026  */
0027 #define VIRTIO_BALLOON_PAGES_PER_PAGE (unsigned int)(PAGE_SIZE >> VIRTIO_BALLOON_PFN_SHIFT)
0028 #define VIRTIO_BALLOON_ARRAY_PFNS_MAX 256
0029 /* Maximum number of (4k) pages to deflate on OOM notifications. */
0030 #define VIRTIO_BALLOON_OOM_NR_PAGES 256
0031 #define VIRTIO_BALLOON_OOM_NOTIFY_PRIORITY 80
0032 
0033 #define VIRTIO_BALLOON_FREE_PAGE_ALLOC_FLAG (__GFP_NORETRY | __GFP_NOWARN | \
0034                          __GFP_NOMEMALLOC)
0035 /* The order of free page blocks to report to host */
0036 #define VIRTIO_BALLOON_HINT_BLOCK_ORDER (MAX_ORDER - 1)
0037 /* The size of a free page block in bytes */
0038 #define VIRTIO_BALLOON_HINT_BLOCK_BYTES \
0039     (1 << (VIRTIO_BALLOON_HINT_BLOCK_ORDER + PAGE_SHIFT))
0040 #define VIRTIO_BALLOON_HINT_BLOCK_PAGES (1 << VIRTIO_BALLOON_HINT_BLOCK_ORDER)
0041 
0042 enum virtio_balloon_vq {
0043     VIRTIO_BALLOON_VQ_INFLATE,
0044     VIRTIO_BALLOON_VQ_DEFLATE,
0045     VIRTIO_BALLOON_VQ_STATS,
0046     VIRTIO_BALLOON_VQ_FREE_PAGE,
0047     VIRTIO_BALLOON_VQ_REPORTING,
0048     VIRTIO_BALLOON_VQ_MAX
0049 };
0050 
0051 enum virtio_balloon_config_read {
0052     VIRTIO_BALLOON_CONFIG_READ_CMD_ID = 0,
0053 };
0054 
0055 struct virtio_balloon {
0056     struct virtio_device *vdev;
0057     struct virtqueue *inflate_vq, *deflate_vq, *stats_vq, *free_page_vq;
0058 
0059     /* Balloon's own wq for cpu-intensive work items */
0060     struct workqueue_struct *balloon_wq;
0061     /* The free page reporting work item submitted to the balloon wq */
0062     struct work_struct report_free_page_work;
0063 
0064     /* The balloon servicing is delegated to a freezable workqueue. */
0065     struct work_struct update_balloon_stats_work;
0066     struct work_struct update_balloon_size_work;
0067 
0068     /* Prevent updating balloon when it is being canceled. */
0069     spinlock_t stop_update_lock;
0070     bool stop_update;
0071     /* Bitmap to indicate if reading the related config fields are needed */
0072     unsigned long config_read_bitmap;
0073 
0074     /* The list of allocated free pages, waiting to be given back to mm */
0075     struct list_head free_page_list;
0076     spinlock_t free_page_list_lock;
0077     /* The number of free page blocks on the above list */
0078     unsigned long num_free_page_blocks;
0079     /*
0080      * The cmd id received from host.
0081      * Read it via virtio_balloon_cmd_id_received to get the latest value
0082      * sent from host.
0083      */
0084     u32 cmd_id_received_cache;
0085     /* The cmd id that is actively in use */
0086     __virtio32 cmd_id_active;
0087     /* Buffer to store the stop sign */
0088     __virtio32 cmd_id_stop;
0089 
0090     /* Waiting for host to ack the pages we released. */
0091     wait_queue_head_t acked;
0092 
0093     /* Number of balloon pages we've told the Host we're not using. */
0094     unsigned int num_pages;
0095     /*
0096      * The pages we've told the Host we're not using are enqueued
0097      * at vb_dev_info->pages list.
0098      * Each page on this list adds VIRTIO_BALLOON_PAGES_PER_PAGE
0099      * to num_pages above.
0100      */
0101     struct balloon_dev_info vb_dev_info;
0102 
0103     /* Synchronize access/update to this struct virtio_balloon elements */
0104     struct mutex balloon_lock;
0105 
0106     /* The array of pfns we tell the Host about. */
0107     unsigned int num_pfns;
0108     __virtio32 pfns[VIRTIO_BALLOON_ARRAY_PFNS_MAX];
0109 
0110     /* Memory statistics */
0111     struct virtio_balloon_stat stats[VIRTIO_BALLOON_S_NR];
0112 
0113     /* Shrinker to return free pages - VIRTIO_BALLOON_F_FREE_PAGE_HINT */
0114     struct shrinker shrinker;
0115 
0116     /* OOM notifier to deflate on OOM - VIRTIO_BALLOON_F_DEFLATE_ON_OOM */
0117     struct notifier_block oom_nb;
0118 
0119     /* Free page reporting device */
0120     struct virtqueue *reporting_vq;
0121     struct page_reporting_dev_info pr_dev_info;
0122 };
0123 
0124 static const struct virtio_device_id id_table[] = {
0125     { VIRTIO_ID_BALLOON, VIRTIO_DEV_ANY_ID },
0126     { 0 },
0127 };
0128 
0129 static u32 page_to_balloon_pfn(struct page *page)
0130 {
0131     unsigned long pfn = page_to_pfn(page);
0132 
0133     BUILD_BUG_ON(PAGE_SHIFT < VIRTIO_BALLOON_PFN_SHIFT);
0134     /* Convert pfn from Linux page size to balloon page size. */
0135     return pfn * VIRTIO_BALLOON_PAGES_PER_PAGE;
0136 }
0137 
0138 static void balloon_ack(struct virtqueue *vq)
0139 {
0140     struct virtio_balloon *vb = vq->vdev->priv;
0141 
0142     wake_up(&vb->acked);
0143 }
0144 
0145 static void tell_host(struct virtio_balloon *vb, struct virtqueue *vq)
0146 {
0147     struct scatterlist sg;
0148     unsigned int len;
0149 
0150     sg_init_one(&sg, vb->pfns, sizeof(vb->pfns[0]) * vb->num_pfns);
0151 
0152     /* We should always be able to add one buffer to an empty queue. */
0153     virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
0154     virtqueue_kick(vq);
0155 
0156     /* When host has read buffer, this completes via balloon_ack */
0157     wait_event(vb->acked, virtqueue_get_buf(vq, &len));
0158 
0159 }
0160 
0161 static int virtballoon_free_page_report(struct page_reporting_dev_info *pr_dev_info,
0162                    struct scatterlist *sg, unsigned int nents)
0163 {
0164     struct virtio_balloon *vb =
0165         container_of(pr_dev_info, struct virtio_balloon, pr_dev_info);
0166     struct virtqueue *vq = vb->reporting_vq;
0167     unsigned int unused, err;
0168 
0169     /* We should always be able to add these buffers to an empty queue. */
0170     err = virtqueue_add_inbuf(vq, sg, nents, vb, GFP_NOWAIT | __GFP_NOWARN);
0171 
0172     /*
0173      * In the extremely unlikely case that something has occurred and we
0174      * are able to trigger an error we will simply display a warning
0175      * and exit without actually processing the pages.
0176      */
0177     if (WARN_ON_ONCE(err))
0178         return err;
0179 
0180     virtqueue_kick(vq);
0181 
0182     /* When host has read buffer, this completes via balloon_ack */
0183     wait_event(vb->acked, virtqueue_get_buf(vq, &unused));
0184 
0185     return 0;
0186 }
0187 
0188 static void set_page_pfns(struct virtio_balloon *vb,
0189               __virtio32 pfns[], struct page *page)
0190 {
0191     unsigned int i;
0192 
0193     BUILD_BUG_ON(VIRTIO_BALLOON_PAGES_PER_PAGE > VIRTIO_BALLOON_ARRAY_PFNS_MAX);
0194 
0195     /*
0196      * Set balloon pfns pointing at this page.
0197      * Note that the first pfn points at start of the page.
0198      */
0199     for (i = 0; i < VIRTIO_BALLOON_PAGES_PER_PAGE; i++)
0200         pfns[i] = cpu_to_virtio32(vb->vdev,
0201                       page_to_balloon_pfn(page) + i);
0202 }
0203 
0204 static unsigned int fill_balloon(struct virtio_balloon *vb, size_t num)
0205 {
0206     unsigned int num_allocated_pages;
0207     unsigned int num_pfns;
0208     struct page *page;
0209     LIST_HEAD(pages);
0210 
0211     /* We can only do one array worth at a time. */
0212     num = min(num, ARRAY_SIZE(vb->pfns));
0213 
0214     for (num_pfns = 0; num_pfns < num;
0215          num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
0216         struct page *page = balloon_page_alloc();
0217 
0218         if (!page) {
0219             dev_info_ratelimited(&vb->vdev->dev,
0220                          "Out of puff! Can't get %u pages\n",
0221                          VIRTIO_BALLOON_PAGES_PER_PAGE);
0222             /* Sleep for at least 1/5 of a second before retry. */
0223             msleep(200);
0224             break;
0225         }
0226 
0227         balloon_page_push(&pages, page);
0228     }
0229 
0230     mutex_lock(&vb->balloon_lock);
0231 
0232     vb->num_pfns = 0;
0233 
0234     while ((page = balloon_page_pop(&pages))) {
0235         balloon_page_enqueue(&vb->vb_dev_info, page);
0236 
0237         set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
0238         vb->num_pages += VIRTIO_BALLOON_PAGES_PER_PAGE;
0239         if (!virtio_has_feature(vb->vdev,
0240                     VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
0241             adjust_managed_page_count(page, -1);
0242         vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE;
0243     }
0244 
0245     num_allocated_pages = vb->num_pfns;
0246     /* Did we get any? */
0247     if (vb->num_pfns != 0)
0248         tell_host(vb, vb->inflate_vq);
0249     mutex_unlock(&vb->balloon_lock);
0250 
0251     return num_allocated_pages;
0252 }
0253 
0254 static void release_pages_balloon(struct virtio_balloon *vb,
0255                  struct list_head *pages)
0256 {
0257     struct page *page, *next;
0258 
0259     list_for_each_entry_safe(page, next, pages, lru) {
0260         if (!virtio_has_feature(vb->vdev,
0261                     VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
0262             adjust_managed_page_count(page, 1);
0263         list_del(&page->lru);
0264         put_page(page); /* balloon reference */
0265     }
0266 }
0267 
0268 static unsigned int leak_balloon(struct virtio_balloon *vb, size_t num)
0269 {
0270     unsigned int num_freed_pages;
0271     struct page *page;
0272     struct balloon_dev_info *vb_dev_info = &vb->vb_dev_info;
0273     LIST_HEAD(pages);
0274 
0275     /* We can only do one array worth at a time. */
0276     num = min(num, ARRAY_SIZE(vb->pfns));
0277 
0278     mutex_lock(&vb->balloon_lock);
0279     /* We can't release more pages than taken */
0280     num = min(num, (size_t)vb->num_pages);
0281     for (vb->num_pfns = 0; vb->num_pfns < num;
0282          vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
0283         page = balloon_page_dequeue(vb_dev_info);
0284         if (!page)
0285             break;
0286         set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
0287         list_add(&page->lru, &pages);
0288         vb->num_pages -= VIRTIO_BALLOON_PAGES_PER_PAGE;
0289     }
0290 
0291     num_freed_pages = vb->num_pfns;
0292     /*
0293      * Note that if
0294      * virtio_has_feature(vdev, VIRTIO_BALLOON_F_MUST_TELL_HOST);
0295      * is true, we *have* to do it in this order
0296      */
0297     if (vb->num_pfns != 0)
0298         tell_host(vb, vb->deflate_vq);
0299     release_pages_balloon(vb, &pages);
0300     mutex_unlock(&vb->balloon_lock);
0301     return num_freed_pages;
0302 }
0303 
0304 static inline void update_stat(struct virtio_balloon *vb, int idx,
0305                    u16 tag, u64 val)
0306 {
0307     BUG_ON(idx >= VIRTIO_BALLOON_S_NR);
0308     vb->stats[idx].tag = cpu_to_virtio16(vb->vdev, tag);
0309     vb->stats[idx].val = cpu_to_virtio64(vb->vdev, val);
0310 }
0311 
0312 #define pages_to_bytes(x) ((u64)(x) << PAGE_SHIFT)
0313 
0314 static unsigned int update_balloon_stats(struct virtio_balloon *vb)
0315 {
0316     unsigned long events[NR_VM_EVENT_ITEMS];
0317     struct sysinfo i;
0318     unsigned int idx = 0;
0319     long available;
0320     unsigned long caches;
0321 
0322     all_vm_events(events);
0323     si_meminfo(&i);
0324 
0325     available = si_mem_available();
0326     caches = global_node_page_state(NR_FILE_PAGES);
0327 
0328 #ifdef CONFIG_VM_EVENT_COUNTERS
0329     update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_IN,
0330                 pages_to_bytes(events[PSWPIN]));
0331     update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_OUT,
0332                 pages_to_bytes(events[PSWPOUT]));
0333     update_stat(vb, idx++, VIRTIO_BALLOON_S_MAJFLT, events[PGMAJFAULT]);
0334     update_stat(vb, idx++, VIRTIO_BALLOON_S_MINFLT, events[PGFAULT]);
0335 #ifdef CONFIG_HUGETLB_PAGE
0336     update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGALLOC,
0337             events[HTLB_BUDDY_PGALLOC]);
0338     update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGFAIL,
0339             events[HTLB_BUDDY_PGALLOC_FAIL]);
0340 #endif
0341 #endif
0342     update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMFREE,
0343                 pages_to_bytes(i.freeram));
0344     update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMTOT,
0345                 pages_to_bytes(i.totalram));
0346     update_stat(vb, idx++, VIRTIO_BALLOON_S_AVAIL,
0347                 pages_to_bytes(available));
0348     update_stat(vb, idx++, VIRTIO_BALLOON_S_CACHES,
0349                 pages_to_bytes(caches));
0350 
0351     return idx;
0352 }
0353 
0354 /*
0355  * While most virtqueues communicate guest-initiated requests to the hypervisor,
0356  * the stats queue operates in reverse.  The driver initializes the virtqueue
0357  * with a single buffer.  From that point forward, all conversations consist of
0358  * a hypervisor request (a call to this function) which directs us to refill
0359  * the virtqueue with a fresh stats buffer.  Since stats collection can sleep,
0360  * we delegate the job to a freezable workqueue that will do the actual work via
0361  * stats_handle_request().
0362  */
0363 static void stats_request(struct virtqueue *vq)
0364 {
0365     struct virtio_balloon *vb = vq->vdev->priv;
0366 
0367     spin_lock(&vb->stop_update_lock);
0368     if (!vb->stop_update)
0369         queue_work(system_freezable_wq, &vb->update_balloon_stats_work);
0370     spin_unlock(&vb->stop_update_lock);
0371 }
0372 
0373 static void stats_handle_request(struct virtio_balloon *vb)
0374 {
0375     struct virtqueue *vq;
0376     struct scatterlist sg;
0377     unsigned int len, num_stats;
0378 
0379     num_stats = update_balloon_stats(vb);
0380 
0381     vq = vb->stats_vq;
0382     if (!virtqueue_get_buf(vq, &len))
0383         return;
0384     sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
0385     virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
0386     virtqueue_kick(vq);
0387 }
0388 
0389 static inline s64 towards_target(struct virtio_balloon *vb)
0390 {
0391     s64 target;
0392     u32 num_pages;
0393 
0394     /* Legacy balloon config space is LE, unlike all other devices. */
0395     virtio_cread_le(vb->vdev, struct virtio_balloon_config, num_pages,
0396             &num_pages);
0397 
0398     target = num_pages;
0399     return target - vb->num_pages;
0400 }
0401 
0402 /* Gives back @num_to_return blocks of free pages to mm. */
0403 static unsigned long return_free_pages_to_mm(struct virtio_balloon *vb,
0404                          unsigned long num_to_return)
0405 {
0406     struct page *page;
0407     unsigned long num_returned;
0408 
0409     spin_lock_irq(&vb->free_page_list_lock);
0410     for (num_returned = 0; num_returned < num_to_return; num_returned++) {
0411         page = balloon_page_pop(&vb->free_page_list);
0412         if (!page)
0413             break;
0414         free_pages((unsigned long)page_address(page),
0415                VIRTIO_BALLOON_HINT_BLOCK_ORDER);
0416     }
0417     vb->num_free_page_blocks -= num_returned;
0418     spin_unlock_irq(&vb->free_page_list_lock);
0419 
0420     return num_returned;
0421 }
0422 
0423 static void virtio_balloon_queue_free_page_work(struct virtio_balloon *vb)
0424 {
0425     if (!virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
0426         return;
0427 
0428     /* No need to queue the work if the bit was already set. */
0429     if (test_and_set_bit(VIRTIO_BALLOON_CONFIG_READ_CMD_ID,
0430                  &vb->config_read_bitmap))
0431         return;
0432 
0433     queue_work(vb->balloon_wq, &vb->report_free_page_work);
0434 }
0435 
0436 static void virtballoon_changed(struct virtio_device *vdev)
0437 {
0438     struct virtio_balloon *vb = vdev->priv;
0439     unsigned long flags;
0440 
0441     spin_lock_irqsave(&vb->stop_update_lock, flags);
0442     if (!vb->stop_update) {
0443         queue_work(system_freezable_wq,
0444                &vb->update_balloon_size_work);
0445         virtio_balloon_queue_free_page_work(vb);
0446     }
0447     spin_unlock_irqrestore(&vb->stop_update_lock, flags);
0448 }
0449 
0450 static void update_balloon_size(struct virtio_balloon *vb)
0451 {
0452     u32 actual = vb->num_pages;
0453 
0454     /* Legacy balloon config space is LE, unlike all other devices. */
0455     virtio_cwrite_le(vb->vdev, struct virtio_balloon_config, actual,
0456              &actual);
0457 }
0458 
0459 static void update_balloon_stats_func(struct work_struct *work)
0460 {
0461     struct virtio_balloon *vb;
0462 
0463     vb = container_of(work, struct virtio_balloon,
0464               update_balloon_stats_work);
0465     stats_handle_request(vb);
0466 }
0467 
0468 static void update_balloon_size_func(struct work_struct *work)
0469 {
0470     struct virtio_balloon *vb;
0471     s64 diff;
0472 
0473     vb = container_of(work, struct virtio_balloon,
0474               update_balloon_size_work);
0475     diff = towards_target(vb);
0476 
0477     if (!diff)
0478         return;
0479 
0480     if (diff > 0)
0481         diff -= fill_balloon(vb, diff);
0482     else
0483         diff += leak_balloon(vb, -diff);
0484     update_balloon_size(vb);
0485 
0486     if (diff)
0487         queue_work(system_freezable_wq, work);
0488 }
0489 
0490 static int init_vqs(struct virtio_balloon *vb)
0491 {
0492     struct virtqueue *vqs[VIRTIO_BALLOON_VQ_MAX];
0493     vq_callback_t *callbacks[VIRTIO_BALLOON_VQ_MAX];
0494     const char *names[VIRTIO_BALLOON_VQ_MAX];
0495     int err;
0496 
0497     /*
0498      * Inflateq and deflateq are used unconditionally. The names[]
0499      * will be NULL if the related feature is not enabled, which will
0500      * cause no allocation for the corresponding virtqueue in find_vqs.
0501      */
0502     callbacks[VIRTIO_BALLOON_VQ_INFLATE] = balloon_ack;
0503     names[VIRTIO_BALLOON_VQ_INFLATE] = "inflate";
0504     callbacks[VIRTIO_BALLOON_VQ_DEFLATE] = balloon_ack;
0505     names[VIRTIO_BALLOON_VQ_DEFLATE] = "deflate";
0506     callbacks[VIRTIO_BALLOON_VQ_STATS] = NULL;
0507     names[VIRTIO_BALLOON_VQ_STATS] = NULL;
0508     callbacks[VIRTIO_BALLOON_VQ_FREE_PAGE] = NULL;
0509     names[VIRTIO_BALLOON_VQ_FREE_PAGE] = NULL;
0510     names[VIRTIO_BALLOON_VQ_REPORTING] = NULL;
0511 
0512     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
0513         names[VIRTIO_BALLOON_VQ_STATS] = "stats";
0514         callbacks[VIRTIO_BALLOON_VQ_STATS] = stats_request;
0515     }
0516 
0517     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
0518         names[VIRTIO_BALLOON_VQ_FREE_PAGE] = "free_page_vq";
0519         callbacks[VIRTIO_BALLOON_VQ_FREE_PAGE] = NULL;
0520     }
0521 
0522     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING)) {
0523         names[VIRTIO_BALLOON_VQ_REPORTING] = "reporting_vq";
0524         callbacks[VIRTIO_BALLOON_VQ_REPORTING] = balloon_ack;
0525     }
0526 
0527     err = virtio_find_vqs(vb->vdev, VIRTIO_BALLOON_VQ_MAX, vqs,
0528                   callbacks, names, NULL);
0529     if (err)
0530         return err;
0531 
0532     vb->inflate_vq = vqs[VIRTIO_BALLOON_VQ_INFLATE];
0533     vb->deflate_vq = vqs[VIRTIO_BALLOON_VQ_DEFLATE];
0534     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
0535         struct scatterlist sg;
0536         unsigned int num_stats;
0537         vb->stats_vq = vqs[VIRTIO_BALLOON_VQ_STATS];
0538 
0539         /*
0540          * Prime this virtqueue with one buffer so the hypervisor can
0541          * use it to signal us later (it can't be broken yet!).
0542          */
0543         num_stats = update_balloon_stats(vb);
0544 
0545         sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
0546         err = virtqueue_add_outbuf(vb->stats_vq, &sg, 1, vb,
0547                        GFP_KERNEL);
0548         if (err) {
0549             dev_warn(&vb->vdev->dev, "%s: add stat_vq failed\n",
0550                  __func__);
0551             return err;
0552         }
0553         virtqueue_kick(vb->stats_vq);
0554     }
0555 
0556     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
0557         vb->free_page_vq = vqs[VIRTIO_BALLOON_VQ_FREE_PAGE];
0558 
0559     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING))
0560         vb->reporting_vq = vqs[VIRTIO_BALLOON_VQ_REPORTING];
0561 
0562     return 0;
0563 }
0564 
0565 static u32 virtio_balloon_cmd_id_received(struct virtio_balloon *vb)
0566 {
0567     if (test_and_clear_bit(VIRTIO_BALLOON_CONFIG_READ_CMD_ID,
0568                    &vb->config_read_bitmap)) {
0569         /* Legacy balloon config space is LE, unlike all other devices. */
0570         virtio_cread_le(vb->vdev, struct virtio_balloon_config,
0571                 free_page_hint_cmd_id,
0572                 &vb->cmd_id_received_cache);
0573     }
0574 
0575     return vb->cmd_id_received_cache;
0576 }
0577 
0578 static int send_cmd_id_start(struct virtio_balloon *vb)
0579 {
0580     struct scatterlist sg;
0581     struct virtqueue *vq = vb->free_page_vq;
0582     int err, unused;
0583 
0584     /* Detach all the used buffers from the vq */
0585     while (virtqueue_get_buf(vq, &unused))
0586         ;
0587 
0588     vb->cmd_id_active = cpu_to_virtio32(vb->vdev,
0589                     virtio_balloon_cmd_id_received(vb));
0590     sg_init_one(&sg, &vb->cmd_id_active, sizeof(vb->cmd_id_active));
0591     err = virtqueue_add_outbuf(vq, &sg, 1, &vb->cmd_id_active, GFP_KERNEL);
0592     if (!err)
0593         virtqueue_kick(vq);
0594     return err;
0595 }
0596 
0597 static int send_cmd_id_stop(struct virtio_balloon *vb)
0598 {
0599     struct scatterlist sg;
0600     struct virtqueue *vq = vb->free_page_vq;
0601     int err, unused;
0602 
0603     /* Detach all the used buffers from the vq */
0604     while (virtqueue_get_buf(vq, &unused))
0605         ;
0606 
0607     sg_init_one(&sg, &vb->cmd_id_stop, sizeof(vb->cmd_id_stop));
0608     err = virtqueue_add_outbuf(vq, &sg, 1, &vb->cmd_id_stop, GFP_KERNEL);
0609     if (!err)
0610         virtqueue_kick(vq);
0611     return err;
0612 }
0613 
0614 static int get_free_page_and_send(struct virtio_balloon *vb)
0615 {
0616     struct virtqueue *vq = vb->free_page_vq;
0617     struct page *page;
0618     struct scatterlist sg;
0619     int err, unused;
0620     void *p;
0621 
0622     /* Detach all the used buffers from the vq */
0623     while (virtqueue_get_buf(vq, &unused))
0624         ;
0625 
0626     page = alloc_pages(VIRTIO_BALLOON_FREE_PAGE_ALLOC_FLAG,
0627                VIRTIO_BALLOON_HINT_BLOCK_ORDER);
0628     /*
0629      * When the allocation returns NULL, it indicates that we have got all
0630      * the possible free pages, so return -EINTR to stop.
0631      */
0632     if (!page)
0633         return -EINTR;
0634 
0635     p = page_address(page);
0636     sg_init_one(&sg, p, VIRTIO_BALLOON_HINT_BLOCK_BYTES);
0637     /* There is always 1 entry reserved for the cmd id to use. */
0638     if (vq->num_free > 1) {
0639         err = virtqueue_add_inbuf(vq, &sg, 1, p, GFP_KERNEL);
0640         if (unlikely(err)) {
0641             free_pages((unsigned long)p,
0642                    VIRTIO_BALLOON_HINT_BLOCK_ORDER);
0643             return err;
0644         }
0645         virtqueue_kick(vq);
0646         spin_lock_irq(&vb->free_page_list_lock);
0647         balloon_page_push(&vb->free_page_list, page);
0648         vb->num_free_page_blocks++;
0649         spin_unlock_irq(&vb->free_page_list_lock);
0650     } else {
0651         /*
0652          * The vq has no available entry to add this page block, so
0653          * just free it.
0654          */
0655         free_pages((unsigned long)p, VIRTIO_BALLOON_HINT_BLOCK_ORDER);
0656     }
0657 
0658     return 0;
0659 }
0660 
0661 static int send_free_pages(struct virtio_balloon *vb)
0662 {
0663     int err;
0664     u32 cmd_id_active;
0665 
0666     while (1) {
0667         /*
0668          * If a stop id or a new cmd id was just received from host,
0669          * stop the reporting.
0670          */
0671         cmd_id_active = virtio32_to_cpu(vb->vdev, vb->cmd_id_active);
0672         if (unlikely(cmd_id_active !=
0673                  virtio_balloon_cmd_id_received(vb)))
0674             break;
0675 
0676         /*
0677          * The free page blocks are allocated and sent to host one by
0678          * one.
0679          */
0680         err = get_free_page_and_send(vb);
0681         if (err == -EINTR)
0682             break;
0683         else if (unlikely(err))
0684             return err;
0685     }
0686 
0687     return 0;
0688 }
0689 
0690 static void virtio_balloon_report_free_page(struct virtio_balloon *vb)
0691 {
0692     int err;
0693     struct device *dev = &vb->vdev->dev;
0694 
0695     /* Start by sending the received cmd id to host with an outbuf. */
0696     err = send_cmd_id_start(vb);
0697     if (unlikely(err))
0698         dev_err(dev, "Failed to send a start id, err = %d\n", err);
0699 
0700     err = send_free_pages(vb);
0701     if (unlikely(err))
0702         dev_err(dev, "Failed to send a free page, err = %d\n", err);
0703 
0704     /* End by sending a stop id to host with an outbuf. */
0705     err = send_cmd_id_stop(vb);
0706     if (unlikely(err))
0707         dev_err(dev, "Failed to send a stop id, err = %d\n", err);
0708 }
0709 
0710 static void report_free_page_func(struct work_struct *work)
0711 {
0712     struct virtio_balloon *vb = container_of(work, struct virtio_balloon,
0713                          report_free_page_work);
0714     u32 cmd_id_received;
0715 
0716     cmd_id_received = virtio_balloon_cmd_id_received(vb);
0717     if (cmd_id_received == VIRTIO_BALLOON_CMD_ID_DONE) {
0718         /* Pass ULONG_MAX to give back all the free pages */
0719         return_free_pages_to_mm(vb, ULONG_MAX);
0720     } else if (cmd_id_received != VIRTIO_BALLOON_CMD_ID_STOP &&
0721            cmd_id_received !=
0722            virtio32_to_cpu(vb->vdev, vb->cmd_id_active)) {
0723         virtio_balloon_report_free_page(vb);
0724     }
0725 }
0726 
0727 #ifdef CONFIG_BALLOON_COMPACTION
0728 /*
0729  * virtballoon_migratepage - perform the balloon page migration on behalf of
0730  *               a compaction thread.     (called under page lock)
0731  * @vb_dev_info: the balloon device
0732  * @newpage: page that will replace the isolated page after migration finishes.
0733  * @page   : the isolated (old) page that is about to be migrated to newpage.
0734  * @mode   : compaction mode -- not used for balloon page migration.
0735  *
0736  * After a ballooned page gets isolated by compaction procedures, this is the
0737  * function that performs the page migration on behalf of a compaction thread
0738  * The page migration for virtio balloon is done in a simple swap fashion which
0739  * follows these two macro steps:
0740  *  1) insert newpage into vb->pages list and update the host about it;
0741  *  2) update the host about the old page removed from vb->pages list;
0742  *
0743  * This function preforms the balloon page migration task.
0744  * Called through balloon_mapping->a_ops->migratepage
0745  */
0746 static int virtballoon_migratepage(struct balloon_dev_info *vb_dev_info,
0747         struct page *newpage, struct page *page, enum migrate_mode mode)
0748 {
0749     struct virtio_balloon *vb = container_of(vb_dev_info,
0750             struct virtio_balloon, vb_dev_info);
0751     unsigned long flags;
0752 
0753     /*
0754      * In order to avoid lock contention while migrating pages concurrently
0755      * to leak_balloon() or fill_balloon() we just give up the balloon_lock
0756      * this turn, as it is easier to retry the page migration later.
0757      * This also prevents fill_balloon() getting stuck into a mutex
0758      * recursion in the case it ends up triggering memory compaction
0759      * while it is attempting to inflate the ballon.
0760      */
0761     if (!mutex_trylock(&vb->balloon_lock))
0762         return -EAGAIN;
0763 
0764     get_page(newpage); /* balloon reference */
0765 
0766     /*
0767       * When we migrate a page to a different zone and adjusted the
0768       * managed page count when inflating, we have to fixup the count of
0769       * both involved zones.
0770       */
0771     if (!virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM) &&
0772         page_zone(page) != page_zone(newpage)) {
0773         adjust_managed_page_count(page, 1);
0774         adjust_managed_page_count(newpage, -1);
0775     }
0776 
0777     /* balloon's page migration 1st step  -- inflate "newpage" */
0778     spin_lock_irqsave(&vb_dev_info->pages_lock, flags);
0779     balloon_page_insert(vb_dev_info, newpage);
0780     vb_dev_info->isolated_pages--;
0781     __count_vm_event(BALLOON_MIGRATE);
0782     spin_unlock_irqrestore(&vb_dev_info->pages_lock, flags);
0783     vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
0784     set_page_pfns(vb, vb->pfns, newpage);
0785     tell_host(vb, vb->inflate_vq);
0786 
0787     /* balloon's page migration 2nd step -- deflate "page" */
0788     spin_lock_irqsave(&vb_dev_info->pages_lock, flags);
0789     balloon_page_delete(page);
0790     spin_unlock_irqrestore(&vb_dev_info->pages_lock, flags);
0791     vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
0792     set_page_pfns(vb, vb->pfns, page);
0793     tell_host(vb, vb->deflate_vq);
0794 
0795     mutex_unlock(&vb->balloon_lock);
0796 
0797     put_page(page); /* balloon reference */
0798 
0799     return MIGRATEPAGE_SUCCESS;
0800 }
0801 #endif /* CONFIG_BALLOON_COMPACTION */
0802 
0803 static unsigned long shrink_free_pages(struct virtio_balloon *vb,
0804                        unsigned long pages_to_free)
0805 {
0806     unsigned long blocks_to_free, blocks_freed;
0807 
0808     pages_to_free = round_up(pages_to_free,
0809                  VIRTIO_BALLOON_HINT_BLOCK_PAGES);
0810     blocks_to_free = pages_to_free / VIRTIO_BALLOON_HINT_BLOCK_PAGES;
0811     blocks_freed = return_free_pages_to_mm(vb, blocks_to_free);
0812 
0813     return blocks_freed * VIRTIO_BALLOON_HINT_BLOCK_PAGES;
0814 }
0815 
0816 static unsigned long virtio_balloon_shrinker_scan(struct shrinker *shrinker,
0817                           struct shrink_control *sc)
0818 {
0819     struct virtio_balloon *vb = container_of(shrinker,
0820                     struct virtio_balloon, shrinker);
0821 
0822     return shrink_free_pages(vb, sc->nr_to_scan);
0823 }
0824 
0825 static unsigned long virtio_balloon_shrinker_count(struct shrinker *shrinker,
0826                            struct shrink_control *sc)
0827 {
0828     struct virtio_balloon *vb = container_of(shrinker,
0829                     struct virtio_balloon, shrinker);
0830 
0831     return vb->num_free_page_blocks * VIRTIO_BALLOON_HINT_BLOCK_PAGES;
0832 }
0833 
0834 static int virtio_balloon_oom_notify(struct notifier_block *nb,
0835                      unsigned long dummy, void *parm)
0836 {
0837     struct virtio_balloon *vb = container_of(nb,
0838                          struct virtio_balloon, oom_nb);
0839     unsigned long *freed = parm;
0840 
0841     *freed += leak_balloon(vb, VIRTIO_BALLOON_OOM_NR_PAGES) /
0842           VIRTIO_BALLOON_PAGES_PER_PAGE;
0843     update_balloon_size(vb);
0844 
0845     return NOTIFY_OK;
0846 }
0847 
0848 static void virtio_balloon_unregister_shrinker(struct virtio_balloon *vb)
0849 {
0850     unregister_shrinker(&vb->shrinker);
0851 }
0852 
0853 static int virtio_balloon_register_shrinker(struct virtio_balloon *vb)
0854 {
0855     vb->shrinker.scan_objects = virtio_balloon_shrinker_scan;
0856     vb->shrinker.count_objects = virtio_balloon_shrinker_count;
0857     vb->shrinker.seeks = DEFAULT_SEEKS;
0858 
0859     return register_shrinker(&vb->shrinker, "virtio-balloon");
0860 }
0861 
0862 static int virtballoon_probe(struct virtio_device *vdev)
0863 {
0864     struct virtio_balloon *vb;
0865     int err;
0866 
0867     if (!vdev->config->get) {
0868         dev_err(&vdev->dev, "%s failure: config access disabled\n",
0869             __func__);
0870         return -EINVAL;
0871     }
0872 
0873     vdev->priv = vb = kzalloc(sizeof(*vb), GFP_KERNEL);
0874     if (!vb) {
0875         err = -ENOMEM;
0876         goto out;
0877     }
0878 
0879     INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func);
0880     INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func);
0881     spin_lock_init(&vb->stop_update_lock);
0882     mutex_init(&vb->balloon_lock);
0883     init_waitqueue_head(&vb->acked);
0884     vb->vdev = vdev;
0885 
0886     balloon_devinfo_init(&vb->vb_dev_info);
0887 
0888     err = init_vqs(vb);
0889     if (err)
0890         goto out_free_vb;
0891 
0892 #ifdef CONFIG_BALLOON_COMPACTION
0893     vb->vb_dev_info.migratepage = virtballoon_migratepage;
0894 #endif
0895     if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
0896         /*
0897          * There is always one entry reserved for cmd id, so the ring
0898          * size needs to be at least two to report free page hints.
0899          */
0900         if (virtqueue_get_vring_size(vb->free_page_vq) < 2) {
0901             err = -ENOSPC;
0902             goto out_del_vqs;
0903         }
0904         vb->balloon_wq = alloc_workqueue("balloon-wq",
0905                     WQ_FREEZABLE | WQ_CPU_INTENSIVE, 0);
0906         if (!vb->balloon_wq) {
0907             err = -ENOMEM;
0908             goto out_del_vqs;
0909         }
0910         INIT_WORK(&vb->report_free_page_work, report_free_page_func);
0911         vb->cmd_id_received_cache = VIRTIO_BALLOON_CMD_ID_STOP;
0912         vb->cmd_id_active = cpu_to_virtio32(vb->vdev,
0913                           VIRTIO_BALLOON_CMD_ID_STOP);
0914         vb->cmd_id_stop = cpu_to_virtio32(vb->vdev,
0915                           VIRTIO_BALLOON_CMD_ID_STOP);
0916         spin_lock_init(&vb->free_page_list_lock);
0917         INIT_LIST_HEAD(&vb->free_page_list);
0918         /*
0919          * We're allowed to reuse any free pages, even if they are
0920          * still to be processed by the host.
0921          */
0922         err = virtio_balloon_register_shrinker(vb);
0923         if (err)
0924             goto out_del_balloon_wq;
0925     }
0926 
0927     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM)) {
0928         vb->oom_nb.notifier_call = virtio_balloon_oom_notify;
0929         vb->oom_nb.priority = VIRTIO_BALLOON_OOM_NOTIFY_PRIORITY;
0930         err = register_oom_notifier(&vb->oom_nb);
0931         if (err < 0)
0932             goto out_unregister_shrinker;
0933     }
0934 
0935     if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON)) {
0936         /* Start with poison val of 0 representing general init */
0937         __u32 poison_val = 0;
0938 
0939         /*
0940          * Let the hypervisor know that we are expecting a
0941          * specific value to be written back in balloon pages.
0942          *
0943          * If the PAGE_POISON value was larger than a byte we would
0944          * need to byte swap poison_val here to guarantee it is
0945          * little-endian. However for now it is a single byte so we
0946          * can pass it as-is.
0947          */
0948         if (!want_init_on_free())
0949             memset(&poison_val, PAGE_POISON, sizeof(poison_val));
0950 
0951         virtio_cwrite_le(vb->vdev, struct virtio_balloon_config,
0952                  poison_val, &poison_val);
0953     }
0954 
0955     vb->pr_dev_info.report = virtballoon_free_page_report;
0956     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING)) {
0957         unsigned int capacity;
0958 
0959         capacity = virtqueue_get_vring_size(vb->reporting_vq);
0960         if (capacity < PAGE_REPORTING_CAPACITY) {
0961             err = -ENOSPC;
0962             goto out_unregister_oom;
0963         }
0964 
0965         /*
0966          * The default page reporting order is @pageblock_order, which
0967          * corresponds to 512MB in size on ARM64 when 64KB base page
0968          * size is used. The page reporting won't be triggered if the
0969          * freeing page can't come up with a free area like that huge.
0970          * So we specify the page reporting order to 5, corresponding
0971          * to 2MB. It helps to avoid THP splitting if 4KB base page
0972          * size is used by host.
0973          *
0974          * Ideally, the page reporting order is selected based on the
0975          * host's base page size. However, it needs more work to report
0976          * that value. The hard-coded order would be fine currently.
0977          */
0978 #if defined(CONFIG_ARM64) && defined(CONFIG_ARM64_64K_PAGES)
0979         vb->pr_dev_info.order = 5;
0980 #endif
0981 
0982         err = page_reporting_register(&vb->pr_dev_info);
0983         if (err)
0984             goto out_unregister_oom;
0985     }
0986 
0987     virtio_device_ready(vdev);
0988 
0989     if (towards_target(vb))
0990         virtballoon_changed(vdev);
0991     return 0;
0992 
0993 out_unregister_oom:
0994     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
0995         unregister_oom_notifier(&vb->oom_nb);
0996 out_unregister_shrinker:
0997     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
0998         virtio_balloon_unregister_shrinker(vb);
0999 out_del_balloon_wq:
1000     if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1001         destroy_workqueue(vb->balloon_wq);
1002 out_del_vqs:
1003     vdev->config->del_vqs(vdev);
1004 out_free_vb:
1005     kfree(vb);
1006 out:
1007     return err;
1008 }
1009 
1010 static void remove_common(struct virtio_balloon *vb)
1011 {
1012     /* There might be pages left in the balloon: free them. */
1013     while (vb->num_pages)
1014         leak_balloon(vb, vb->num_pages);
1015     update_balloon_size(vb);
1016 
1017     /* There might be free pages that are being reported: release them. */
1018     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1019         return_free_pages_to_mm(vb, ULONG_MAX);
1020 
1021     /* Now we reset the device so we can clean up the queues. */
1022     virtio_reset_device(vb->vdev);
1023 
1024     vb->vdev->config->del_vqs(vb->vdev);
1025 }
1026 
1027 static void virtballoon_remove(struct virtio_device *vdev)
1028 {
1029     struct virtio_balloon *vb = vdev->priv;
1030 
1031     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING))
1032         page_reporting_unregister(&vb->pr_dev_info);
1033     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
1034         unregister_oom_notifier(&vb->oom_nb);
1035     if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1036         virtio_balloon_unregister_shrinker(vb);
1037     spin_lock_irq(&vb->stop_update_lock);
1038     vb->stop_update = true;
1039     spin_unlock_irq(&vb->stop_update_lock);
1040     cancel_work_sync(&vb->update_balloon_size_work);
1041     cancel_work_sync(&vb->update_balloon_stats_work);
1042 
1043     if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
1044         cancel_work_sync(&vb->report_free_page_work);
1045         destroy_workqueue(vb->balloon_wq);
1046     }
1047 
1048     remove_common(vb);
1049     kfree(vb);
1050 }
1051 
1052 #ifdef CONFIG_PM_SLEEP
1053 static int virtballoon_freeze(struct virtio_device *vdev)
1054 {
1055     struct virtio_balloon *vb = vdev->priv;
1056 
1057     /*
1058      * The workqueue is already frozen by the PM core before this
1059      * function is called.
1060      */
1061     remove_common(vb);
1062     return 0;
1063 }
1064 
1065 static int virtballoon_restore(struct virtio_device *vdev)
1066 {
1067     struct virtio_balloon *vb = vdev->priv;
1068     int ret;
1069 
1070     ret = init_vqs(vdev->priv);
1071     if (ret)
1072         return ret;
1073 
1074     virtio_device_ready(vdev);
1075 
1076     if (towards_target(vb))
1077         virtballoon_changed(vdev);
1078     update_balloon_size(vb);
1079     return 0;
1080 }
1081 #endif
1082 
1083 static int virtballoon_validate(struct virtio_device *vdev)
1084 {
1085     /*
1086      * Inform the hypervisor that our pages are poisoned or
1087      * initialized. If we cannot do that then we should disable
1088      * page reporting as it could potentially change the contents
1089      * of our free pages.
1090      */
1091     if (!want_init_on_free() && !page_poisoning_enabled_static())
1092         __virtio_clear_bit(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
1093     else if (!virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON))
1094         __virtio_clear_bit(vdev, VIRTIO_BALLOON_F_REPORTING);
1095 
1096     __virtio_clear_bit(vdev, VIRTIO_F_ACCESS_PLATFORM);
1097     return 0;
1098 }
1099 
1100 static unsigned int features[] = {
1101     VIRTIO_BALLOON_F_MUST_TELL_HOST,
1102     VIRTIO_BALLOON_F_STATS_VQ,
1103     VIRTIO_BALLOON_F_DEFLATE_ON_OOM,
1104     VIRTIO_BALLOON_F_FREE_PAGE_HINT,
1105     VIRTIO_BALLOON_F_PAGE_POISON,
1106     VIRTIO_BALLOON_F_REPORTING,
1107 };
1108 
1109 static struct virtio_driver virtio_balloon_driver = {
1110     .feature_table = features,
1111     .feature_table_size = ARRAY_SIZE(features),
1112     .driver.name =  KBUILD_MODNAME,
1113     .driver.owner = THIS_MODULE,
1114     .id_table = id_table,
1115     .validate = virtballoon_validate,
1116     .probe =    virtballoon_probe,
1117     .remove =   virtballoon_remove,
1118     .config_changed = virtballoon_changed,
1119 #ifdef CONFIG_PM_SLEEP
1120     .freeze =   virtballoon_freeze,
1121     .restore =  virtballoon_restore,
1122 #endif
1123 };
1124 
1125 module_virtio_driver(virtio_balloon_driver);
1126 MODULE_DEVICE_TABLE(virtio, id_table);
1127 MODULE_DESCRIPTION("Virtio balloon driver");
1128 MODULE_LICENSE("GPL");