drm/ttm: swap consecutive allocated cached pages v3

When we detect consecutive allocation of pages swap them to avoid
accidentally freeing them as huge page.

v2: use swap
v3: check if it's really the first allocated page

Signed-off-by: Christian König <christian.koenig@amd.com>
Reviewed-by: Roger He <Hongbo.He@amd.com>
Reviewed-by: Michel Dänzer <michel.daenzer@amd.com>
Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
diff --git a/drivers/gpu/drm/ttm/ttm_page_alloc.c b/drivers/gpu/drm/ttm/ttm_page_alloc.c
index 116897a..b6f7ce2 100644
--- a/drivers/gpu/drm/ttm/ttm_page_alloc.c
+++ b/drivers/gpu/drm/ttm/ttm_page_alloc.c
@@ -877,7 +877,7 @@ static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
 #endif
 	struct list_head plist;
 	struct page *p = NULL;
-	unsigned count;
+	unsigned count, first;
 	int r;
 
 	/* No pool for cached pages */
@@ -918,6 +918,7 @@ static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
 		}
 #endif
 
+		first = i;
 		while (npages) {
 			p = alloc_page(gfp_flags);
 			if (!p) {
@@ -925,6 +926,10 @@ static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
 				return -ENOMEM;
 			}
 
+			/* Swap the pages if we detect consecutive order */
+			if (i > first && pages[i - 1] == p - 1)
+				swap(p, pages[i - 1]);
+
 			pages[i++] = p;
 			--npages;
 		}