主頁 > 作業系統 > 伙伴系統分配記憶體

伙伴系統分配記憶體

2020-09-10 21:51:14 作業系統

內核中常用的分配物理記憶體頁面的介面函式是alloc_pages(),用于分配一個或者多個連續的物理頁面,分配頁面個數只能是2個整數次冪,相比于多次分配離散的物理頁面,分配連續的物理頁面有利于提高系統記憶體的碎片化,記憶體碎片化是一個很讓人頭疼的問題,alloc_pages()函式有兩個,一個是分配gfp_mask,另一個是分配階數order,

[include/linux/gfp.h]
#define alloc_pages(gfp_mask, order)	\
	alloc_pages_node(numa_node_id(), gfp_mask, order)

分配掩碼是非常重要的引數,它同樣定義在gfp.h頭檔案中,

/* Plain integer GFP bitmasks. Do not use this directly. */
#define ___GFP_DMA		0x01u
#define ___GFP_HIGHMEM		0x02u
#define ___GFP_DMA32		0x04u
#define ___GFP_MOVABLE		0x08u
#define ___GFP_WAIT		0x10u
#define ___GFP_HIGH		0x20u
#define ___GFP_IO		0x40u
#define ___GFP_FS		0x80u
#define ___GFP_COLD		0x100u
#define ___GFP_NOWARN		0x200u
#define ___GFP_REPEAT		0x400u
#define ___GFP_NOFAIL		0x800u
#define ___GFP_NORETRY		0x1000u
#define ___GFP_MEMALLOC		0x2000u
#define ___GFP_COMP		0x4000u
#define ___GFP_ZERO		0x8000u
#define ___GFP_NOMEMALLOC	0x10000u
#define ___GFP_HARDWALL		0x20000u
#define ___GFP_THISNODE		0x40000u
#define ___GFP_RECLAIMABLE	0x80000u
#define ___GFP_NOTRACK		0x200000u
#define ___GFP_NO_KSWAPD	0x400000u
#define ___GFP_OTHER_NODE	0x800000u
#define ___GFP_WRITE		0x1000000u

分配掩碼是在內核代碼中分成兩類,一類叫zone modifiers,另一類是action modifiers,zone modifiers指定從哪一個zone中分配所需的頁面,zone modifiers由分配掩碼的最低4位來定義,分別是___GFP_DMA___GFP_HIGHMEM___GFP_DMA32___GFP_MOVABLE

/* If the above are modified, __GFP_BITS_SHIFT may need updating */

/*
 * GFP bitmasks..
 *
 * Zone modifiers (see linux/mmzone.h - low three bits)
 *
 * Do not put any conditional on these. If necessary modify the definitions
 * without the underscores and use them consistently. The definitions here may
 * be used in bit comparisons.
 */
#define __GFP_DMA	((__force gfp_t)___GFP_DMA)
#define __GFP_HIGHMEM	((__force gfp_t)___GFP_HIGHMEM)
#define __GFP_DMA32	((__force gfp_t)___GFP_DMA32)
#define __GFP_MOVABLE	((__force gfp_t)___GFP_MOVABLE)  /* Page is movable */
#define GFP_ZONEMASK	(__GFP_DMA|__GFP_HIGHMEM|__GFP_DMA32|__GFP_MOVABLE)

action modifiers并不限制從哪個記憶體域中分配記憶體,但會改變分配行為,其定義如下:

/*
 * Action modifiers - doesn't change the zoning
 *
 * __GFP_REPEAT: Try hard to allocate the memory, but the allocation attempt
 * _might_ fail.  This depends upon the particular VM implementation.
 *
 * __GFP_NOFAIL: The VM implementation _must_ retry infinitely: the caller
 * cannot handle allocation failures.  This modifier is deprecated and no new
 * users should be added.
 *
 * __GFP_NORETRY: The VM implementation must not retry indefinitely.
 *
 * __GFP_MOVABLE: Flag that this page will be movable by the page migration
 * mechanism or reclaimed
 */
#define __GFP_WAIT	((__force gfp_t)___GFP_WAIT)	/* Can wait and reschedule? */
#define __GFP_HIGH	((__force gfp_t)___GFP_HIGH)	/* Should access emergency pools? */
#define __GFP_IO	((__force gfp_t)___GFP_IO)	/* Can start physical IO? */
#define __GFP_FS	((__force gfp_t)___GFP_FS)	/* Can call down to low-level FS? */
#define __GFP_COLD	((__force gfp_t)___GFP_COLD)	/* Cache-cold page required */
#define __GFP_NOWARN	((__force gfp_t)___GFP_NOWARN)	/* Suppress page allocation failure warning */
#define __GFP_REPEAT	((__force gfp_t)___GFP_REPEAT)	/* See above */
#define __GFP_NOFAIL	((__force gfp_t)___GFP_NOFAIL)	/* See above */
#define __GFP_NORETRY	((__force gfp_t)___GFP_NORETRY) /* See above */
#define __GFP_MEMALLOC	((__force gfp_t)___GFP_MEMALLOC)/* Allow access to emergency reserves */
#define __GFP_COMP	((__force gfp_t)___GFP_COMP)	/* Add compound page metadata */
#define __GFP_ZERO	((__force gfp_t)___GFP_ZERO)	/* Return zeroed page on success */
#define __GFP_NOMEMALLOC ((__force gfp_t)___GFP_NOMEMALLOC) /* Don't use emergency reserves.
							 * This takes precedence over the
							 * __GFP_MEMALLOC flag if both are
							 * set
							 */
#define __GFP_HARDWALL   ((__force gfp_t)___GFP_HARDWALL) /* Enforce hardwall cpuset memory allocs */
#define __GFP_THISNODE	((__force gfp_t)___GFP_THISNODE)/* No fallback, no policies */
#define __GFP_RECLAIMABLE ((__force gfp_t)___GFP_RECLAIMABLE) /* Page is reclaimable */
#define __GFP_NOTRACK	((__force gfp_t)___GFP_NOTRACK)  /* Don't track with kmemcheck */

#define __GFP_NO_KSWAPD	((__force gfp_t)___GFP_NO_KSWAPD)
#define __GFP_OTHER_NODE ((__force gfp_t)___GFP_OTHER_NODE) /* On behalf of other node */
#define __GFP_WRITE	((__force gfp_t)___GFP_WRITE)	/* Allocator intends to dirty page */

上述這些標志位,我們在后續代碼中遇到時再詳細介紹,

下面是GFP_KERNEL為例,為看理想情況下alloc_pages()函式是如何分配出物理記憶體的,

[分配物理記憶體的例子]
page = alloc_pages(GFP_KERNEL, order);

GFP_KERNEL分配掩碼定義在gfp.h頭檔案上,是一個分配掩碼的組合,常用的分配掩碼組合如下:

/* This equals 0, but use constants in case they ever change */
#define GFP_NOWAIT	(GFP_ATOMIC & ~__GFP_HIGH)
/* GFP_ATOMIC means both !wait (__GFP_WAIT not set) and use emergency pool */
#define GFP_ATOMIC	(__GFP_HIGH)
#define GFP_NOIO	(__GFP_WAIT)
#define GFP_NOFS	(__GFP_WAIT | __GFP_IO)
#define GFP_KERNEL	(__GFP_WAIT | __GFP_IO | __GFP_FS)
#define GFP_TEMPORARY	(__GFP_WAIT | __GFP_IO | __GFP_FS | \
			 __GFP_RECLAIMABLE)
#define GFP_USER	(__GFP_WAIT | __GFP_IO | __GFP_FS | __GFP_HARDWALL)
#define GFP_HIGHUSER	(GFP_USER | __GFP_HIGHMEM)
#define GFP_HIGHUSER_MOVABLE	(GFP_HIGHUSER | __GFP_MOVABLE)
#define GFP_IOFS	(__GFP_IO | __GFP_FS)
#define GFP_TRANSHUGE	(GFP_HIGHUSER_MOVABLE | __GFP_COMP | \
			 __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN | \
			 __GFP_NO_KSWAPD)

所以GFP_KERNEL分配掩碼包含了__GFP_WAIT__GFP_IO__GFP_FS這三個標志位,換算成十六進制0xd0;

alloc_pages()最終呼叫__alloc_pages_nodemask()函式,它是伙伴系統的核心函式;

/*
 * This is the 'heart' of the zoned buddy allocator.
 */
struct page *
__alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order,
			struct zonelist *zonelist, nodemask_t *nodemask)
{
	struct zoneref *preferred_zoneref;
	struct page *page = NULL;
	unsigned int cpuset_mems_cookie;
	int alloc_flags = ALLOC_WMARK_LOW|ALLOC_CPUSET|ALLOC_FAIR;
	gfp_t alloc_mask; /* The gfp_t that was actually used for allocation */
	struct alloc_context ac = {
		.high_zoneidx = gfp_zone(gfp_mask),
		.nodemask = nodemask,
		.migratetype = gfpflags_to_migratetype(gfp_mask),
	};

struct alloc_context資料結構是伙伴系統分配函式中用于保存相關引數的資料結構,gfp_zone()函式從分配掩碼中計算出zone的zoneidx,并存放high_zoneidx成員中,

static inline enum zone_type gfp_zone(gfp_t flags)
{
	enum zone_type z;
	int bit = (__force int) (flags & GFP_ZONEMASK);

	z = (GFP_ZONE_TABLE >> (bit * ZONES_SHIFT)) &
					 ((1 << ZONES_SHIFT) - 1);
	VM_BUG_ON((GFP_ZONE_BAD >> bit) & 1);
	return z;
}

gfp_zone()函式會用到GFP_ZONEMASK、GFP_ZONE_TABLE和ZONES_SHIFT等宏,它們的定義如下:

#define GFP_ZONEMASK	(__GFP_DMA|__GFP_HIGHMEM|__GFP_DMA32|__GFP_MOVABLE)
#define GFP_ZONE_TABLE ( \
	(ZONE_NORMAL << 0 * ZONES_SHIFT)				      \
	| (OPT_ZONE_DMA << ___GFP_DMA * ZONES_SHIFT)			      \
	| (OPT_ZONE_HIGHMEM << ___GFP_HIGHMEM * ZONES_SHIFT)		      \
	| (OPT_ZONE_DMA32 << ___GFP_DMA32 * ZONES_SHIFT)		      \
	| (ZONE_NORMAL << ___GFP_MOVABLE * ZONES_SHIFT)			      \
	| (OPT_ZONE_DMA << (___GFP_MOVABLE | ___GFP_DMA) * ZONES_SHIFT)	      \
	| (ZONE_MOVABLE << (___GFP_MOVABLE | ___GFP_HIGHMEM) * ZONES_SHIFT)   \
	| (OPT_ZONE_DMA32 << (___GFP_MOVABLE | ___GFP_DMA32) * ZONES_SHIFT)   \
)
#if MAX_NR_ZONES < 2
#define ZONES_SHIFT 0
#elif MAX_NR_ZONES <= 2
#define ZONES_SHIFT 1
#elif MAX_NR_ZONES <= 4
#define ZONES_SHIFT 2

GFP_ZONEMASK是分配掩碼的低4位,在ARM Vexprss平臺上,只有ZONE_NORMAL和ZONE_HIGHMEM這兩個zone,但是計算__MAX_NR_ZONES需要加上ZONE_MOVABLE,所以MAX_NR_ZONES等于3,這里ZONE_SHIFT等于2,那么GFP_ZONE_TABLE計算結果等于0x200010,

在上述例子中,以GFP_KERNEL分配掩碼(0xd0)為引數代入gfp_zone()函式中,最終結果為0,即high_zoneidx為0,

另外__alloc_pages_nodemask()第15行代碼中的gfpflags_to_migratetype()函式把gfp_mask分配掩碼轉換成MIGRATE_TYPES型別是MIGRATE_UNMOVABLE;如果分配掩碼為GFP_HIGHUSER_MOVABLE,那么MIGRATE_TYPES型別是MIGRATE_MOVABLE

/* Convert GFP flags to their corresponding migrate type */
static inline int gfpflags_to_migratetype(const gfp_t gfp_flags)
{
	WARN_ON((gfp_flags & GFP_MOVABLE_MASK) == GFP_MOVABLE_MASK);

	if (unlikely(page_group_by_mobility_disabled))
		return MIGRATE_UNMOVABLE;

	/* Group based on mobility */
	return (((gfp_flags & __GFP_MOVABLE) != 0) << 1) |
		((gfp_flags & __GFP_RECLAIMABLE) != 0);
}

繼續回到__alloc_pages_nodemask()函式中,

[__alloc_pages_nodemask]
retry_cpuset:
	cpuset_mems_cookie = read_mems_allowed_begin();

	/* We set it here, as __alloc_pages_slowpath might have changed it */
	ac.zonelist = zonelist;
	/* The preferred zone is used for statistics later */
	preferred_zoneref = first_zones_zonelist(ac.zonelist, ac.high_zoneidx,
				ac.nodemask ? : &cpuset_current_mems_allowed,
				&ac.preferred_zone);
	if (!ac.preferred_zone)
		goto out;
	ac.classzone_idx = zonelist_zone_idx(preferred_zoneref);

	/* First allocation attempt */
	alloc_mask = gfp_mask|__GFP_HARDWALL;
	page = get_page_from_freelist(alloc_mask, order, alloc_flags, &ac);
	if (unlikely(!page)) {
		/*
		 * Runtime PM, block IO and its error handling path
		 * can deadlock because I/O on the device might not
		 * complete.
		 */
		alloc_mask = memalloc_noio_flags(gfp_mask);

		page = __alloc_pages_slowpath(alloc_mask, order, &ac);
	}

	if (kmemcheck_enabled && page)
		kmemcheck_pagealloc_alloc(page, order, gfp_mask);

	trace_mm_page_alloc(page, order, alloc_mask, ac.migratetype);

out:
	/*
	 * When updating a task's mems_allowed, it is possible to race with
	 * parallel threads in such a way that an allocation can fail while
	 * the mask is being updated. If a page allocation is about to fail,
	 * check if the cpuset changed during allocation and if so, retry.
	 */
	if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
		goto retry_cpuset;

	return page;

首先get_page_from_freelist()會去嘗試分配物理頁面,如果這里分配失敗,就會呼叫到__alloc_pages_slowpath()函式,這個函式會處理許多特殊的場景,這里假設在理想情況下,get_page_from_freelist()能分配成功;

/*
 * get_page_from_freelist goes through the zonelist trying to allocate
 * a page.
 */
static struct page *
get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags,
						const struct alloc_context *ac)
{
	struct zonelist *zonelist = ac->zonelist;
	struct zoneref *z;
	struct page *page = NULL;
	struct zone *zone;
	nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */
	int zlc_active = 0;		/* set if using zonelist_cache */
	int did_zlc_setup = 0;		/* just call zlc_setup() one time */
	bool consider_zone_dirty = (alloc_flags & ALLOC_WMARK_LOW) &&
				(gfp_mask & __GFP_WRITE);
	int nr_fair_skipped = 0;
	bool zonelist_rescan;

zonelist_scan:
	zonelist_rescan = false;

	/*
	 * Scan zonelist, looking for a zone with enough free.
	 * See also __cpuset_node_allowed() comment in kernel/cpuset.c.
	 */
	for_each_zone_zonelist_nodemask(zone, z, zonelist, ac->high_zoneidx,
								ac->nodemask) {

get_page_from_freelist()函式首先需要先判斷可以從哪一個zone來分配記憶體,for_each_zone_zonelist_nodemask宏掃描記憶體節點中的zonelist去查找合適分配記憶體的zone,

/**
 * for_each_zone_zonelist_nodemask - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask
 * @zone - The current zone in the iterator
 * @z - The current pointer within zonelist->zones being iterated
 * @zlist - The zonelist being iterated
 * @highidx - The zone index of the highest zone to return
 * @nodemask - Nodemask allowed by the allocator
 *
 * This iterator iterates though all zones at or below a given zone index and
 * within a given nodemask
 */
#define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \
	for (z = first_zones_zonelist(zlist, highidx, nodemask, &zone);	\
		zone;							\
		z = next_zones_zonelist(++z, highidx, nodemask),	\
			zone = zonelist_zone(z))			\

for_each_zone_zonelist_nodemask首先通過first_zones_zonelist()從給定的zoneidx開始查找,這個給定的zoneidx就是highidx,之前通過gfp_zone()函式轉換得來的,

/**
 * first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist
 * @zonelist - The zonelist to search for a suitable zone
 * @highest_zoneidx - The zone index of the highest zone to return
 * @nodes - An optional nodemask to filter the zonelist with
 * @zone - The first suitable zone found is returned via this parameter
 *
 * This function returns the first zone at or below a given zone index that is
 * within the allowed nodemask. The zoneref returned is a cursor that can be
 * used to iterate the zonelist with next_zones_zonelist by advancing it by
 * one before calling.
 */
static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist,
					enum zone_type highest_zoneidx,
					nodemask_t *nodes,
					struct zone **zone)
{
	struct zoneref *z = next_zones_zonelist(zonelist->_zonerefs,
							highest_zoneidx, nodes);
	*zone = zonelist_zone(z);
	return z;
}

first_zones_zonelist()函式會呼叫next_zones_zonelist()函式來計算zoneref,最后回傳zone資料結構;

struct zoneref *next_zones_zonelist(struct zoneref *z,
					enum zone_type highest_zoneidx,
					nodemask_t *nodes)
{
	/*
	 * Find the next suitable zone to use for the allocation.
	 * Only filter based on nodemask if it's set
	 */
	if (likely(nodes == NULL))
		while (zonelist_zone_idx(z) > highest_zoneidx)
			z++;
	else
		while (zonelist_zone_idx(z) > highest_zoneidx ||
				(z->zone && !zref_in_nodemask(z, nodes)))
			z++;

	return z;
}

計算zone的核心函式在next_zones_zonelist()函式中,這里highest_zoneidx是gfp_zone()函式計算分配掩碼得來,zonelist有一個zoneref陣列,zoneref資料結構里有一個成員zone指標會指向zone資料結構,還有一個zone_index成員指向zone的編號,zone在系統處理時會初始化這個陣列,具體函式在build_zonelists_node()中,在ARM Vexpress平臺中,zone型別、zoneref[]陣列和zoneidx的關系如下:

ZONE_HIGHMEM	__zonerefs[0]->zone_index=1
ZONE_NORMAL		__zonerefs[1]->zone_index=0

zonerefs[0]表示ZONE_HIGHMEM,其zone編號zone_index的值為1;zonerefs[1]表示ZONE_NORMAL,其zone的編號zone_index為0,也就是說,基于zone的設計思想是:分配物理頁面時會優先考慮ZONE_HIGHMEM,因為ZONE_HIGHMEM在zonelist中排在ZONE_NORMAL前面

回到我們之前的例子,gfp_zone(GFP_KERNEL)函式回傳0,即highest_zoneidx為0,而這個記憶體節點的第一個zone是ZONE_HIGHMEM,其zone編號zone_index的值為1.因此在next_zones_zonelist()中,z++,最終first_zones_zonelist()函式會回傳ZONE_NORMAL,在for_each_zone_zonelist_nodemask()遍歷程序中也只能遍歷ZONE_NORMAL這一個zone了,

再舉一個例子,分配掩碼GFP_HIGHUSER_MOVABLE,GFP_HIGHUSER_MOVEABLE包含了__GFP_HIGHMEM,那么next_zones_zonelist()函式回傳哪個zone呢?

GFP_HIGHUSER_MOVABLE的值為0x200da,那么gfp_zone(GFP_HIGHUSER_MOVABLE)函式等于2,即highest_zoneidx為2,而這個記憶體節點的第一個ZONE_HIGHME,其zone編號zone_index的值為1;

  • first_zones_zonelist()函式中,由于第一個zone的zone_index值小于highest_zoneidx,因此會回傳ZONE_HIGHMEM,

  • for_each_zone_zonelist_nodemask()函式中,next_zones_zonelist(++z, highidx, nodemask)依然會回傳ZONE_NORMAL;

  • 因此這里會遍歷ZONE_HIGHMEM和ZONE_NORMAL,這兩個zone,但是會先遍歷ZONE_HIGHMEM,然后才是ZONE_NORMAL,

    要正確理解for_each_zone_zonelist_nodemask()這個宏的行為,需要理解如下兩個方面:

    • highest_zoneidx是怎么計算得來的,即如何決議分配掩碼,這是gfp_zone()函式的職責,
    • 每個記憶體節點都有一個struct pglist_data資料結構,其成員node_zonelists是一個struct zonelist資料結構,zonelist中包含了struct zoneref __zonerefs[]陣列來描述這些zone,其中ZONE_HIGHMEM排在前面,并且 _zonerefs[0]->zone_index=1,ZONE_NORMAL排在后面,且 _zonerefs[1]->zone_index=0;

    上述這些設計讓人感覺復雜,但是這是正確理解以zone為基礎的物理頁面分配機制的基石,(說實話zone的分配實在是奇妙~)

    __alloc_page_nodemask()的第24行代碼呼叫first_zones_zonelist(),計算出preferred_zoneref并且保存到ac.classzone_idx變數中,該變數在kswapd內核執行緒中還會用到,例如以GFP_KERNEL為分配掩碼,preferred_zone指的是ZONE_NORMAL,ac.classzone_idx的值為0;

    回到get_page_from_freelist()函式中,for_each_zone_zonelist_nodemask()找到了接下來可以從哪些zone中分配記憶體,下面做一些必要的檢查;

    [get_page_from_freelist()]
    ....
    		if (cpusets_enabled() &&
    			(alloc_flags & ALLOC_CPUSET) &&
    			!cpuset_zone_allowed(zone, gfp_mask))
    				continue;
    		/*
    		 * Distribute pages in proportion to the individual
    		 * zone size to ensure fair page aging.  The zone a
    		 * page was allocated in should have no effect on the
    		 * time the page has in memory before being reclaimed.
    		 */
    		if (alloc_flags & ALLOC_FAIR) {
    			if (!zone_local(ac->preferred_zone, zone))
    				break;
    			if (test_bit(ZONE_FAIR_DEPLETED, &zone->flags)) {
    				nr_fair_skipped++;
    				continue;
    			}
    		}
    		/*
    		 * When allocating a page cache page for writing, we
    		 * want to get it from a zone that is within its dirty
    		 * limit, such that no single zone holds more than its
    		 * proportional share of globally allowed dirty pages.
    		 * The dirty limits take into account the zone's
    		 * lowmem reserves and high watermark so that kswapd
    		 * should be able to balance it without having to
    		 * write pages from its LRU list.
    		 *
    		 * This may look like it could increase pressure on
    		 * lower zones by failing allocations in higher zones
    		 * before they are full.  But the pages that do spill
    		 * over are limited as the lower zones are protected
    		 * by this very same mechanism.  It should not become
    		 * a practical burden to them.
    		 *
    		 * XXX: For now, allow allocations to potentially
    		 * exceed the per-zone dirty limit in the slowpath
    		 * (ALLOC_WMARK_LOW unset) before going into reclaim,
    		 * which is important when on a NUMA setup the allowed
    		 * zones are together not big enough to reach the
    		 * global limit.  The proper fix for these situations
    		 * will require awareness of zones in the
    		 * dirty-throttling and the flusher threads.
    		 */
    		if (consider_zone_dirty && !zone_dirty_ok(zone))
    			continue;
    .....
    

    下面代碼用于檢測當前zone的watermark水位是否充足,

    [get_page_from_freelist()]
    ...
    		mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK];
    		if (!zone_watermark_ok(zone, order, mark,
    				       ac->classzone_idx, alloc_flags)) {
    			...
    			ret = zone_reclaim(zone, gfp_mask, order);
    			switch (ret) {
    			case ZONE_RECLAIM_NOSCAN:
    				/* did not scan */
    				continue;
    			case ZONE_RECLAIM_FULL:
    				/* scanned but unreclaimable */
    				continue;
    			default:
    				/* did we reclaim enough */
    				if (zone_watermark_ok(zone, order, mark,
    						ac->classzone_idx, alloc_flags))
    					goto try_this_zone;
    
    				/*
    				 * Failed to reclaim enough to meet watermark.
    				 * Only mark the zone full if checking the min
    				 * watermark or if we failed to reclaim just
    				 * 1<<order pages or else the page allocator
    				 * fastpath will prematurely mark zones full
    				 * when the watermark is between the low and
    				 * min watermarks.
    				 */
    				if (((alloc_flags & ALLOC_WMARK_MASK) == ALLOC_WMARK_MIN) ||
    				    ret == ZONE_RECLAIM_SOME)
    					goto this_zone_full;
    
    				continue;
    			}
    		}
    
    try_this_zone:
    		page = buffered_rmqueue(ac->preferred_zone, zone, order,
    						gfp_mask, ac->migratetype);
    		if (page) {
    			if (prep_new_page(page, order, gfp_mask, alloc_flags))
    				goto try_this_zone;
    			return page;
    		}
    ...
    

    zone資料結構中有一個成員watermark記錄各種水位的情況,系統定義了3種水位,分別是WMARK_MINWMARK_LOWWMARK_HIGH,watermark水位的計算在__setup_per_zone_wmarks()函式中,

    [mm/page_alloc.c]
    static void __setup_per_zone_wmarks(void)
    {
    	unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10);
    	unsigned long lowmem_pages = 0;
    	struct zone *zone;
    	unsigned long flags;
    
    	/* Calculate total number of !ZONE_HIGHMEM pages */
    	for_each_zone(zone) {
    		if (!is_highmem(zone))
    			lowmem_pages += zone->managed_pages;
    	}
    
    	for_each_zone(zone) {
    		u64 tmp;
    
    		spin_lock_irqsave(&zone->lock, flags);
    		tmp = (u64)pages_min * zone->managed_pages;
    		do_div(tmp, lowmem_pages);
    		if (is_highmem(zone)) {
    			/*
    			 * __GFP_HIGH and PF_MEMALLOC allocations usually don't
    			 * need highmem pages, so cap pages_min to a small
    			 * value here.
    			 *
    			 * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN)
    			 * deltas controls asynch page reclaim, and so should
    			 * not be capped for highmem.
    			 */
    			unsigned long min_pages;
    
    			min_pages = zone->managed_pages / 1024;
    			min_pages = clamp(min_pages, SWAP_CLUSTER_MAX, 128UL);
    			zone->watermark[WMARK_MIN] = min_pages;
    		} else {
    			/*
    			 * If it's a lowmem zone, reserve a number of pages
    			 * proportionate to the zone's size.
    			 */
    			zone->watermark[WMARK_MIN] = tmp;
    		}
    
    		zone->watermark[WMARK_LOW]  = min_wmark_pages(zone) + (tmp >> 2);
    		zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1);
    
    		__mod_zone_page_state(zone, NR_ALLOC_BATCH,
    			high_wmark_pages(zone) - low_wmark_pages(zone) -
    			atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]));
    
    		setup_zone_migrate_reserve(zone);
    		spin_unlock_irqrestore(&zone->lock, flags);
    	}
    
    	/* update totalreserve_pages */
    	calculate_totalreserve_pages();
    }
    

    計算watermark水位用到min_free_kbytes這個值,它是在系統啟動時通過系統空閑頁面的數量計算的,具體計算在init_per_zone_wmark_min()這個函式中,另外系統起來之后也可以通過sysfs來設定,節點在/proc/sys/vm/min_free_kbytes,計算watermark水位的公式不算復雜,最后結果保存在每個zone的watermark陣列中,后續伙伴系統和kswapd內核執行緒中用到;

    回到get_page_from_freelist()函式,這里會讀取WMARK_LOW水位的值到變數mark中,這里zone_watermark_ok()函式判斷當前zone的空閑頁面是否滿足WMARK_LOW水位,

    [get_page_from_freelist->zone_watermark_ok->__zone_watermark_ok]
    
    /*
     * Return true if free pages are above 'mark'. This takes into account the order
     * of the allocation.
     */
    static bool __zone_watermark_ok(struct zone *z, unsigned int order,
    			unsigned long mark, int classzone_idx, int alloc_flags,
    			long free_pages)
    {
    	/* free_pages may go negative - that's OK */
    	long min = mark;
    	int o;
    	long free_cma = 0;
    
    	free_pages -= (1 << order) - 1;
    	if (alloc_flags & ALLOC_HIGH)
    		min -= min / 2;
    	if (alloc_flags & ALLOC_HARDER)
    		min -= min / 4;
    #ifdef CONFIG_CMA
    	/* If allocation can't use CMA areas don't use free CMA pages */
    	if (!(alloc_flags & ALLOC_CMA))
    		free_cma = zone_page_state(z, NR_FREE_CMA_PAGES);
    #endif
    
    	if (free_pages - free_cma <= min + z->lowmem_reserve[classzone_idx])
    		return false;
    	for (o = 0; o < order; o++) {
    		/* At the next order, this order's pages become unavailable */
    		free_pages -= z->free_area[o].nr_free << o;
    
    		/* Require fewer higher order pages to be free */
    		min >>= 1;
    
    		if (free_pages <= min)
    			return false;
    	}
    	return true;
    }
    

    引數z表示要判斷的zone,order是要分配的記憶體的階數,mark是要檢查的水位,通常分配物理記憶體頁面的內核路徑是檢查WMARK_LOW水位,而頁面回收kswapd內核執行緒則是檢查WMARK_HIGH水位,這會導致一個記憶體節點各個zone的頁面老化速度不一致的問題,為了解決這個問題,內核提出了許多的詭異的補丁,這個問題可以參見之后的內容,

    __zone_watermark_ok()函式首先判斷zone的空閑頁面是否小于某個水位值和zone的最低保留值(lowmem_reserve)之和,回傳true表示空閑頁面在某個水位在上,否則回傳false;

    回到get_page_from_freelist()函式中,當判斷當前zone的空閑頁面低于WMARK_LOW水位,會呼叫zone_reclaim()函式來回收頁面,我們這里假設zone_watermark_ok()判斷空閑頁面充沛,接下來就會呼叫buffered_rmqueue()函式從伙伴系統中分配物理頁面,

    [__alloc_pages_nodemask()->get_page_from_freelist()->buffered_rmqueue()]
    /*
     * Allocate a page from the given zone. Use pcplists for order-0 allocations.
     */
    static inline
    struct page *buffered_rmqueue(struct zone *preferred_zone,
    			struct zone *zone, unsigned int order,
    			gfp_t gfp_flags, int migratetype)
    {
    	unsigned long flags;
    	struct page *page;
    	bool cold = ((gfp_flags & __GFP_COLD) != 0);
    
    	if (likely(order == 0)) {
    		struct per_cpu_pages *pcp;
    		struct list_head *list;
    
    		local_irq_save(flags);
    		pcp = &this_cpu_ptr(zone->pageset)->pcp;
    		list = &pcp->lists[migratetype];
    		if (list_empty(list)) {
    			pcp->count += rmqueue_bulk(zone, 0,
    					pcp->batch, list,
    					migratetype, cold);
    			if (unlikely(list_empty(list)))
    				goto failed;
    		}
    
    		if (cold)
    			page = list_entry(list->prev, struct page, lru);
    		else
    			page = list_entry(list->next, struct page, lru);
    
    		list_del(&page->lru);
    		pcp->count--;
    	} else {
    		if (unlikely(gfp_flags & __GFP_NOFAIL)) {
    			/*
    			 * __GFP_NOFAIL is not to be used in new code.
    			 *
    			 * All __GFP_NOFAIL callers should be fixed so that they
    			 * properly detect and handle allocation failures.
    			 *
    			 * We most definitely don't want callers attempting to
    			 * allocate greater than order-1 page units with
    			 * __GFP_NOFAIL.
    			 */
    			WARN_ON_ONCE(order > 1);
    		}
    		spin_lock_irqsave(&zone->lock, flags);
    		page = __rmqueue(zone, order, migratetype);
    		spin_unlock(&zone->lock);
    		if (!page)
    			goto failed;
    		__mod_zone_freepage_state(zone, -(1 << order),
    					  get_freepage_migratetype(page));
    	}
    
    	__mod_zone_page_state(zone, NR_ALLOC_BATCH, -(1 << order));
    	if (atomic_long_read(&zone->vm_stat[NR_ALLOC_BATCH]) <= 0 &&
    	    !test_bit(ZONE_FAIR_DEPLETED, &zone->flags))
    		set_bit(ZONE_FAIR_DEPLETED, &zone->flags);
    
    	__count_zone_vm_events(PGALLOC, zone, 1 << order);
    	zone_statistics(preferred_zone, zone, gfp_flags);
    	local_irq_restore(flags);
    
    	VM_BUG_ON_PAGE(bad_range(zone, page), page);
    	return page;
    
    failed:
    	local_irq_restore(flags);
    	return NULL;
    }
    

    這里根據order數值兵分兩路:一路是order等于0 的情況,也就是分配一個物理頁面時,從zone->per_cpu_pageset串列中分配;另一路order大于0的情況,就從伙伴系統中分配,我們只關注order大于0 的情況,它最侄訓呼叫到__rmqueue_smallest()函式,

    [get_page_from_freelist()->buffered_rmqueue()->buffered_rmqueue->__rmqueue()->__rmqueue_smallest()]
    
    /*
     * Go through the free lists for the given migratetype and remove
     * the smallest available page from the freelists
     */
    static inline
    struct page *__rmqueue_smallest(struct zone *zone, unsigned int order,
    						int migratetype)
    {
    	unsigned int current_order;
    	struct free_area *area;
    	struct page *page;
    
    	/* Find a page of the appropriate size in the preferred list */
    	for (current_order = order; current_order < MAX_ORDER; ++current_order) {
    		area = &(zone->free_area[current_order]);
    		if (list_empty(&area->free_list[migratetype]))
    			continue;
    
    		page = list_entry(area->free_list[migratetype].next,
    							struct page, lru);
    		list_del(&page->lru);
    		rmv_page_order(page);
    		area->nr_free--;
    		expand(zone, page, order, current_order, area, migratetype);
    		set_freepage_migratetype(page, migratetype);
    		return page;
    	}
    
    	return NULL;
    }
    

    在__rmqueue_smallest()函式中,首先從order開始查找zone中的空閑鏈表,如果zone的當前order對應的空閑區free_area中相應的migratetype型別的鏈表里沒有空閑鏈表,那么就會查找下一級order

    為什么會這樣?因為在系統啟動時,空閑頁面會盡可能分配到MAX_ORDER-1的鏈表中,這個可以在系統剛起來之后,通過'cat /proc/pagetypeinfo'命令可以看出端倪,當找到某個order的空閑區中對應的mirgratetype型別的空閑鏈表中有空閑記憶體塊時,就會從一個記憶體塊摘下來,然后摘用expand()函式來切“蛋糕”,因為通常摘下來的記憶體塊會比需要的記憶體大,切完之后需要把剩下來的記憶體塊重新放回伙伴系統中,

    expand()函式就是實作“切蛋糕”的功能,這里的引數high就是current_order,通常是current_order要比需求的order要大,每比較一次,area減一,相當于退了一級order,最后通過list_add把剩下的記憶體塊添加到低一級的空閑鏈表中,

    [get_page_from_freelist()->buffered_rmqueue()->buffered_rmqueue->__rmqueue()->__rmqueue_smallest()->expand()]
    /*
     * The order of subdivision here is critical for the IO subsystem.
     * Please do not alter this order without good reasons and regression
     * testing. Specifically, as large blocks of memory are subdivided,
     * the order in which smaller blocks are delivered depends on the order
     * they're subdivided in this function. This is the primary factor
     * influencing the order in which pages are delivered to the IO
     * subsystem according to empirical testing, and this is also justified
     * by considering the behavior of a buddy system containing a single
     * large block of memory acted on by a series of small allocations.
     * This behavior is a critical factor in sglist merging's success.
     *
     * -- nyc
     */
    static inline void expand(struct zone *zone, struct page *page,
    	int low, int high, struct free_area *area,
    	int migratetype)
    {
    	unsigned long size = 1 << high;
    
    	while (high > low) {
    		area--;
    		high--;
    		size >>= 1;
    		VM_BUG_ON_PAGE(bad_range(zone, &page[size]), &page[size]);
    
    		if (IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
    			debug_guardpage_enabled() &&
    			high < debug_guardpage_minorder()) {
    			/*
    			 * Mark as guard pages (or page), that will allow to
    			 * merge back to allocator when buddy will be freed.
    			 * Corresponding page table entries will not be touched,
    			 * pages will stay not present in virtual address space
    			 */
    			set_page_guard(zone, &page[size], high, migratetype);
    			continue;
    		}
    		list_add(&page[size].lru, &area->free_list[migratetype]);
    		area->nr_free++;
    		set_page_order(&page[size], high);
    	}
    }
    

    所需要的頁面分配成功之后,__rmqueue()函式回傳到這個記憶體塊的起始頁面struct page資料結構,回到buffered_rmqueue()函式,最后還需要利用zone_statistics()函式做一些統計資料的計算,

    回到get_page_from_freelist()函式,最后還要通過prep_new_page()函式做一些有趣的檢查,才能最終出廠,

    [__alloc_page_nodemask()->get_page_from_freelist()->prep_new_page()->check_new_page()]
    /*
     * This page is about to be returned from the page allocator
     */
    static inline int check_new_page(struct page *page)
    {
    	const char *bad_reason = NULL;
    	unsigned long bad_flags = 0;
    
    	if (unlikely(page_mapcount(page)))
    		bad_reason = "nonzero mapcount";
    	if (unlikely(page->mapping != NULL))
    		bad_reason = "non-NULL mapping";
    	if (unlikely(atomic_read(&page->_count) != 0))
    		bad_reason = "nonzero _count";
    	if (unlikely(page->flags & PAGE_FLAGS_CHECK_AT_PREP)) {
    		bad_reason = "PAGE_FLAGS_CHECK_AT_PREP flag set";
    		bad_flags = PAGE_FLAGS_CHECK_AT_PREP;
    	}
    #ifdef CONFIG_MEMCG
    	if (unlikely(page->mem_cgroup))
    		bad_reason = "page still charged to cgroup";
    #endif
    	if (unlikely(bad_reason)) {
    		bad_page(page, bad_reason, bad_flags);
    		return 1;
    	}
    	return 0;
    }
    

    check_new_page()函式主要做如下的檢查:

    • 剛分配的頁面struct page的_macpcount計數應該為0,
    • 這是page->mapping為NULL,
    • 判斷這是page的_count是否為0,注意alloc_page()分配的 _count為1,但這里為0,因為這個函式之后還呼叫set_page_refcounted()->set_page_count(),把 _count設定為1;
    • 檢查PAGE_FLAGS_CHECK_AT_PREP標志位,這個flag在free_page時已經清除了,而這時該flag被設定,說明分配程序中有問題,

    上述檢查都通過后,我們分配的頁面就合格了,可以出廠了,頁面page便開啟了屬于它的精彩生命周期,

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/3573.html

標籤:嵌入式

上一篇:手寫一個簡易的多周期 MIPS CPU

下一篇:《痞子衡嵌入式半月刊》 第 8 期

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more