1 /******************************************************************************
2  *
3  * Back-end of the driver for virtual block devices. This portion of the
4  * driver exports a 'unified' block-device interface that can be accessed
5  * by any operating system that implements a compatible front end. A
6  * reference front-end implementation can be found in:
7  *  drivers/block/xen-blkfront.c
8  *
9  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
10  * Copyright (c) 2005, Christopher Clark
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License version 2
14  * as published by the Free Software Foundation; or, when distributed
15  * separately from the Linux kernel or incorporated into other
16  * software packages, subject to the following license:
17  *
18  * Permission is hereby granted, free of charge, to any person obtaining a copy
19  * of this source file (the "Software"), to deal in the Software without
20  * restriction, including without limitation the rights to use, copy, modify,
21  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
22  * and to permit persons to whom the Software is furnished to do so, subject to
23  * the following conditions:
24  *
25  * The above copyright notice and this permission notice shall be included in
26  * all copies or substantial portions of the Software.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
33  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
34  * IN THE SOFTWARE.
35  */
36 
37 #include <linux/spinlock.h>
38 #include <linux/kthread.h>
39 #include <linux/list.h>
40 #include <linux/delay.h>
41 #include <linux/freezer.h>
42 #include <linux/bitmap.h>
43 
44 #include <xen/events.h>
45 #include <xen/page.h>
46 #include <xen/xen.h>
47 #include <asm/xen/hypervisor.h>
48 #include <asm/xen/hypercall.h>
49 #include <xen/balloon.h>
50 #include <xen/grant_table.h>
51 #include "common.h"
52 
53 /*
54  * Maximum number of unused free pages to keep in the internal buffer.
55  * Setting this to a value too low will reduce memory used in each backend,
56  * but can have a performance penalty.
57  *
58  * A sane value is xen_blkif_reqs * BLKIF_MAX_SEGMENTS_PER_REQUEST, but can
59  * be set to a lower value that might degrade performance on some intensive
60  * IO workloads.
61  */
62 
63 static int xen_blkif_max_buffer_pages = 1024;
64 module_param_named(max_buffer_pages, xen_blkif_max_buffer_pages, int, 0644);
65 MODULE_PARM_DESC(max_buffer_pages,
66 "Maximum number of free pages to keep in each block backend buffer");
67 
68 /*
69  * Maximum number of grants to map persistently in blkback. For maximum
70  * performance this should be the total numbers of grants that can be used
71  * to fill the ring, but since this might become too high, specially with
72  * the use of indirect descriptors, we set it to a value that provides good
73  * performance without using too much memory.
74  *
75  * When the list of persistent grants is full we clean it up using a LRU
76  * algorithm.
77  */
78 
79 static int xen_blkif_max_pgrants = 1056;
80 module_param_named(max_persistent_grants, xen_blkif_max_pgrants, int, 0644);
81 MODULE_PARM_DESC(max_persistent_grants,
82                  "Maximum number of grants to map persistently");
83 
84 /*
85  * The LRU mechanism to clean the lists of persistent grants needs to
86  * be executed periodically. The time interval between consecutive executions
87  * of the purge mechanism is set in ms.
88  */
89 #define LRU_INTERVAL 100
90 
91 /*
92  * When the persistent grants list is full we will remove unused grants
93  * from the list. The percent number of grants to be removed at each LRU
94  * execution.
95  */
96 #define LRU_PERCENT_CLEAN 5
97 
98 /* Run-time switchable: /sys/module/blkback/parameters/ */
99 static unsigned int log_stats;
100 module_param(log_stats, int, 0644);
101 
102 #define BLKBACK_INVALID_HANDLE (~0)
103 
104 /* Number of free pages to remove on each call to gnttab_free_pages */
105 #define NUM_BATCH_FREE_PAGES 10
106 
107 static inline int get_free_page(struct xen_blkif *blkif, struct page **page)
108 {
109 	unsigned long flags;
110 
111 	spin_lock_irqsave(&blkif->free_pages_lock, flags);
112 	if (list_empty(&blkif->free_pages)) {
113 		BUG_ON(blkif->free_pages_num != 0);
114 		spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
115 		return gnttab_alloc_pages(1, page);
116 	}
117 	BUG_ON(blkif->free_pages_num == 0);
118 	page[0] = list_first_entry(&blkif->free_pages, struct page, lru);
119 	list_del(&page[0]->lru);
120 	blkif->free_pages_num--;
121 	spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
122 
123 	return 0;
124 }
125 
126 static inline void put_free_pages(struct xen_blkif *blkif, struct page **page,
127                                   int num)
128 {
129 	unsigned long flags;
130 	int i;
131 
132 	spin_lock_irqsave(&blkif->free_pages_lock, flags);
133 	for (i = 0; i < num; i++)
134 		list_add(&page[i]->lru, &blkif->free_pages);
135 	blkif->free_pages_num += num;
136 	spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
137 }
138 
139 static inline void shrink_free_pagepool(struct xen_blkif *blkif, int num)
140 {
141 	/* Remove requested pages in batches of NUM_BATCH_FREE_PAGES */
142 	struct page *page[NUM_BATCH_FREE_PAGES];
143 	unsigned int num_pages = 0;
144 	unsigned long flags;
145 
146 	spin_lock_irqsave(&blkif->free_pages_lock, flags);
147 	while (blkif->free_pages_num > num) {
148 		BUG_ON(list_empty(&blkif->free_pages));
149 		page[num_pages] = list_first_entry(&blkif->free_pages,
150 		                                   struct page, lru);
151 		list_del(&page[num_pages]->lru);
152 		blkif->free_pages_num--;
153 		if (++num_pages == NUM_BATCH_FREE_PAGES) {
154 			spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
155 			gnttab_free_pages(num_pages, page);
156 			spin_lock_irqsave(&blkif->free_pages_lock, flags);
157 			num_pages = 0;
158 		}
159 	}
160 	spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
161 	if (num_pages != 0)
162 		gnttab_free_pages(num_pages, page);
163 }
164 
165 #define vaddr(page) ((unsigned long)pfn_to_kaddr(page_to_pfn(page)))
166 
167 static int do_block_io_op(struct xen_blkif *blkif);
168 static int dispatch_rw_block_io(struct xen_blkif *blkif,
169 				struct blkif_request *req,
170 				struct pending_req *pending_req);
171 static void make_response(struct xen_blkif *blkif, u64 id,
172 			  unsigned short op, int st);
173 
174 #define foreach_grant_safe(pos, n, rbtree, node) \
175 	for ((pos) = container_of(rb_first((rbtree)), typeof(*(pos)), node), \
176 	     (n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL; \
177 	     &(pos)->node != NULL; \
178 	     (pos) = container_of(n, typeof(*(pos)), node), \
179 	     (n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL)
180 
181 
182 /*
183  * We don't need locking around the persistent grant helpers
184  * because blkback uses a single-thread for each backed, so we
185  * can be sure that this functions will never be called recursively.
186  *
187  * The only exception to that is put_persistent_grant, that can be called
188  * from interrupt context (by xen_blkbk_unmap), so we have to use atomic
189  * bit operations to modify the flags of a persistent grant and to count
190  * the number of used grants.
191  */
192 static int add_persistent_gnt(struct xen_blkif *blkif,
193 			       struct persistent_gnt *persistent_gnt)
194 {
195 	struct rb_node **new = NULL, *parent = NULL;
196 	struct persistent_gnt *this;
197 
198 	if (blkif->persistent_gnt_c >= xen_blkif_max_pgrants) {
199 		if (!blkif->vbd.overflow_max_grants)
200 			blkif->vbd.overflow_max_grants = 1;
201 		return -EBUSY;
202 	}
203 	/* Figure out where to put new node */
204 	new = &blkif->persistent_gnts.rb_node;
205 	while (*new) {
206 		this = container_of(*new, struct persistent_gnt, node);
207 
208 		parent = *new;
209 		if (persistent_gnt->gnt < this->gnt)
210 			new = &((*new)->rb_left);
211 		else if (persistent_gnt->gnt > this->gnt)
212 			new = &((*new)->rb_right);
213 		else {
214 			pr_alert_ratelimited(DRV_PFX " trying to add a gref that's already in the tree\n");
215 			return -EINVAL;
216 		}
217 	}
218 
219 	bitmap_zero(persistent_gnt->flags, PERSISTENT_GNT_FLAGS_SIZE);
220 	set_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
221 	/* Add new node and rebalance tree. */
222 	rb_link_node(&(persistent_gnt->node), parent, new);
223 	rb_insert_color(&(persistent_gnt->node), &blkif->persistent_gnts);
224 	blkif->persistent_gnt_c++;
225 	atomic_inc(&blkif->persistent_gnt_in_use);
226 	return 0;
227 }
228 
229 static struct persistent_gnt *get_persistent_gnt(struct xen_blkif *blkif,
230 						 grant_ref_t gref)
231 {
232 	struct persistent_gnt *data;
233 	struct rb_node *node = NULL;
234 
235 	node = blkif->persistent_gnts.rb_node;
236 	while (node) {
237 		data = container_of(node, struct persistent_gnt, node);
238 
239 		if (gref < data->gnt)
240 			node = node->rb_left;
241 		else if (gref > data->gnt)
242 			node = node->rb_right;
243 		else {
244 			if(test_bit(PERSISTENT_GNT_ACTIVE, data->flags)) {
245 				pr_alert_ratelimited(DRV_PFX " requesting a grant already in use\n");
246 				return NULL;
247 			}
248 			set_bit(PERSISTENT_GNT_ACTIVE, data->flags);
249 			atomic_inc(&blkif->persistent_gnt_in_use);
250 			return data;
251 		}
252 	}
253 	return NULL;
254 }
255 
256 static void put_persistent_gnt(struct xen_blkif *blkif,
257                                struct persistent_gnt *persistent_gnt)
258 {
259 	if(!test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
260 	          pr_alert_ratelimited(DRV_PFX " freeing a grant already unused");
261 	set_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
262 	clear_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
263 	atomic_dec(&blkif->persistent_gnt_in_use);
264 }
265 
266 static void free_persistent_gnts_unmap_callback(int result,
267 						struct gntab_unmap_queue_data *data)
268 {
269 	struct completion *c = data->data;
270 
271 	/* BUG_ON used to reproduce existing behaviour,
272 	   but is this the best way to deal with this? */
273 	BUG_ON(result);
274 	complete(c);
275 }
276 
277 static void free_persistent_gnts(struct xen_blkif *blkif, struct rb_root *root,
278                                  unsigned int num)
279 {
280 	struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
281 	struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
282 	struct persistent_gnt *persistent_gnt;
283 	struct rb_node *n;
284 	int segs_to_unmap = 0;
285 	struct gntab_unmap_queue_data unmap_data;
286 	struct completion unmap_completion;
287 
288 	init_completion(&unmap_completion);
289 
290 	unmap_data.data = &unmap_completion;
291 	unmap_data.done = &free_persistent_gnts_unmap_callback;
292 	unmap_data.pages = pages;
293 	unmap_data.unmap_ops = unmap;
294 	unmap_data.kunmap_ops = NULL;
295 
296 	foreach_grant_safe(persistent_gnt, n, root, node) {
297 		BUG_ON(persistent_gnt->handle ==
298 			BLKBACK_INVALID_HANDLE);
299 		gnttab_set_unmap_op(&unmap[segs_to_unmap],
300 			(unsigned long) pfn_to_kaddr(page_to_pfn(
301 				persistent_gnt->page)),
302 			GNTMAP_host_map,
303 			persistent_gnt->handle);
304 
305 		pages[segs_to_unmap] = persistent_gnt->page;
306 
307 		if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST ||
308 			!rb_next(&persistent_gnt->node)) {
309 
310 			unmap_data.count = segs_to_unmap;
311 			gnttab_unmap_refs_async(&unmap_data);
312 			wait_for_completion(&unmap_completion);
313 
314 			put_free_pages(blkif, pages, segs_to_unmap);
315 			segs_to_unmap = 0;
316 		}
317 
318 		rb_erase(&persistent_gnt->node, root);
319 		kfree(persistent_gnt);
320 		num--;
321 	}
322 	BUG_ON(num != 0);
323 }
324 
325 void xen_blkbk_unmap_purged_grants(struct work_struct *work)
326 {
327 	struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
328 	struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
329 	struct persistent_gnt *persistent_gnt;
330 	int ret, segs_to_unmap = 0;
331 	struct xen_blkif *blkif = container_of(work, typeof(*blkif), persistent_purge_work);
332 
333 	while(!list_empty(&blkif->persistent_purge_list)) {
334 		persistent_gnt = list_first_entry(&blkif->persistent_purge_list,
335 		                                  struct persistent_gnt,
336 		                                  remove_node);
337 		list_del(&persistent_gnt->remove_node);
338 
339 		gnttab_set_unmap_op(&unmap[segs_to_unmap],
340 			vaddr(persistent_gnt->page),
341 			GNTMAP_host_map,
342 			persistent_gnt->handle);
343 
344 		pages[segs_to_unmap] = persistent_gnt->page;
345 
346 		if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST) {
347 			ret = gnttab_unmap_refs(unmap, NULL, pages,
348 				segs_to_unmap);
349 			BUG_ON(ret);
350 			put_free_pages(blkif, pages, segs_to_unmap);
351 			segs_to_unmap = 0;
352 		}
353 		kfree(persistent_gnt);
354 	}
355 	if (segs_to_unmap > 0) {
356 		ret = gnttab_unmap_refs(unmap, NULL, pages, segs_to_unmap);
357 		BUG_ON(ret);
358 		put_free_pages(blkif, pages, segs_to_unmap);
359 	}
360 }
361 
362 static void purge_persistent_gnt(struct xen_blkif *blkif)
363 {
364 	struct persistent_gnt *persistent_gnt;
365 	struct rb_node *n;
366 	unsigned int num_clean, total;
367 	bool scan_used = false, clean_used = false;
368 	struct rb_root *root;
369 
370 	if (blkif->persistent_gnt_c < xen_blkif_max_pgrants ||
371 	    (blkif->persistent_gnt_c == xen_blkif_max_pgrants &&
372 	    !blkif->vbd.overflow_max_grants)) {
373 		return;
374 	}
375 
376 	if (work_pending(&blkif->persistent_purge_work)) {
377 		pr_alert_ratelimited(DRV_PFX "Scheduled work from previous purge is still pending, cannot purge list\n");
378 		return;
379 	}
380 
381 	num_clean = (xen_blkif_max_pgrants / 100) * LRU_PERCENT_CLEAN;
382 	num_clean = blkif->persistent_gnt_c - xen_blkif_max_pgrants + num_clean;
383 	num_clean = min(blkif->persistent_gnt_c, num_clean);
384 	if ((num_clean == 0) ||
385 	    (num_clean > (blkif->persistent_gnt_c - atomic_read(&blkif->persistent_gnt_in_use))))
386 		return;
387 
388 	/*
389 	 * At this point, we can assure that there will be no calls
390          * to get_persistent_grant (because we are executing this code from
391          * xen_blkif_schedule), there can only be calls to put_persistent_gnt,
392          * which means that the number of currently used grants will go down,
393          * but never up, so we will always be able to remove the requested
394          * number of grants.
395 	 */
396 
397 	total = num_clean;
398 
399 	pr_debug(DRV_PFX "Going to purge %u persistent grants\n", num_clean);
400 
401 	BUG_ON(!list_empty(&blkif->persistent_purge_list));
402 	root = &blkif->persistent_gnts;
403 purge_list:
404 	foreach_grant_safe(persistent_gnt, n, root, node) {
405 		BUG_ON(persistent_gnt->handle ==
406 			BLKBACK_INVALID_HANDLE);
407 
408 		if (clean_used) {
409 			clear_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
410 			continue;
411 		}
412 
413 		if (test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
414 			continue;
415 		if (!scan_used &&
416 		    (test_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags)))
417 			continue;
418 
419 		rb_erase(&persistent_gnt->node, root);
420 		list_add(&persistent_gnt->remove_node,
421 		         &blkif->persistent_purge_list);
422 		if (--num_clean == 0)
423 			goto finished;
424 	}
425 	/*
426 	 * If we get here it means we also need to start cleaning
427 	 * grants that were used since last purge in order to cope
428 	 * with the requested num
429 	 */
430 	if (!scan_used && !clean_used) {
431 		pr_debug(DRV_PFX "Still missing %u purged frames\n", num_clean);
432 		scan_used = true;
433 		goto purge_list;
434 	}
435 finished:
436 	if (!clean_used) {
437 		pr_debug(DRV_PFX "Finished scanning for grants to clean, removing used flag\n");
438 		clean_used = true;
439 		goto purge_list;
440 	}
441 
442 	blkif->persistent_gnt_c -= (total - num_clean);
443 	blkif->vbd.overflow_max_grants = 0;
444 
445 	/* We can defer this work */
446 	schedule_work(&blkif->persistent_purge_work);
447 	pr_debug(DRV_PFX "Purged %u/%u\n", (total - num_clean), total);
448 	return;
449 }
450 
451 /*
452  * Retrieve from the 'pending_reqs' a free pending_req structure to be used.
453  */
454 static struct pending_req *alloc_req(struct xen_blkif *blkif)
455 {
456 	struct pending_req *req = NULL;
457 	unsigned long flags;
458 
459 	spin_lock_irqsave(&blkif->pending_free_lock, flags);
460 	if (!list_empty(&blkif->pending_free)) {
461 		req = list_entry(blkif->pending_free.next, struct pending_req,
462 				 free_list);
463 		list_del(&req->free_list);
464 	}
465 	spin_unlock_irqrestore(&blkif->pending_free_lock, flags);
466 	return req;
467 }
468 
469 /*
470  * Return the 'pending_req' structure back to the freepool. We also
471  * wake up the thread if it was waiting for a free page.
472  */
473 static void free_req(struct xen_blkif *blkif, struct pending_req *req)
474 {
475 	unsigned long flags;
476 	int was_empty;
477 
478 	spin_lock_irqsave(&blkif->pending_free_lock, flags);
479 	was_empty = list_empty(&blkif->pending_free);
480 	list_add(&req->free_list, &blkif->pending_free);
481 	spin_unlock_irqrestore(&blkif->pending_free_lock, flags);
482 	if (was_empty)
483 		wake_up(&blkif->pending_free_wq);
484 }
485 
486 /*
487  * Routines for managing virtual block devices (vbds).
488  */
489 static int xen_vbd_translate(struct phys_req *req, struct xen_blkif *blkif,
490 			     int operation)
491 {
492 	struct xen_vbd *vbd = &blkif->vbd;
493 	int rc = -EACCES;
494 
495 	if ((operation != READ) && vbd->readonly)
496 		goto out;
497 
498 	if (likely(req->nr_sects)) {
499 		blkif_sector_t end = req->sector_number + req->nr_sects;
500 
501 		if (unlikely(end < req->sector_number))
502 			goto out;
503 		if (unlikely(end > vbd_sz(vbd)))
504 			goto out;
505 	}
506 
507 	req->dev  = vbd->pdevice;
508 	req->bdev = vbd->bdev;
509 	rc = 0;
510 
511  out:
512 	return rc;
513 }
514 
515 static void xen_vbd_resize(struct xen_blkif *blkif)
516 {
517 	struct xen_vbd *vbd = &blkif->vbd;
518 	struct xenbus_transaction xbt;
519 	int err;
520 	struct xenbus_device *dev = xen_blkbk_xenbus(blkif->be);
521 	unsigned long long new_size = vbd_sz(vbd);
522 
523 	pr_info(DRV_PFX "VBD Resize: Domid: %d, Device: (%d, %d)\n",
524 		blkif->domid, MAJOR(vbd->pdevice), MINOR(vbd->pdevice));
525 	pr_info(DRV_PFX "VBD Resize: new size %llu\n", new_size);
526 	vbd->size = new_size;
527 again:
528 	err = xenbus_transaction_start(&xbt);
529 	if (err) {
530 		pr_warn(DRV_PFX "Error starting transaction");
531 		return;
532 	}
533 	err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
534 			    (unsigned long long)vbd_sz(vbd));
535 	if (err) {
536 		pr_warn(DRV_PFX "Error writing new size");
537 		goto abort;
538 	}
539 	/*
540 	 * Write the current state; we will use this to synchronize
541 	 * the front-end. If the current state is "connected" the
542 	 * front-end will get the new size information online.
543 	 */
544 	err = xenbus_printf(xbt, dev->nodename, "state", "%d", dev->state);
545 	if (err) {
546 		pr_warn(DRV_PFX "Error writing the state");
547 		goto abort;
548 	}
549 
550 	err = xenbus_transaction_end(xbt, 0);
551 	if (err == -EAGAIN)
552 		goto again;
553 	if (err)
554 		pr_warn(DRV_PFX "Error ending transaction");
555 	return;
556 abort:
557 	xenbus_transaction_end(xbt, 1);
558 }
559 
560 /*
561  * Notification from the guest OS.
562  */
563 static void blkif_notify_work(struct xen_blkif *blkif)
564 {
565 	blkif->waiting_reqs = 1;
566 	wake_up(&blkif->wq);
567 }
568 
569 irqreturn_t xen_blkif_be_int(int irq, void *dev_id)
570 {
571 	blkif_notify_work(dev_id);
572 	return IRQ_HANDLED;
573 }
574 
575 /*
576  * SCHEDULER FUNCTIONS
577  */
578 
579 static void print_stats(struct xen_blkif *blkif)
580 {
581 	pr_info("xen-blkback (%s): oo %3llu  |  rd %4llu  |  wr %4llu  |  f %4llu"
582 		 "  |  ds %4llu | pg: %4u/%4d\n",
583 		 current->comm, blkif->st_oo_req,
584 		 blkif->st_rd_req, blkif->st_wr_req,
585 		 blkif->st_f_req, blkif->st_ds_req,
586 		 blkif->persistent_gnt_c,
587 		 xen_blkif_max_pgrants);
588 	blkif->st_print = jiffies + msecs_to_jiffies(10 * 1000);
589 	blkif->st_rd_req = 0;
590 	blkif->st_wr_req = 0;
591 	blkif->st_oo_req = 0;
592 	blkif->st_ds_req = 0;
593 }
594 
595 int xen_blkif_schedule(void *arg)
596 {
597 	struct xen_blkif *blkif = arg;
598 	struct xen_vbd *vbd = &blkif->vbd;
599 	unsigned long timeout;
600 	int ret;
601 
602 	xen_blkif_get(blkif);
603 
604 	while (!kthread_should_stop()) {
605 		if (try_to_freeze())
606 			continue;
607 		if (unlikely(vbd->size != vbd_sz(vbd)))
608 			xen_vbd_resize(blkif);
609 
610 		timeout = msecs_to_jiffies(LRU_INTERVAL);
611 
612 		timeout = wait_event_interruptible_timeout(
613 			blkif->wq,
614 			blkif->waiting_reqs || kthread_should_stop(),
615 			timeout);
616 		if (timeout == 0)
617 			goto purge_gnt_list;
618 		timeout = wait_event_interruptible_timeout(
619 			blkif->pending_free_wq,
620 			!list_empty(&blkif->pending_free) ||
621 			kthread_should_stop(),
622 			timeout);
623 		if (timeout == 0)
624 			goto purge_gnt_list;
625 
626 		blkif->waiting_reqs = 0;
627 		smp_mb(); /* clear flag *before* checking for work */
628 
629 		ret = do_block_io_op(blkif);
630 		if (ret > 0)
631 			blkif->waiting_reqs = 1;
632 		if (ret == -EACCES)
633 			wait_event_interruptible(blkif->shutdown_wq,
634 						 kthread_should_stop());
635 
636 purge_gnt_list:
637 		if (blkif->vbd.feature_gnt_persistent &&
638 		    time_after(jiffies, blkif->next_lru)) {
639 			purge_persistent_gnt(blkif);
640 			blkif->next_lru = jiffies + msecs_to_jiffies(LRU_INTERVAL);
641 		}
642 
643 		/* Shrink if we have more than xen_blkif_max_buffer_pages */
644 		shrink_free_pagepool(blkif, xen_blkif_max_buffer_pages);
645 
646 		if (log_stats && time_after(jiffies, blkif->st_print))
647 			print_stats(blkif);
648 	}
649 
650 	/* Drain pending purge work */
651 	flush_work(&blkif->persistent_purge_work);
652 
653 	if (log_stats)
654 		print_stats(blkif);
655 
656 	blkif->xenblkd = NULL;
657 	xen_blkif_put(blkif);
658 
659 	return 0;
660 }
661 
662 /*
663  * Remove persistent grants and empty the pool of free pages
664  */
665 void xen_blkbk_free_caches(struct xen_blkif *blkif)
666 {
667 	/* Free all persistent grant pages */
668 	if (!RB_EMPTY_ROOT(&blkif->persistent_gnts))
669 		free_persistent_gnts(blkif, &blkif->persistent_gnts,
670 			blkif->persistent_gnt_c);
671 
672 	BUG_ON(!RB_EMPTY_ROOT(&blkif->persistent_gnts));
673 	blkif->persistent_gnt_c = 0;
674 
675 	/* Since we are shutting down remove all pages from the buffer */
676 	shrink_free_pagepool(blkif, 0 /* All */);
677 }
678 
679 static unsigned int xen_blkbk_unmap_prepare(
680 	struct xen_blkif *blkif,
681 	struct grant_page **pages,
682 	unsigned int num,
683 	struct gnttab_unmap_grant_ref *unmap_ops,
684 	struct page **unmap_pages)
685 {
686 	unsigned int i, invcount = 0;
687 
688 	for (i = 0; i < num; i++) {
689 		if (pages[i]->persistent_gnt != NULL) {
690 			put_persistent_gnt(blkif, pages[i]->persistent_gnt);
691 			continue;
692 		}
693 		if (pages[i]->handle == BLKBACK_INVALID_HANDLE)
694 			continue;
695 		unmap_pages[invcount] = pages[i]->page;
696 		gnttab_set_unmap_op(&unmap_ops[invcount], vaddr(pages[i]->page),
697 				    GNTMAP_host_map, pages[i]->handle);
698 		pages[i]->handle = BLKBACK_INVALID_HANDLE;
699 		invcount++;
700        }
701 
702        return invcount;
703 }
704 
705 static void xen_blkbk_unmap_and_respond_callback(int result, struct gntab_unmap_queue_data *data)
706 {
707 	struct pending_req* pending_req = (struct pending_req*) (data->data);
708 	struct xen_blkif *blkif = pending_req->blkif;
709 
710 	/* BUG_ON used to reproduce existing behaviour,
711 	   but is this the best way to deal with this? */
712 	BUG_ON(result);
713 
714 	put_free_pages(blkif, data->pages, data->count);
715 	make_response(blkif, pending_req->id,
716 		      pending_req->operation, pending_req->status);
717 	free_req(blkif, pending_req);
718 	/*
719 	 * Make sure the request is freed before releasing blkif,
720 	 * or there could be a race between free_req and the
721 	 * cleanup done in xen_blkif_free during shutdown.
722 	 *
723 	 * NB: The fact that we might try to wake up pending_free_wq
724 	 * before drain_complete (in case there's a drain going on)
725 	 * it's not a problem with our current implementation
726 	 * because we can assure there's no thread waiting on
727 	 * pending_free_wq if there's a drain going on, but it has
728 	 * to be taken into account if the current model is changed.
729 	 */
730 	if (atomic_dec_and_test(&blkif->inflight) && atomic_read(&blkif->drain)) {
731 		complete(&blkif->drain_complete);
732 	}
733 	xen_blkif_put(blkif);
734 }
735 
736 static void xen_blkbk_unmap_and_respond(struct pending_req *req)
737 {
738 	struct gntab_unmap_queue_data* work = &req->gnttab_unmap_data;
739 	struct xen_blkif *blkif = req->blkif;
740 	struct grant_page **pages = req->segments;
741 	unsigned int invcount;
742 
743 	invcount = xen_blkbk_unmap_prepare(blkif, pages, req->nr_pages,
744 					   req->unmap, req->unmap_pages);
745 
746 	work->data = req;
747 	work->done = xen_blkbk_unmap_and_respond_callback;
748 	work->unmap_ops = req->unmap;
749 	work->kunmap_ops = NULL;
750 	work->pages = req->unmap_pages;
751 	work->count = invcount;
752 
753 	gnttab_unmap_refs_async(&req->gnttab_unmap_data);
754 }
755 
756 
757 /*
758  * Unmap the grant references.
759  *
760  * This could accumulate ops up to the batch size to reduce the number
761  * of hypercalls, but since this is only used in error paths there's
762  * no real need.
763  */
764 static void xen_blkbk_unmap(struct xen_blkif *blkif,
765                             struct grant_page *pages[],
766                             int num)
767 {
768 	struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
769 	struct page *unmap_pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
770 	unsigned int invcount = 0;
771 	int ret;
772 
773 	while (num) {
774 		unsigned int batch = min(num, BLKIF_MAX_SEGMENTS_PER_REQUEST);
775 
776 		invcount = xen_blkbk_unmap_prepare(blkif, pages, batch,
777 						   unmap, unmap_pages);
778 		if (invcount) {
779 			ret = gnttab_unmap_refs(unmap, NULL, unmap_pages, invcount);
780 			BUG_ON(ret);
781 			put_free_pages(blkif, unmap_pages, invcount);
782 		}
783 		pages += batch;
784 		num -= batch;
785 	}
786 }
787 
788 static int xen_blkbk_map(struct xen_blkif *blkif,
789 			 struct grant_page *pages[],
790 			 int num, bool ro)
791 {
792 	struct gnttab_map_grant_ref map[BLKIF_MAX_SEGMENTS_PER_REQUEST];
793 	struct page *pages_to_gnt[BLKIF_MAX_SEGMENTS_PER_REQUEST];
794 	struct persistent_gnt *persistent_gnt = NULL;
795 	phys_addr_t addr = 0;
796 	int i, seg_idx, new_map_idx;
797 	int segs_to_map = 0;
798 	int ret = 0;
799 	int last_map = 0, map_until = 0;
800 	int use_persistent_gnts;
801 
802 	use_persistent_gnts = (blkif->vbd.feature_gnt_persistent);
803 
804 	/*
805 	 * Fill out preq.nr_sects with proper amount of sectors, and setup
806 	 * assign map[..] with the PFN of the page in our domain with the
807 	 * corresponding grant reference for each page.
808 	 */
809 again:
810 	for (i = map_until; i < num; i++) {
811 		uint32_t flags;
812 
813 		if (use_persistent_gnts)
814 			persistent_gnt = get_persistent_gnt(
815 				blkif,
816 				pages[i]->gref);
817 
818 		if (persistent_gnt) {
819 			/*
820 			 * We are using persistent grants and
821 			 * the grant is already mapped
822 			 */
823 			pages[i]->page = persistent_gnt->page;
824 			pages[i]->persistent_gnt = persistent_gnt;
825 		} else {
826 			if (get_free_page(blkif, &pages[i]->page))
827 				goto out_of_memory;
828 			addr = vaddr(pages[i]->page);
829 			pages_to_gnt[segs_to_map] = pages[i]->page;
830 			pages[i]->persistent_gnt = NULL;
831 			flags = GNTMAP_host_map;
832 			if (!use_persistent_gnts && ro)
833 				flags |= GNTMAP_readonly;
834 			gnttab_set_map_op(&map[segs_to_map++], addr,
835 					  flags, pages[i]->gref,
836 					  blkif->domid);
837 		}
838 		map_until = i + 1;
839 		if (segs_to_map == BLKIF_MAX_SEGMENTS_PER_REQUEST)
840 			break;
841 	}
842 
843 	if (segs_to_map) {
844 		ret = gnttab_map_refs(map, NULL, pages_to_gnt, segs_to_map);
845 		BUG_ON(ret);
846 	}
847 
848 	/*
849 	 * Now swizzle the MFN in our domain with the MFN from the other domain
850 	 * so that when we access vaddr(pending_req,i) it has the contents of
851 	 * the page from the other domain.
852 	 */
853 	for (seg_idx = last_map, new_map_idx = 0; seg_idx < map_until; seg_idx++) {
854 		if (!pages[seg_idx]->persistent_gnt) {
855 			/* This is a newly mapped grant */
856 			BUG_ON(new_map_idx >= segs_to_map);
857 			if (unlikely(map[new_map_idx].status != 0)) {
858 				pr_debug(DRV_PFX "invalid buffer -- could not remap it\n");
859 				put_free_pages(blkif, &pages[seg_idx]->page, 1);
860 				pages[seg_idx]->handle = BLKBACK_INVALID_HANDLE;
861 				ret |= 1;
862 				goto next;
863 			}
864 			pages[seg_idx]->handle = map[new_map_idx].handle;
865 		} else {
866 			continue;
867 		}
868 		if (use_persistent_gnts &&
869 		    blkif->persistent_gnt_c < xen_blkif_max_pgrants) {
870 			/*
871 			 * We are using persistent grants, the grant is
872 			 * not mapped but we might have room for it.
873 			 */
874 			persistent_gnt = kmalloc(sizeof(struct persistent_gnt),
875 				                 GFP_KERNEL);
876 			if (!persistent_gnt) {
877 				/*
878 				 * If we don't have enough memory to
879 				 * allocate the persistent_gnt struct
880 				 * map this grant non-persistenly
881 				 */
882 				goto next;
883 			}
884 			persistent_gnt->gnt = map[new_map_idx].ref;
885 			persistent_gnt->handle = map[new_map_idx].handle;
886 			persistent_gnt->page = pages[seg_idx]->page;
887 			if (add_persistent_gnt(blkif,
888 			                       persistent_gnt)) {
889 				kfree(persistent_gnt);
890 				persistent_gnt = NULL;
891 				goto next;
892 			}
893 			pages[seg_idx]->persistent_gnt = persistent_gnt;
894 			pr_debug(DRV_PFX " grant %u added to the tree of persistent grants, using %u/%u\n",
895 				 persistent_gnt->gnt, blkif->persistent_gnt_c,
896 				 xen_blkif_max_pgrants);
897 			goto next;
898 		}
899 		if (use_persistent_gnts && !blkif->vbd.overflow_max_grants) {
900 			blkif->vbd.overflow_max_grants = 1;
901 			pr_debug(DRV_PFX " domain %u, device %#x is using maximum number of persistent grants\n",
902 			         blkif->domid, blkif->vbd.handle);
903 		}
904 		/*
905 		 * We could not map this grant persistently, so use it as
906 		 * a non-persistent grant.
907 		 */
908 next:
909 		new_map_idx++;
910 	}
911 	segs_to_map = 0;
912 	last_map = map_until;
913 	if (map_until != num)
914 		goto again;
915 
916 	return ret;
917 
918 out_of_memory:
919 	pr_alert(DRV_PFX "%s: out of memory\n", __func__);
920 	put_free_pages(blkif, pages_to_gnt, segs_to_map);
921 	return -ENOMEM;
922 }
923 
924 static int xen_blkbk_map_seg(struct pending_req *pending_req)
925 {
926 	int rc;
927 
928 	rc = xen_blkbk_map(pending_req->blkif, pending_req->segments,
929 			   pending_req->nr_pages,
930 	                   (pending_req->operation != BLKIF_OP_READ));
931 
932 	return rc;
933 }
934 
935 static int xen_blkbk_parse_indirect(struct blkif_request *req,
936 				    struct pending_req *pending_req,
937 				    struct seg_buf seg[],
938 				    struct phys_req *preq)
939 {
940 	struct grant_page **pages = pending_req->indirect_pages;
941 	struct xen_blkif *blkif = pending_req->blkif;
942 	int indirect_grefs, rc, n, nseg, i;
943 	struct blkif_request_segment *segments = NULL;
944 
945 	nseg = pending_req->nr_pages;
946 	indirect_grefs = INDIRECT_PAGES(nseg);
947 	BUG_ON(indirect_grefs > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
948 
949 	for (i = 0; i < indirect_grefs; i++)
950 		pages[i]->gref = req->u.indirect.indirect_grefs[i];
951 
952 	rc = xen_blkbk_map(blkif, pages, indirect_grefs, true);
953 	if (rc)
954 		goto unmap;
955 
956 	for (n = 0, i = 0; n < nseg; n++) {
957 		if ((n % SEGS_PER_INDIRECT_FRAME) == 0) {
958 			/* Map indirect segments */
959 			if (segments)
960 				kunmap_atomic(segments);
961 			segments = kmap_atomic(pages[n/SEGS_PER_INDIRECT_FRAME]->page);
962 		}
963 		i = n % SEGS_PER_INDIRECT_FRAME;
964 		pending_req->segments[n]->gref = segments[i].gref;
965 		seg[n].nsec = segments[i].last_sect -
966 			segments[i].first_sect + 1;
967 		seg[n].offset = (segments[i].first_sect << 9);
968 		if ((segments[i].last_sect >= (PAGE_SIZE >> 9)) ||
969 		    (segments[i].last_sect < segments[i].first_sect)) {
970 			rc = -EINVAL;
971 			goto unmap;
972 		}
973 		preq->nr_sects += seg[n].nsec;
974 	}
975 
976 unmap:
977 	if (segments)
978 		kunmap_atomic(segments);
979 	xen_blkbk_unmap(blkif, pages, indirect_grefs);
980 	return rc;
981 }
982 
983 static int dispatch_discard_io(struct xen_blkif *blkif,
984 				struct blkif_request *req)
985 {
986 	int err = 0;
987 	int status = BLKIF_RSP_OKAY;
988 	struct block_device *bdev = blkif->vbd.bdev;
989 	unsigned long secure;
990 	struct phys_req preq;
991 
992 	xen_blkif_get(blkif);
993 
994 	preq.sector_number = req->u.discard.sector_number;
995 	preq.nr_sects      = req->u.discard.nr_sectors;
996 
997 	err = xen_vbd_translate(&preq, blkif, WRITE);
998 	if (err) {
999 		pr_warn(DRV_PFX "access denied: DISCARD [%llu->%llu] on dev=%04x\n",
1000 			preq.sector_number,
1001 			preq.sector_number + preq.nr_sects, blkif->vbd.pdevice);
1002 		goto fail_response;
1003 	}
1004 	blkif->st_ds_req++;
1005 
1006 	secure = (blkif->vbd.discard_secure &&
1007 		 (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?
1008 		 BLKDEV_DISCARD_SECURE : 0;
1009 
1010 	err = blkdev_issue_discard(bdev, req->u.discard.sector_number,
1011 				   req->u.discard.nr_sectors,
1012 				   GFP_KERNEL, secure);
1013 fail_response:
1014 	if (err == -EOPNOTSUPP) {
1015 		pr_debug(DRV_PFX "discard op failed, not supported\n");
1016 		status = BLKIF_RSP_EOPNOTSUPP;
1017 	} else if (err)
1018 		status = BLKIF_RSP_ERROR;
1019 
1020 	make_response(blkif, req->u.discard.id, req->operation, status);
1021 	xen_blkif_put(blkif);
1022 	return err;
1023 }
1024 
1025 static int dispatch_other_io(struct xen_blkif *blkif,
1026 			     struct blkif_request *req,
1027 			     struct pending_req *pending_req)
1028 {
1029 	free_req(blkif, pending_req);
1030 	make_response(blkif, req->u.other.id, req->operation,
1031 		      BLKIF_RSP_EOPNOTSUPP);
1032 	return -EIO;
1033 }
1034 
1035 static void xen_blk_drain_io(struct xen_blkif *blkif)
1036 {
1037 	atomic_set(&blkif->drain, 1);
1038 	do {
1039 		if (atomic_read(&blkif->inflight) == 0)
1040 			break;
1041 		wait_for_completion_interruptible_timeout(
1042 				&blkif->drain_complete, HZ);
1043 
1044 		if (!atomic_read(&blkif->drain))
1045 			break;
1046 	} while (!kthread_should_stop());
1047 	atomic_set(&blkif->drain, 0);
1048 }
1049 
1050 /*
1051  * Completion callback on the bio's. Called as bh->b_end_io()
1052  */
1053 
1054 static void __end_block_io_op(struct pending_req *pending_req, int error)
1055 {
1056 	/* An error fails the entire request. */
1057 	if ((pending_req->operation == BLKIF_OP_FLUSH_DISKCACHE) &&
1058 	    (error == -EOPNOTSUPP)) {
1059 		pr_debug(DRV_PFX "flush diskcache op failed, not supported\n");
1060 		xen_blkbk_flush_diskcache(XBT_NIL, pending_req->blkif->be, 0);
1061 		pending_req->status = BLKIF_RSP_EOPNOTSUPP;
1062 	} else if ((pending_req->operation == BLKIF_OP_WRITE_BARRIER) &&
1063 		    (error == -EOPNOTSUPP)) {
1064 		pr_debug(DRV_PFX "write barrier op failed, not supported\n");
1065 		xen_blkbk_barrier(XBT_NIL, pending_req->blkif->be, 0);
1066 		pending_req->status = BLKIF_RSP_EOPNOTSUPP;
1067 	} else if (error) {
1068 		pr_debug(DRV_PFX "Buffer not up-to-date at end of operation,"
1069 			 " error=%d\n", error);
1070 		pending_req->status = BLKIF_RSP_ERROR;
1071 	}
1072 
1073 	/*
1074 	 * If all of the bio's have completed it is time to unmap
1075 	 * the grant references associated with 'request' and provide
1076 	 * the proper response on the ring.
1077 	 */
1078 	if (atomic_dec_and_test(&pending_req->pendcnt))
1079 		xen_blkbk_unmap_and_respond(pending_req);
1080 }
1081 
1082 /*
1083  * bio callback.
1084  */
1085 static void end_block_io_op(struct bio *bio, int error)
1086 {
1087 	__end_block_io_op(bio->bi_private, error);
1088 	bio_put(bio);
1089 }
1090 
1091 
1092 
1093 /*
1094  * Function to copy the from the ring buffer the 'struct blkif_request'
1095  * (which has the sectors we want, number of them, grant references, etc),
1096  * and transmute  it to the block API to hand it over to the proper block disk.
1097  */
1098 static int
1099 __do_block_io_op(struct xen_blkif *blkif)
1100 {
1101 	union blkif_back_rings *blk_rings = &blkif->blk_rings;
1102 	struct blkif_request req;
1103 	struct pending_req *pending_req;
1104 	RING_IDX rc, rp;
1105 	int more_to_do = 0;
1106 
1107 	rc = blk_rings->common.req_cons;
1108 	rp = blk_rings->common.sring->req_prod;
1109 	rmb(); /* Ensure we see queued requests up to 'rp'. */
1110 
1111 	if (RING_REQUEST_PROD_OVERFLOW(&blk_rings->common, rp)) {
1112 		rc = blk_rings->common.rsp_prod_pvt;
1113 		pr_warn(DRV_PFX "Frontend provided bogus ring requests (%d - %d = %d). Halting ring processing on dev=%04x\n",
1114 			rp, rc, rp - rc, blkif->vbd.pdevice);
1115 		return -EACCES;
1116 	}
1117 	while (rc != rp) {
1118 
1119 		if (RING_REQUEST_CONS_OVERFLOW(&blk_rings->common, rc))
1120 			break;
1121 
1122 		if (kthread_should_stop()) {
1123 			more_to_do = 1;
1124 			break;
1125 		}
1126 
1127 		pending_req = alloc_req(blkif);
1128 		if (NULL == pending_req) {
1129 			blkif->st_oo_req++;
1130 			more_to_do = 1;
1131 			break;
1132 		}
1133 
1134 		switch (blkif->blk_protocol) {
1135 		case BLKIF_PROTOCOL_NATIVE:
1136 			memcpy(&req, RING_GET_REQUEST(&blk_rings->native, rc), sizeof(req));
1137 			break;
1138 		case BLKIF_PROTOCOL_X86_32:
1139 			blkif_get_x86_32_req(&req, RING_GET_REQUEST(&blk_rings->x86_32, rc));
1140 			break;
1141 		case BLKIF_PROTOCOL_X86_64:
1142 			blkif_get_x86_64_req(&req, RING_GET_REQUEST(&blk_rings->x86_64, rc));
1143 			break;
1144 		default:
1145 			BUG();
1146 		}
1147 		blk_rings->common.req_cons = ++rc; /* before make_response() */
1148 
1149 		/* Apply all sanity checks to /private copy/ of request. */
1150 		barrier();
1151 
1152 		switch (req.operation) {
1153 		case BLKIF_OP_READ:
1154 		case BLKIF_OP_WRITE:
1155 		case BLKIF_OP_WRITE_BARRIER:
1156 		case BLKIF_OP_FLUSH_DISKCACHE:
1157 		case BLKIF_OP_INDIRECT:
1158 			if (dispatch_rw_block_io(blkif, &req, pending_req))
1159 				goto done;
1160 			break;
1161 		case BLKIF_OP_DISCARD:
1162 			free_req(blkif, pending_req);
1163 			if (dispatch_discard_io(blkif, &req))
1164 				goto done;
1165 			break;
1166 		default:
1167 			if (dispatch_other_io(blkif, &req, pending_req))
1168 				goto done;
1169 			break;
1170 		}
1171 
1172 		/* Yield point for this unbounded loop. */
1173 		cond_resched();
1174 	}
1175 done:
1176 	return more_to_do;
1177 }
1178 
1179 static int
1180 do_block_io_op(struct xen_blkif *blkif)
1181 {
1182 	union blkif_back_rings *blk_rings = &blkif->blk_rings;
1183 	int more_to_do;
1184 
1185 	do {
1186 		more_to_do = __do_block_io_op(blkif);
1187 		if (more_to_do)
1188 			break;
1189 
1190 		RING_FINAL_CHECK_FOR_REQUESTS(&blk_rings->common, more_to_do);
1191 	} while (more_to_do);
1192 
1193 	return more_to_do;
1194 }
1195 /*
1196  * Transmutation of the 'struct blkif_request' to a proper 'struct bio'
1197  * and call the 'submit_bio' to pass it to the underlying storage.
1198  */
1199 static int dispatch_rw_block_io(struct xen_blkif *blkif,
1200 				struct blkif_request *req,
1201 				struct pending_req *pending_req)
1202 {
1203 	struct phys_req preq;
1204 	struct seg_buf *seg = pending_req->seg;
1205 	unsigned int nseg;
1206 	struct bio *bio = NULL;
1207 	struct bio **biolist = pending_req->biolist;
1208 	int i, nbio = 0;
1209 	int operation;
1210 	struct blk_plug plug;
1211 	bool drain = false;
1212 	struct grant_page **pages = pending_req->segments;
1213 	unsigned short req_operation;
1214 
1215 	req_operation = req->operation == BLKIF_OP_INDIRECT ?
1216 			req->u.indirect.indirect_op : req->operation;
1217 	if ((req->operation == BLKIF_OP_INDIRECT) &&
1218 	    (req_operation != BLKIF_OP_READ) &&
1219 	    (req_operation != BLKIF_OP_WRITE)) {
1220 		pr_debug(DRV_PFX "Invalid indirect operation (%u)\n",
1221 			 req_operation);
1222 		goto fail_response;
1223 	}
1224 
1225 	switch (req_operation) {
1226 	case BLKIF_OP_READ:
1227 		blkif->st_rd_req++;
1228 		operation = READ;
1229 		break;
1230 	case BLKIF_OP_WRITE:
1231 		blkif->st_wr_req++;
1232 		operation = WRITE_ODIRECT;
1233 		break;
1234 	case BLKIF_OP_WRITE_BARRIER:
1235 		drain = true;
1236 	case BLKIF_OP_FLUSH_DISKCACHE:
1237 		blkif->st_f_req++;
1238 		operation = WRITE_FLUSH;
1239 		break;
1240 	default:
1241 		operation = 0; /* make gcc happy */
1242 		goto fail_response;
1243 		break;
1244 	}
1245 
1246 	/* Check that the number of segments is sane. */
1247 	nseg = req->operation == BLKIF_OP_INDIRECT ?
1248 	       req->u.indirect.nr_segments : req->u.rw.nr_segments;
1249 
1250 	if (unlikely(nseg == 0 && operation != WRITE_FLUSH) ||
1251 	    unlikely((req->operation != BLKIF_OP_INDIRECT) &&
1252 		     (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) ||
1253 	    unlikely((req->operation == BLKIF_OP_INDIRECT) &&
1254 		     (nseg > MAX_INDIRECT_SEGMENTS))) {
1255 		pr_debug(DRV_PFX "Bad number of segments in request (%d)\n",
1256 			 nseg);
1257 		/* Haven't submitted any bio's yet. */
1258 		goto fail_response;
1259 	}
1260 
1261 	preq.nr_sects      = 0;
1262 
1263 	pending_req->blkif     = blkif;
1264 	pending_req->id        = req->u.rw.id;
1265 	pending_req->operation = req_operation;
1266 	pending_req->status    = BLKIF_RSP_OKAY;
1267 	pending_req->nr_pages  = nseg;
1268 
1269 	if (req->operation != BLKIF_OP_INDIRECT) {
1270 		preq.dev               = req->u.rw.handle;
1271 		preq.sector_number     = req->u.rw.sector_number;
1272 		for (i = 0; i < nseg; i++) {
1273 			pages[i]->gref = req->u.rw.seg[i].gref;
1274 			seg[i].nsec = req->u.rw.seg[i].last_sect -
1275 				req->u.rw.seg[i].first_sect + 1;
1276 			seg[i].offset = (req->u.rw.seg[i].first_sect << 9);
1277 			if ((req->u.rw.seg[i].last_sect >= (PAGE_SIZE >> 9)) ||
1278 			    (req->u.rw.seg[i].last_sect <
1279 			     req->u.rw.seg[i].first_sect))
1280 				goto fail_response;
1281 			preq.nr_sects += seg[i].nsec;
1282 		}
1283 	} else {
1284 		preq.dev               = req->u.indirect.handle;
1285 		preq.sector_number     = req->u.indirect.sector_number;
1286 		if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq))
1287 			goto fail_response;
1288 	}
1289 
1290 	if (xen_vbd_translate(&preq, blkif, operation) != 0) {
1291 		pr_debug(DRV_PFX "access denied: %s of [%llu,%llu] on dev=%04x\n",
1292 			 operation == READ ? "read" : "write",
1293 			 preq.sector_number,
1294 			 preq.sector_number + preq.nr_sects,
1295 			 blkif->vbd.pdevice);
1296 		goto fail_response;
1297 	}
1298 
1299 	/*
1300 	 * This check _MUST_ be done after xen_vbd_translate as the preq.bdev
1301 	 * is set there.
1302 	 */
1303 	for (i = 0; i < nseg; i++) {
1304 		if (((int)preq.sector_number|(int)seg[i].nsec) &
1305 		    ((bdev_logical_block_size(preq.bdev) >> 9) - 1)) {
1306 			pr_debug(DRV_PFX "Misaligned I/O request from domain %d",
1307 				 blkif->domid);
1308 			goto fail_response;
1309 		}
1310 	}
1311 
1312 	/* Wait on all outstanding I/O's and once that has been completed
1313 	 * issue the WRITE_FLUSH.
1314 	 */
1315 	if (drain)
1316 		xen_blk_drain_io(pending_req->blkif);
1317 
1318 	/*
1319 	 * If we have failed at this point, we need to undo the M2P override,
1320 	 * set gnttab_set_unmap_op on all of the grant references and perform
1321 	 * the hypercall to unmap the grants - that is all done in
1322 	 * xen_blkbk_unmap.
1323 	 */
1324 	if (xen_blkbk_map_seg(pending_req))
1325 		goto fail_flush;
1326 
1327 	/*
1328 	 * This corresponding xen_blkif_put is done in __end_block_io_op, or
1329 	 * below (in "!bio") if we are handling a BLKIF_OP_DISCARD.
1330 	 */
1331 	xen_blkif_get(blkif);
1332 	atomic_inc(&blkif->inflight);
1333 
1334 	for (i = 0; i < nseg; i++) {
1335 		while ((bio == NULL) ||
1336 		       (bio_add_page(bio,
1337 				     pages[i]->page,
1338 				     seg[i].nsec << 9,
1339 				     seg[i].offset) == 0)) {
1340 
1341 			int nr_iovecs = min_t(int, (nseg-i), BIO_MAX_PAGES);
1342 			bio = bio_alloc(GFP_KERNEL, nr_iovecs);
1343 			if (unlikely(bio == NULL))
1344 				goto fail_put_bio;
1345 
1346 			biolist[nbio++] = bio;
1347 			bio->bi_bdev    = preq.bdev;
1348 			bio->bi_private = pending_req;
1349 			bio->bi_end_io  = end_block_io_op;
1350 			bio->bi_iter.bi_sector  = preq.sector_number;
1351 		}
1352 
1353 		preq.sector_number += seg[i].nsec;
1354 	}
1355 
1356 	/* This will be hit if the operation was a flush or discard. */
1357 	if (!bio) {
1358 		BUG_ON(operation != WRITE_FLUSH);
1359 
1360 		bio = bio_alloc(GFP_KERNEL, 0);
1361 		if (unlikely(bio == NULL))
1362 			goto fail_put_bio;
1363 
1364 		biolist[nbio++] = bio;
1365 		bio->bi_bdev    = preq.bdev;
1366 		bio->bi_private = pending_req;
1367 		bio->bi_end_io  = end_block_io_op;
1368 	}
1369 
1370 	atomic_set(&pending_req->pendcnt, nbio);
1371 	blk_start_plug(&plug);
1372 
1373 	for (i = 0; i < nbio; i++)
1374 		submit_bio(operation, biolist[i]);
1375 
1376 	/* Let the I/Os go.. */
1377 	blk_finish_plug(&plug);
1378 
1379 	if (operation == READ)
1380 		blkif->st_rd_sect += preq.nr_sects;
1381 	else if (operation & WRITE)
1382 		blkif->st_wr_sect += preq.nr_sects;
1383 
1384 	return 0;
1385 
1386  fail_flush:
1387 	xen_blkbk_unmap(blkif, pending_req->segments,
1388 	                pending_req->nr_pages);
1389  fail_response:
1390 	/* Haven't submitted any bio's yet. */
1391 	make_response(blkif, req->u.rw.id, req_operation, BLKIF_RSP_ERROR);
1392 	free_req(blkif, pending_req);
1393 	msleep(1); /* back off a bit */
1394 	return -EIO;
1395 
1396  fail_put_bio:
1397 	for (i = 0; i < nbio; i++)
1398 		bio_put(biolist[i]);
1399 	atomic_set(&pending_req->pendcnt, 1);
1400 	__end_block_io_op(pending_req, -EINVAL);
1401 	msleep(1); /* back off a bit */
1402 	return -EIO;
1403 }
1404 
1405 
1406 
1407 /*
1408  * Put a response on the ring on how the operation fared.
1409  */
1410 static void make_response(struct xen_blkif *blkif, u64 id,
1411 			  unsigned short op, int st)
1412 {
1413 	struct blkif_response  resp;
1414 	unsigned long     flags;
1415 	union blkif_back_rings *blk_rings = &blkif->blk_rings;
1416 	int notify;
1417 
1418 	resp.id        = id;
1419 	resp.operation = op;
1420 	resp.status    = st;
1421 
1422 	spin_lock_irqsave(&blkif->blk_ring_lock, flags);
1423 	/* Place on the response ring for the relevant domain. */
1424 	switch (blkif->blk_protocol) {
1425 	case BLKIF_PROTOCOL_NATIVE:
1426 		memcpy(RING_GET_RESPONSE(&blk_rings->native, blk_rings->native.rsp_prod_pvt),
1427 		       &resp, sizeof(resp));
1428 		break;
1429 	case BLKIF_PROTOCOL_X86_32:
1430 		memcpy(RING_GET_RESPONSE(&blk_rings->x86_32, blk_rings->x86_32.rsp_prod_pvt),
1431 		       &resp, sizeof(resp));
1432 		break;
1433 	case BLKIF_PROTOCOL_X86_64:
1434 		memcpy(RING_GET_RESPONSE(&blk_rings->x86_64, blk_rings->x86_64.rsp_prod_pvt),
1435 		       &resp, sizeof(resp));
1436 		break;
1437 	default:
1438 		BUG();
1439 	}
1440 	blk_rings->common.rsp_prod_pvt++;
1441 	RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blk_rings->common, notify);
1442 	spin_unlock_irqrestore(&blkif->blk_ring_lock, flags);
1443 	if (notify)
1444 		notify_remote_via_irq(blkif->irq);
1445 }
1446 
1447 static int __init xen_blkif_init(void)
1448 {
1449 	int rc = 0;
1450 
1451 	if (!xen_domain())
1452 		return -ENODEV;
1453 
1454 	rc = xen_blkif_interface_init();
1455 	if (rc)
1456 		goto failed_init;
1457 
1458 	rc = xen_blkif_xenbus_init();
1459 	if (rc)
1460 		goto failed_init;
1461 
1462  failed_init:
1463 	return rc;
1464 }
1465 
1466 module_init(xen_blkif_init);
1467 
1468 MODULE_LICENSE("Dual BSD/GPL");
1469 MODULE_ALIAS("xen-backend:vbd");
1470