+ n_pages = rk_obj->num_pages;
+
+ dst_pages = drm_malloc_ab(n_pages, sizeof(struct page *));
+ if (!dst_pages) {
+ ret = -ENOMEM;
+ goto err_put_pages;
+ }
+
+ cur_page = 0;
+ remain = n_pages;
+ /* look for the end of the current chunk */
+ while (remain) {
+ for (j = cur_page + 1; j < n_pages; ++j) {
+ if (page_to_pfn(pages[j]) !=
+ page_to_pfn(pages[j - 1]) + 1)
+ break;
+ }
+
+ chunk_pages = j - cur_page;
+
+ if (chunk_pages > 7) {
+ for (i = 0; i < chunk_pages; i++)
+ dst_pages[end + i] = pages[cur_page + i];
+ end += chunk_pages;
+ } else {
+ for (i = 0; i < chunk_pages; i++) {
+ info = kmalloc(sizeof(*info), GFP_KERNEL);
+ if (!info) {
+ ret = -ENOMEM;
+ goto err_put_list;
+ }
+
+ INIT_LIST_HEAD(&info->list);
+ info->page = pages[cur_page + i];
+ phys = page_to_phys(info->page);
+ bit12_14 = (phys >> 12) & 0x7;
+ list_add_tail(&info->list, &lists[bit12_14]);
+ block_index[bit12_14]++;
+ }
+ }
+
+ cur_page = j;
+ remain -= chunk_pages;
+ }
+
+ maximum = block_index[0];
+ for (i = 1; i < PG_ROUND; i++)
+ maximum = max(maximum, block_index[i]);
+
+ for (i = 0; i < maximum; i++) {
+ for (j = 0; j < PG_ROUND; j++) {
+ if (!list_empty(&lists[j])) {
+ struct page_info *info;
+
+ info = list_first_entry(&lists[j],
+ struct page_info, list);
+ dst_pages[end++] = info->page;
+ list_del(&info->list);
+ kfree(info);
+ }
+ }
+ }
+
+ DRM_DEBUG_KMS("%s, %d, end = %d, n_pages = %d\n", __func__, __LINE__,
+ end, n_pages);
+
+ rk_obj->sgt = drm_prime_pages_to_sg(dst_pages, rk_obj->num_pages);