U-Boot · source analysis

block 장치와 partition 문자열 해석

ifname과 0.1:2 같은 문자열에서 장치·hardware partition·disk partition 선택이 갈리는 지점을 읽습니다.

Series
13 / 22
Baseline
v2026.07
Commit
ece349ade297
Source
disk/part.c:431-519 (발췌 범위)

장치 번호와 disk partition 번호는 어디에서 갈라지는가?

blk_get_device_part_str(ifname, dev_part_str, &desc, &info, allow_whole_dev)는 이미 존재하는 block descriptor를 선택하고 partition 정보를 호출자가 준 info에 채운다. 파일시스템이나 loader를 호출하지 않는다.

예를 들어 ifname="mmc"와 dev_part_str="0.1:2"는 장치 0의 hardware partition 1을 먼저 선택하고, 그 주소 공간의 disk partition 2를 찾는다. :0은 caller가 whole device를 허용할 때만 의미가 있다.

입력 문자열의 서로 다른 두 구분자

그림 1. mmc와 0.1:2는 한 번에 partition table로 가지 않는다
inputifname = mmcdev_part_str = 0.1:2
allow_whole_dev는 caller의 정책
device selector0.1 → blk_get_device_by_str장치 0, MMC hardware partition 1. BLK 활성·MMC 조건에서 part_init.
disk selector:2 → part_get_info선택된 descriptor의 partition driver에서 2번 entry를 읽어 info에 복사.
.는 hardware partition, :는 disk partition 경계다. name/UUID 탐색 함수는 아래의 별도 API다.

근거: 장치·hwpart L394–450, disk partition 구분 L516–554.

장치 lookup 뒤 세 가지 결과 경로

그림 2. whole disk, 번호 지정, auto 탐색은 서로 다른 선택
after optional bootdevice fallbackblk_get_device_by_str() → *desc빈 문자열·- fallback은 ENV_SUPPORT 조건부. hostfs/ubi는 별도 조기 반환.
whole disk
table 불명 또는 :0유효 LBA와 allow_whole_dev 확인
part_get_info_whole_diskret = 0
번호 선택
:N 또는 미지정table이 알려졌고 미지정이면 N=1
part_get_info(desc,N,info)type 검사 후 ret = N
auto 선택
:auto첫 bootable을 찾고, 없으면 첫 유효 entry
선택된 Ntype 검사 후 ret = N

각 분기에서 실패하면 음수 오류로 돌아온다. auto는 partition name이나 UUID 탐색이 아니다. 근거: disk/part.c L536–664.

입력·출력 포인터와 반환 코드

경계입력출력/반환제약
초기화ifname, dev_part_str*desc=NULL, *info 0 초기화아직 장치가 선택되지 않음
조건부 특례hostfs 또는 ubiinfo의 type/name, 반환 0regular block descriptor 경로를 건너뜀
device/hwpart0.1 같은 앞부분기존 blk_desc *를 *desc에MMC는 선택한 hwpart에서 part_init
whole disktable 불명 또는 :0info.start=0, size=desc->lba, 반환 0device LBA > 0, caller의 whole-dev 허용
partition번호/미지정/autopart_get_info 결과와 양수 partition ID선택 뒤 BOOT_PART_TYPE 검사
오류파싱·lookup·type 실패음수 반환, dup_str free*desc는 이미 선택됐을 수도 있음

원본 코드

아래 코드는 U-Boot v2026.07의 disk/part.c에서 431-519줄을 그대로 가져온 것이다.

commitece349ade2973e220f524ce59e59711cc919263fanchor · L455int blk_get_device_part_str(const char *ifname
431	*desc = get_dev_hwpart(ifname, dev, hwpart);
432	if (!(*desc) || ((*desc)->type == DEV_TYPE_UNKNOWN)) {
433		debug("** Bad device %s %s **\n", ifname, dev_hwpart_str);
434		dev = -ENODEV;
435		goto cleanup;
436	}
437
438	if (blk_enabled()) {
439		/*
440		 * Updates the partition table for the specified hw partition.
441		 * Always should be done, otherwise hw partition 0 will return
442		 * stale data after displaying a non-zero hw partition.
443		 */
444		if ((*desc)->uclass_id == UCLASS_MMC)
445			part_init(*desc);
446	}
447
448cleanup:
449	free(dup_str);
450	return dev;
451}
452
453#define PART_UNSPECIFIED -2
454#define PART_AUTO -1
455int blk_get_device_part_str(const char *ifname, const char *dev_part_str,
456			     struct blk_desc **desc,
457			     struct disk_partition *info, int allow_whole_dev)
458{
459	int ret;
460	const char *part_str;
461	char *dup_str = NULL;
462	const char *dev_str;
463	int dev;
464	char *ep;
465	int p;
466	int part;
467	struct disk_partition tmpinfo;
468
469	*desc = NULL;
470	memset(info, 0, sizeof(*info));
471
472#if IS_ENABLED(CONFIG_SANDBOX) || IS_ENABLED(CONFIG_SEMIHOSTING)
473	/*
474	 * Special-case a pseudo block device "hostfs", to allow access to the
475	 * host's own filesystem.
476	 */
477	if (!strcmp(ifname, "hostfs")) {
478		strcpy((char *)info->type, BOOT_PART_TYPE);
479		strcpy((char *)info->name, "Host filesystem");
480
481		return 0;
482	}
483#endif
484
485#if IS_ENABLED(CONFIG_CMD_UBIFS) && !IS_ENABLED(CONFIG_XPL_BUILD)
486	/*
487	 * Special-case ubi, ubi goes through a mtd, rather than through
488	 * a regular block device.
489	 */
490	if (!strcmp(ifname, "ubi")) {
491		if (!ubifs_is_mounted()) {
492			printf("UBIFS not mounted, use ubifsmount to mount volume first!\n");
493			return -EINVAL;
494		}
495
496		strcpy((char *)info->type, BOOT_PART_TYPE);
497		strcpy((char *)info->name, "UBI");
498		return 0;
499	}
500#endif
501
502	/* If no dev_part_str, use bootdevice environment variable */
503	if (CONFIG_IS_ENABLED(ENV_SUPPORT)) {
504		if (!dev_part_str || !strlen(dev_part_str) ||
505		    !strcmp(dev_part_str, "-"))
506			dev_part_str = env_get("bootdevice");
507	}
508
509	/* If still no dev_part_str, it's an error */
510	if (!dev_part_str) {
511		printf("** No device specified **\n");
512		ret = -ENODEV;
513		goto cleanup;
514	}
515
516	/* Separate device and partition ID specification */
517	part_str = strchr(dev_part_str, ':');
518	if (part_str) {
519		dup_str = strdup(dev_part_str);
함수의 나머지 연속 원문 L520–664 보기: lookup·whole disk·auto·type 검사·반환

위 원본 89행은 strdup() 직후 끝납니다. 아래는 같은 고정 commit의 바로 다음 줄부터 함수 종료까지입니다.

520		dup_str[part_str - dev_part_str] = 0;
521		dev_str = dup_str;
522		part_str++;
523	} else {
524		dev_str = dev_part_str;
525	}
526
527	/* Look up the device */
528	dev = blk_get_device_by_str(ifname, dev_str, desc);
529	if (dev < 0) {
530		printf("** Bad device specification %s %s **\n",
531		       ifname, dev_str);
532		ret = dev;
533		goto cleanup;
534	}
535
536	/* Convert partition ID string to number */
537	if (!part_str || !*part_str) {
538		part = PART_UNSPECIFIED;
539	} else if (!strcmp(part_str, "auto")) {
540		part = PART_AUTO;
541	} else {
542		/* Something specified -> use exactly that */
543		part = (int)hextoul(part_str, &ep);
544		/*
545		 * Less than whole string converted,
546		 * or request for whole device, but caller requires partition.
547		 */
548		if (*ep || (part == 0 && !allow_whole_dev)) {
549			printf("** Bad partition specification %s %s **\n",
550			    ifname, dev_part_str);
551			ret = -ENOENT;
552			goto cleanup;
553		}
554	}
555
556	/*
557	 * No partition table on device,
558	 * or user requested partition 0 (entire device).
559	 */
560	if (((*desc)->part_type == PART_TYPE_UNKNOWN) || !part) {
561		if (!(*desc)->lba) {
562			printf("** Bad device size - %s %s **\n", ifname,
563			       dev_str);
564			ret = -EINVAL;
565			goto cleanup;
566		}
567
568		/*
569		 * If user specified a partition ID other than 0,
570		 * or the calling command only accepts partitions,
571		 * it's an error.
572		 */
573		if ((part > 0) || (!allow_whole_dev)) {
574			printf("** No partition table - %s %s **\n", ifname,
575			       dev_str);
576			ret = -EPROTONOSUPPORT;
577			goto cleanup;
578		}
579
580		(*desc)->log2blksz = LOG2((*desc)->blksz);
581
582		part_get_info_whole_disk(*desc, info);
583
584		ret = 0;
585		goto cleanup;
586	}
587
588	/*
589	 * Now there's known to be a partition table,
590	 * not specifying a partition means to pick partition 1.
591	 */
592	if (part == PART_UNSPECIFIED)
593		part = 1;
594
595	/*
596	 * If user didn't specify a partition number, or did specify something
597	 * other than "auto", use that partition number directly.
598	 */
599	if (part != PART_AUTO) {
600		ret = part_get_info(*desc, part, info);
601		if (ret) {
602			printf("** Invalid partition %d **\n", part);
603			goto cleanup;
604		}
605	} else {
606		/*
607		 * Find the first bootable partition.
608		 * If none are bootable, fall back to the first valid partition.
609		 */
610		part = 0;
611		for (p = 1; p <= MAX_SEARCH_PARTITIONS; p++) {
612			ret = part_get_info(*desc, p, info);
613			if (ret)
614				continue;
615
616			/*
617			 * First valid partition, or new better partition?
618			 * If so, save partition ID.
619			 */
620			if (!part || info->bootable)
621				part = p;
622
623			/* Best possible partition? Stop searching. */
624			if (info->bootable)
625				break;
626
627			/*
628			 * We now need to search further for best possible.
629			 * If we what we just queried was the best so far,
630			 * save the info since we over-write it next loop.
631			 */
632			if (part == p)
633				tmpinfo = *info;
634		}
635		/* If we found any acceptable partition */
636		if (part) {
637			/*
638			 * If we searched all possible partition IDs,
639			 * return the first valid partition we found.
640			 */
641			if (p == MAX_SEARCH_PARTITIONS + 1)
642				*info = tmpinfo;
643		} else {
644			printf("** No valid partitions found **\n");
645			goto cleanup;
646		}
647	}
648	if (strncmp((char *)info->type, BOOT_PART_TYPE, sizeof(info->type)) != 0) {
649		printf("** Invalid partition type \"%.32s\""
650			" (expect \"" BOOT_PART_TYPE "\")\n",
651			info->type);
652		ret  = -EINVAL;
653		goto cleanup;
654	}
655
656	(*desc)->log2blksz = LOG2((*desc)->blksz);
657
658	ret = part;
659	goto cleanup;
660
661cleanup:
662	free(dup_str);
663	return ret;
664}

발췌 경계와 함수 전체 읽기

기존 L431–519의 89행은 고정 원문과 줄별로 일치하므로 그대로 유지했다. L431–451은 앞 함수 blk_get_device_by_str()의 끝이고, L455에서 blk_get_device_part_str()이 시작한다. L519는 문자열 복제 직후라 장치 lookup이나 partition 결과가 아직 없다.

추가로 접힌 L520–664는 이 함수의 연속 나머지다. 장치 lookup L527–534, 분기 L536–647, BOOT_PART_TYPE 검사 L648–654, 반환·dup_str 해제 L656–664를 읽는다. name/UUID 탐색은 L666 이후의 별도 함수다.

파서의 네 단계

01

입력 기본값과 조기 반환

ENV_SUPPORT에서 dev_part_str이 없거나 비었거나 -이면 bootdevice를 읽는다. hostfs와 ubi는 구성 조건부 특례로 block 장치 lookup 전에 돌아간다.

02

장치와 hardware partition

: 앞 문자열을 blk_get_device_by_str()로 넘긴다. 그 함수는 .을 따로 나누어 hardware partition을 선택하고, BLK 활성·MMC 조건에서 part_init()으로 해당 공간의 table 상태를 갱신한다.

03

disk partition 번호

뒤 문자열이 없으면 PART_UNSPECIFIED, auto면 PART_AUTO, 그 밖에는 숫자로 해석한다. 알려진 table에서 미지정이면 1번을 택하고, :0은 whole device 허용 정책을 검사한다.

04

info와 반환값

whole disk는 part_get_info_whole_disk(), 선택 partition은 part_get_info()와 type 검사를 거친다. 반환값 0·양수·음수는 각각 특례/whole, partition ID, 오류를 뜻한다.

숫자와 부수 효과: device, hardware partition, disk partition은 여기서 모두 hextoul()로 읽는다. 예를 들어 :10은 10진수 10이 아니라 16진수 0x10이다. 문자열 파서 자체가 descriptor를 할당하지는 않지만 하위 lookup은 device_probe()와 hardware-partition 선택을 실행할 수 있다. 따라서 전체 호출을 상태 변화 없는 문자열 분석으로 취급하지 않는다.

auto는 1..MAX_SEARCH_PARTITIONS 범위에서만 검사한다. *info가 처음 0이었다고 실패 뒤에도 반드시 0인 것은 아니며, 하위 driver가 일부 필드를 썼을 수 있다. 이 고정 코드의 두 strdup() 호출은 NULL 검사를 하지 않으므로, 메모리 부족까지 모두 정돈된 음수 오류로 반환한다고 일반화할 수도 없다. 성공한 반환값 없이 출력 포인터·필드를 사용하지 않는다.

숫자 0과 auto를 같은 기본값으로 보지 않는다

그림 3. 반환값이 나타내는 선택 대상
0whole device 또는 특례whole disk는 start=0, size=lba. hostfs/ubi는 별도 pseudo path.
positivedisk partition ID명시 번호, 미지정 기본 1, 또는 auto 검색 결과.
negative파싱·lookup·검증 실패실패 위치에 따라 *desc는 NULL 또는 선택된 상태일 수 있다.

part_get_info_by_name()·part_get_info_by_uuid()는 이 기본 문자열 파서의 숨은 fallback이 아니라 L666 이후의 별도 API다.

01

알 수 없는 table과 whole disk

part_type == PART_TYPE_UNKNOWN이거나 part==0이면 device LBA와 allow_whole_dev를 검사한다. 명시 양수 partition을 요구했거나 caller가 whole을 금지하면 오류다.

02

auto의 선택 순서

L611–647은 1번부터 검사해 첫 bootable partition을 우선하고, 없으면 처음 찾은 유효 partition을 보존한다. name 또는 UUID 기준 검색은 하지 않는다.

03

partition driver가 채우는 정보

part_get_info()는 descriptor의 partition type에 맞는 driver를 거쳐 info를 채운다. GPT backup header 사용 여부나 CRC 복구 정책은 이 호출 한 줄만으로 단정할 수 없다.

이 함수가 소유하는 것과 빌려 쓰는 것

대상생성/갱신이 함수의 책임
*desc처음 NULL; blk_get_device_by_str()가 기존 descriptor를 선택descriptor 자체를 생성하거나 해제하지 않는다.
*info처음 0; whole helper 또는 partition driver가 채움caller가 준 저장 공간에 결과를 쓴다.
dup_str: 분리를 위한 strdup공통 cleanup에서 free한다.
tmpinfoauto에서 첫 유효 partition의 임시 복사bootable을 못 찾고 끝까지 스캔하면 결과를 복원한다.

오류가 나는 분기와 남는 결과

그림 4. 실패 위치에 따라 descriptor 상태가 다를 수 있다
before lookup입력 누락·특례 오류*desc는 초기 NULL. info는 특례가 채우기 전이면 0.
device lookupbad dev/hwparthelper의 음수 오류를 반환하고 파싱 복제문자열을 해제.
after lookuppart/type 오류*desc가 선택됐어도 호출 전체는 실패. 반환 코드 먼저 확인.
조건고정 소스의 결과근거
device 문자열·lookup 실패blk_get_device_by_str() 오류가 전파됨L527–534
:0인데 whole 금지-ENOENTL536–553
table 없는데 양수 part 요구-EPROTONOSUPPORTL560–577
선택한 partition 조회 실패part_get_info()의 오류로 종료L599–604
partition type 불일치-EINVALL648–654

고정 소스와 보드에서 확인할 증거

보드 명령의 제공 여부와 숫자 해석은 U-Boot 구성에 따른다. 아래 명령은 예시이며 실행 결과를 가정하지 않는다. nm은 C 선언문이 아니라 심볼 이름을 표시한다.

목적명령 또는 원문판정
심볼 포함 여부${CROSS_COMPILE}nm -n u-boot | grep -E ' (T|t) blk_get_device_part_str$'현재 이미지에 함수가 포함됐는지 확인.
환경 fallbackprintenv bootdevice입력 생략·-와 ENV_SUPPORT 경계를 비교.
partition 목록part list mmc 0선택 장치의 table/entry를 확인. 명령 지원은 빌드별.
device/hwpartmmc list, mmc dev 0명령 자체가 장치 상태를 바꿀 수 있어 전후를 기록.
원본disk/part.c L394–664문자열·whole·auto·type·cleanup 분기 대조.

문자열 해석을 분리해 확인하기

  1. 01
    device/hwpart와 disk partition 구분

    검증용 보드에서 0.1:2의 *desc->hwpart와 선택된 info.start/size를 각각 기록한다. 다른 hardware partition이면 같은 번호의 disk entry도 다른 공간에서 해석된다.

  2. 02
    whole 허용 정책

    caller의 allow_whole_dev가 0/1일 때 :0, table 불명 장치, 명시 양수 partition의 반환 코드와 *desc 상태를 비교한다.

  3. 03
    auto 선택

    테스트용 table에서 첫 유효 entry와 bootable entry가 다를 때 선택 ID를 확인한다. partition name/UUID 함수의 결과와 혼동하지 않는다.

원문과 다음 글