O conteúdo informativo dos índices de opções.
Um amplo fluxo de pesquisa mostra que a informação flui para os preços das ações subjacentes através do mercado de opções. Por exemplo, pesquisas anteriores mostram que tanto a relação Put-Call (P / C) quanto a razão entre volume de opções e ações (O / S) preveem retornos de ações futuros negativos. Neste artigo, comparamos o nível de informação contido nessas duas taxas de volume de opções comumente usadas. Primeiro, descobrimos que os índices P / C contêm mais previsibilidade sobre os retornos futuros das ações no nível diário do que os índices O / S. Em segundo lugar, em contraste com nosso primeiro conjunto de resultados, os índices O / S contêm mais previsibilidade sobre retornos futuros nos níveis semanal e mensal do que os índices P / C. De fato, nossos testes mostram que enquanto os índices P / C contêm previsibilidade sobre retornos diários futuros e, até certo ponto, retornos semanais futuros, a previsibilidade de retorno em razões P / C é passageira. Os índices O / S, por outro lado, predizem significativamente os retornos negativos em todos os níveis: diário, semanal e mensal. Enquanto Pan e Poteshman (2006) mostram que os índices P / C assinados, que requerem dados proprietários, têm poder preditivo, descobrimos que relações P / C não assinadas, que não requerem dados proprietários, também têm poder preditivo.
Classificação JEL.
Escolha uma opção para localizar / acessar este artigo:
Verifique se você tem acesso através de suas credenciais de login ou de sua instituição.
Um treeview de MSForms (todo o VBA); Características.
Atuação.
Realisticamente, um formulário VBA com todos os controles que precisamos para cada nó não pode corresponder ao do original compilado. Mesmo assim, ficamos surpresos com o que foi possível, embora com considerável ajuste e refinamento. O teste de luz sugere que 1000 a 2000 nós são bastante viáveis, mesmo em um laptop típico de cinco anos, dependendo da configuração do treeview.
O original tem uma ampla variedade de recursos e funcionalidades. Tentamos replicar a maioria deles e adicionamos alguns recursos próprios.
Caixas de seleção.
O controle comum treeview tem uma opção de caixas de seleção para que você possa verificar os nós. Nós garantimos que nosso treeview também tem isso.
Uma foto diz mais que mil palavras, então:
Caixas de seleção são possíveis e funcionam!
Expandir / recolher caixas ou ícones.
Por padrão, desenhamos um retângulo com mais ou menos caracteres como texto para imitar as caixas de expansão / recolhimento. Você também pode optar por expandir / recolher ícones. Nós incluímos os ícones de expansores estilo XP e Win7 no formulário de demonstração ou você pode personalizar o seu como desejar:
Ícones como botões de expansão / recolhimento.
O treeview da lib de controles comuns sempre mostra linhas para indicar a estrutura. Com o nosso, é opcional mostrar linhas. A escolha pode ser por razões estéticas, no entanto, um treeview muito grande carregará significativamente mais rápido sem linhas, o que pode ser uma consideração primordial.
Escolha se deseja ou não mostrar linhas.
Mais uma vez, vamos apenas olhar para a foto!
Você pode adicionar ícones também!
Se você estiver familiarizado com o controle ImageList, incorporamos uma abordagem semelhante. Você pode armazenar suas imagens em um quadro (oculto) e passar uma referência ao quadro, da mesma forma que você passaria uma referência a um ImageList para o treeview de controles comuns. No entanto, suas imagens de ícone podem ser armazenadas em qualquer lugar. Contanto que você possa recuperar um & # 8220; StdPicture & # 8221; manipule cada ícone e adicione-o a uma coleção & # 8220; & # 8221; isso é tudo que precisamos.
Formatação de etiquetas.
A formatação de etiquetas está disponível para você com código tão simples quanto:
cNode. BackColor = RGB (255, 255, 220) 'amarelo pálido.
cNode. ForeColor = RGB (180, 0, 0) 'vermelho escuro.
Certifique-se de não usar código como:
Quando você está construindo o conjunto de nós, os controles da treeview ainda não foram criados (isso é feito quando. Refresh é chamado). Usando as propriedades expostas pela própria classe do nó, elas são aplicadas quando os nós são criados. Somente quando a treeview for totalmente inicializada e atualizada, você poderá acessar as propriedades do cNode. Control.
Além disso, o treeview selecionará automaticamente as configurações de fonte padrão de seu controle pai (frame), de modo que controlar a aparência do treeview será tão fácil quanto configurar as propriedades do quadro que você usará para hospedar o treeview. Eu explicarei isso na próxima página.
Funcionalidade
Nós já implementamos algumas funcionalidades. Aqui está o que você pode fazer "fora da caixa":
Recolhendo e expandindo.
Clicar nos botões de expansão / recolhimento faz como anunciado: expande ou recolhe a árvore.
Navegação usando mouse e teclado.
A navegação usando o mouse e o teclado funciona da mesma maneira que na pasta & quot; old & quot; treeview. A seta para a direita e a esquerda se expande ou colapsa, a seta para cima e para baixo move-se para cima ou para baixo na árvore. Page-up e down apenas trabalho.
Edição de nós
Você pode usar F2 para editar um nó. Clicar duas vezes em um nó também o coloca no modo de edição. Esta opção pode ser ativada ou desativada configurando um valor de propriedade.
Arraste e solte.
Estamos trabalhando nisso.
Copiando, movendo (cortando) e colando.
Copiar e mover funções são embutidas, você pode copiar ou mover nós únicos ou ramos inteiros. Você pode fazer isso silenciosamente, mas também facilitamos a interceptação das ações do usuário no nó selecionado, por exemplo, Ctrl-c, Ctrl-x, Ctrl-v. Você pode incluir seu próprio código para validar as ações pretendidas, por exemplo, permitir apenas a cópia entre níveis semelhantes e depois instigar a cópia ou a movimentação.
Uma rotina de ordenação eficiente foi concebida especialmente para esta treeview. Atualmente, ele opera somente em um determinado nível de nó, no entanto, opções para ordem de classificação e texto / binário são incluídas.
Propriedades
Existe um grande número de propriedades que você pode alterar. Para se ter uma ideia, alguns estão listados abaixo. Existem mais propriedades e métodos, documentados no download do Excel.
Largura completa.
True: As larguras de legenda do nó se estendem além da largura da visualização em árvore, proporcionando claro destaque do nó selecionado e se backcolor's são aplicados.
Se os ícones do nó forem usados, um controle de imagem adicional será criado para uso com 'largura total'
Uma árvore grande usando ícones de nós carregará mais rapidamente se a largura total não for aplicada.
Caixas de seleção.
Verdadeiro: mostre as caixas de seleção.
Pressione a tecla de espaço ou clique para alterar o valor.
O evento de alteração de verificação é preso no formulário e o rótulo de informações é atualizado.
Permitir edição.
O usuário pode editar manualmente o nó.
Clique duas vezes ou pressione F2 em um nó selecionado.
Digite a tecla para aplicar a edição ou Esc para abortar.
Mostrar linhas.
Mostrar ou não linhas pode ser uma questão de estética ou necessidades dependendo da árvore.
Tente experimentar com diferentes larguras de indentação (veja o botão de rotação).
Em uma árvore grande, o tempo de inicialização será consideravelmente mais rápido se as linhas não forem exibidas.
Botão de raiz.
Verdadeiro: a árvore inteira pode ser recolhida para a raiz.
Falso: a árvore só pode ser recolhida para o primeiro nível.
Ícones de expansor.
Os botões do expansor podem ser Etiquetas com +/- caracteres alternados ou pares de ícones.
Se os ícones forem usados, as imagens devem estar disponíveis na pasta de trabalho, em uma folha ou como na demo oculta no formulário.
A demonstração inclui pseudo WinXP e Win7 Explorer tipo expansor ícones, mas você pode usar qualquer ícone de sua escolha, ou nenhum ícone.
Recuo
O padrão é 15 pontos.
NodeHeight.
O treeview já ajusta automaticamente sua altura do Node para o tamanho da fonte ou tamanho da caixa de seleção ou tamanho do ícone, o que for maior.
Provavelmente é melhor não ajustar a altura do Nó.
O tamanho da fonte e outras propriedades de rótulo padrão são adotadas do quadro pai.
Alterar apenas no tempo de design.
Nós.
ActivateNode.
NodesClear.
NodeRemove.
SetTreeExpansionLevel.
TerminateTree.
ScrollToView.
Atualmente disponibilizamos um conjunto limitado de eventos:
Clique em evento.
Dispara quando você clica em qualquer nó.
Evento de verificação de nó.
Dispara quando você clica na caixa de seleção de um nó.
Após o evento de edição de rótulo.
Incêndios após editar um rótulo.
Evento de chave para baixo.
Dispara quando você pressiona uma tecla. O demoform incluído no projeto de amostra mostra como implementar o copiar e colar.
Eventos do mouse.
Todos os eventos do mouse são enviados usando um único evento MouseEvents.
Adicione seus próprios eventos.
Não é difícil adicionar seus próprios eventos, por exemplo São necessárias três etapas para adicionar um novo evento a um elemento específico da árvore:
Adicione um evento à classe clsNode para a parte da árvore da qual você precisa de um evento, usando as listas suspensas na parte superior da janela de código. Certifique-se de que chama um amigo sub na classe clsTreeView.
Próximo: usando esta treeview em seu projeto VBA.
A mostrar os últimos 8 comentários de 47 no total (Mostrar todos os comentários):
Comentário perto: swapnil bhalerao (30-01-2014 12:14:31)
Eu estou trabalhando em modo de exibição de árvore semelhante, mas eu quero várias caixas de seleção para cada nó (pelo menos três) cada representando célula de três colunas diferentes, também se eu verifiquei 3-4 nós deve mostrar o valor de uma célula associada das colunas para o qual particular A caixa de seleção foi marcada.
Comentário por: Peter Thornton (1/31/2017 5:55:07 PM)
Seria possível adicionar várias caixas de seleção, mas muito para mostrar como aqui. Experimente e siga como os ícones e as caixas de seleção são adicionados e aumente os deslocamentos para adicionar à propriedade Left dos Nós. A manipulação de eventos na classe do nó e referenciada à classe treeview principal pode ser adicionada de maneira semelhante à caixa de seleção única existente.
Comentário por: Pablo (15/02/2017 21:49:17)
Oi, este é um componente incrível, mas estou experimentando algo realmente estranho, quando tento adicionar manipuladores de eventos a um evento de clique de nó que eu tenho o evento é gerado mesmo quando uma tecla é pressionada (por exemplo: Enter, seta para cima, etc )
Você tem alguma sugestão sobre como resolver isso?
Comentário por: Peter Thornton (16/02/2017 13:37:11)
De fato, as teclas de navegação irão indiretamente aumentar o evento click, o que significa que você pode interceptar um nó que foi ativado, seja meu mouse ou teclado. Isso "por design" e consistente com aplicativos equivalentes.
Comentário por: Pablo (17/02/2017 21:33:43)
Obrigado pela sua resposta rápida, de fato eu gostaria de usar as teclas para navegação e apenas levantar um evento de clique apenas quando pressionado "Enter", em vez de cada tecla, estou tentando usar a TV como um menu, onde você pode clique ou pressione Enter para abrir o formulário desejado. Eu tentei também capturar o evento _KeyUp, mas por algum motivo (ímpar) o código de tecla para "Enter" é o mesmo que a seta para a esquerda.
Ficaria muito grato se você pudesse apontar onde fazer as alterações mencionadas nesta linha: "permitir a navegação pelo teclado, mas não gerar nenhum evento de clique"
Comentário por: Peter Thornton (18/02/2017 11:06:05)
Oi Pablo, OK, eu acho que eu sigo.
No mesmo evento próximo ao topo, depois de "If KeyCode = vbKeyReturn" comentar o If / Else / End if e substituir por:
RaiseEvent Click (moActiveNode) 'Enter aumentará o evento de clique.
Ou, interceptar vbKeyReturn no evento mcTree_KeyDown ou KeyUp no formulário principal.
Comentário por: Ray Buckley (19/10/17 12:31:03)
Você está suportando a funcionalidade de arrastar e soltar ainda.
Comentário por: Peter Thornton (19/10/2017 5:16:41 PM)
Demonstração de Opções Binárias & # 8211; Tudo que você precisa saber.
Se você já teve alguma dúvida sobre as contas de demonstração de opções binárias, é bem provável que encontre a resposta nesse artigo enorme. Cobrimos tudo, desde uma conta demo até tipos de contas de demonstração, como usá-las para melhorar sua negociação e, claro, como obtê-las. Aperte o cinto e comece a ler, você está em uma longa jornada.
Você não pode aprender corretamente as opções binárias sem praticar. Pense em pilotos (mas isso se aplica a quase todas as profissões por aí): um piloto aprende a teoria, então pula naquele simulador virtual de vôo e só depois disso, ele consegue pilotar um avião real. Opções Binárias são as mesmas: você tem que aprender a teoria - nossa Escola cuida disso - então você tem que trocar dinheiro virtual em uma conta Demo e só então você pode negociar de verdade. No entanto, por alguns motivos estranhos, nem todos os corretores oferecem contas Demo gratuitas. Uma coisa é certa: a conta Demo não é um boato, mas está envolta em muita incerteza e hoje vamos tentar levantar o nevoeiro, dando-lhe a verdade por trás das contas Demo.
O que é uma conta de demonstração de opções binárias?
Quando se fala de contas de demonstração, a maioria das pessoas está se referindo a contas de dinheiro virtual. Contas de caixa virtuais são basicamente a negociação de ativos reais com tempos de expiração reais, mas com dinheiro "virtual" ou "demo". Em outras palavras, você não pode perder seu dinheiro real, mas pode praticar e se familiarizar com a plataforma Opções Binárias e com o processo de colocação de negociações. É muito parecido com jogar um videogame de negociação, apenas com dados reais e gráficos reais que ajudarão você a ficar um passo mais perto de negociar Opções Binárias para ganhar a vida.
Alguns corretores afirmam ter uma demonstração, mas geralmente é apenas um clipe de filme ou algum outro tipo de breve demonstração sobre como negociar Opções Binárias, não uma conta usada para praticar negociações. Quando me deparo com uma corretora que afirma ter uma demonstração, mas tudo o que eles têm é um clipe de filme de 5 minutos, eu costumo começar a procurar outro corretor. Não acho justo enganar clientes assim. O que você encontrará com mais frequência é a chance de jogar no mercado por alguns minutos ou alguns dias, até que o corretor corte seu acesso e peça que você faça um depósito.
Ainda não tem certeza porque você precisa de uma conta demo? Então você deve entender que você pode usar o comércio de demonstração como uma ótima ferramenta para ajudar o processo de aprendizagem de opções binárias. Neste artigo vamos discutir as variações das contas de demonstração que estão disponíveis atualmente: “Real”, “Free”, “Paper” e nosso próprio sabor especial, CommuniTraders 2.0.
& # 8220; Real & # 8221; Conta Demo - Trocar Dinheiro Virtual.
A maioria dos corretores de opções binárias não fornece aos clientes contas de demonstração e, em vez disso, fornece desculpas hilárias. Alguns dizem que é desnecessário e só aumentaria a carga de tráfego em seus sites. por isso, poderia prejudicar a negociação com dinheiro real. Outros corretores explicaram que isso poderia induzir as pessoas a pensarem que suas decisões são as mesmas quando se negocia dinheiro real versus dinheiro virtual. Alguns corretores até me disseram que eu realmente posso fazer isso sozinho sem qualquer ajuda dizendo - basta escolher um ativo, definir seu tempo de expiração e, em seguida, verificar sua negociação no histórico de vencimentos dos ativos.
Por outro lado, alguns corretores de opções binárias fornecem uma conta de demonstração. Uma conta virtual é configurada pelo corretor no momento em que o comerciante pede, geralmente não antes. Os corretores não os entregam apenas. Cada corretor fornecerá uma quantia diferente de dinheiro virtual. Outra questão importante são os períodos de expiração das contas de demonstração - alguns corretores oferecem uma conta de demonstração gratuita, mas apenas por um dia, ou uma semana no máximo. Portanto, se você pretende abrir uma conta desse tipo, certifique-se de saber um pouco sobre a negociação antecipadamente, porque você desejará fazer algumas transações virtuais antes que o corretor feche sua conta virtual. Como eu disse, geralmente é uma oferta dentro de um limite de tempo específico. Portanto, certifique-se de fazer o melhor possível e coloque o máximo de negociações possível enquanto sua conta de demonstração ainda estiver ativa.
& # 8220; Grátis & # 8221; Contas Demo - Preciso Depositar Primeiro?
A grande maioria dos corretores de opções binárias exige um depósito inicial antes de configurar uma conta de demonstração de opções binárias. Há muito poucas contas de demonstração verdadeiramente gratuitas, apenas as contas de demonstração pretendiam levá-lo a fazer um depósito. A resposta para isso é mais ou menos a mesma explicação escrita acima - os corretores não querem distribuir contas de demonstração aleatoriamente para pessoas que nunca podem fazer uma troca de dinheiro real. Outra razão pela qual um depósito inicial é necessário é o contrato não-escrito entre clientes e corretores. Ao dizer “contrato”, estou sugerindo que fazer um depósito mostra um compromisso do cliente e, portanto, o corretor tem um bom motivo para fornecer ao comerciante uma conta de demonstração. Alguns podem dizer que é um problema, eu concordo em parte. Pode ser um problema, mas você pode depositar, usar a conta de dinheiro virtual e solicitar uma retirada. Então, se você está realmente interessado em uma conta demo sem negociar para valer, tente a minha sugestão. No geral, acho que negociar dinheiro virtual é um passo que todos os negociantes devem concluir antes de investir dinheiro real. Mesmo que o aspecto psicológico (medo de perder dinheiro, ganância) não seja o mesmo de quando estiver negociando com contas de demonstração, ainda é um bom exercício que o prepara para futuras negociações de Opções Binárias.
Uma série de novos corretores surgiram com uma atitude diferente em relação à oferta de contas de demonstração. Eles oferecem contas de demonstração diretamente na plataforma, sem a necessidade de registro ou depósitos, mas ainda há capturas. Existem dois tipos dessas contas de demonstração gratuitas. Um que não requer inscrição e oferece acesso direto à demonstração - esse tem o inconveniente de não salvar o histórico de negociações. O segundo tipo é aquele que requer um registro para que possa ser convertido em uma conta ativa mais tarde. Depois de criar um nome e uma senha, você poderá entrar e começar a negociar imediatamente. Algo que ambos têm em comum são limites e restrições à negociação, como; saldo de caixa limitado, ativos bloqueados e algumas ferramentas de negociação indisponíveis.
Paper Trading a Demo.
Para obter mais informações sobre o comércio de papel, consulte o seguinte artigo: Negociando opções binárias no papel.
Não jogue na demonstração. Force-se a acreditar que é real!
Antes de escolher sua estratégia de negociação em termos de prazo (horário, diário, três dias, semanal e etc.) ou em termos de condições de mercado (faixa, tendência, entrecortada) você precisa praticar cada uma em uma demonstração para veja qual deles se encaixa melhor no seu estilo. Se você quiser construir um bom sistema, você terá que saber as regras exatas para quando você troca de chamadas ou coloca. Em seguida, você colocaria esses itens em uma demonstração como se estivesse fazendo isso em uma conta real. No momento em que você faz uma negociação em uma conta real, você terá praticado sua estratégia dezenas de vezes. Você terá experiência e terá habilidades técnicas necessárias para realizar uma negociação. Mas uma coisa que você NUNCA deve fazer: não brinque com a conta de demonstração. Nunca pense: "Ah, é apenas uma demonstração, não importa se eu explodir". Não jogue dinheiro por aí (mesmo que seja Demo), pensando que você é esse cara:
Claro, o dinheiro de demonstração não vai comprar carros ou casas, mas considere uma ferramenta para ajudar você a conseguir essas coisas sozinho, não um brinquedo. Se você negociar de maneira imprudente e aumentar os US $ 20.000 iniciais para US $ 100.000, isso não significa que você conseguirá reproduzir o feito em uma conta real, pois assim que seu dinheiro estiver na linha, adivinhe, você começará a se preocupar. “E se eu perder este negócio? E se eu perder o próximo também… OMG se eu perder o terceiro também, estou ficando louco ”. Tente cuidar de sua conta demo tanto quanto você faria para sua conta real. Agora, eu sei que não é totalmente possível, mas tente, porque você quer que o seu comércio de demonstração replique o máximo possível de condições reais, você quer se preparar para uma negociação real onde você se arrisca a ganhar dinheiro real.
Uma conta prática ajuda você a passar pelos mesmos processos e ações pelos quais você passará ao fazer um negócio real e prepará-lo para os possíveis resultados. Se você acha que a negociação em escala é mais atraente do que a negociação em tendência, você terá que descobrir qual método usar para negociar um intervalo e passar pelo processo em uma conta de demonstração, uma dúzia ou até centenas de vezes. O ponto é que você não coloca apenas negociações aleatórias e tenta ver como você é bom. Não, isso é jogo e nós não queremos fazer isso. Você seleciona um método ou estratégia e repassa quantas vezes puder para melhorar nesse método específico.
Negociação de demonstração como oposição a negociação ao vivo.
Aprender a negociar em uma demonstração é uma coisa empolgante e recompensadora. Você aprende a fazer negócios, aplica várias estratégias de negociação, cronometra suas entradas e escolhe vencimentos e não arrisca um único centavo. No entanto, você nunca deve esquecer que passar para a negociação ao vivo será uma experiência diferente. Não importa o quanto você tente tratar sua demonstração como se fosse uma conta de dinheiro real, você não poderá fazer isso completamente. Em uma conta do Live você experimentará o estresse (pelo menos inicialmente), o que você não tem durante a demonstração, você corre o risco de ganhar dinheiro real, suas emoções ficarão no seu caminho, as dúvidas podem começar a vir também. Após sua primeira perda ou algumas perdas, você pode perder sua confiança em seu método. Naquela época, voltar a negociar demo pode ser útil. No entanto, se você tiver sofrido uma série de perdas no Demo antes de se mudar para o Live, você estará familiarizado com o sentimento e lidará com isso mais facilmente. Não estou dizendo que será fácil, mas, pelo menos, você sabe que sua estratégia não é 99% precisa e também sabe que, depois de uma série de derrotas, as coisas começarão a melhorar.
A verdadeira jornada está à frente.
A negociação real certamente não é fácil, mas isso não significa que você não possa lidar com as coisas mencionadas acima. Você não se tornará um bom operador negociando exclusivamente em uma conta demo da mesma forma que você não se tornará um grande boxeador simplesmente fazendo um boxe paralelo. Você só será capaz de adquirir habilidades com a negociação de demonstração. Para ganhar a nitidez de um profissional, você terá que começar a colocar operações reais em uma conta real, cometendo erros, aprendendo com eles, corrigindo-os e melhorando seu estilo de negociação sob condições reais de negociação. Alguns traders dizem que estar em torno de um mês em uma demonstração é mais do que suficiente, outros dizem que você precisa de pelo menos 6 meses, outros aconselham que você deve dobrar sua conta Demo três vezes antes de mudar para o Real. Pessoas diferentes, opiniões diferentes; Eu digo usá-lo tanto quanto você precisa, mas não tenha medo de fazer a troca. Sempre que alguém pratica seus métodos favoritos o suficiente, ele certamente terá que mudar de demonstração para real. Uma vez que você acredita que está pronto para fazer isso, vá para CommuniTraders novamente e aperte o botão "Conta Real", que o levará a uma lista da nossa Lista de Corretores Recomendados. É hora de começar sua jornada real!
Conclusão Final - Use o Virtual Thingy.
Não importa o quanto você leia e aprenda, você precisa praticar. Oferecemos uma Escola de Opções Binárias muito complexa, pensando que os corretores oferecerão as ferramentas para praticar o que você aprendeu. Quando percebemos que eles não mantêm a parte do acordo, decidimos trazer CommuniTraders para que você tenha seu próprio "simulador de voo" gratuito. Hoje em dia, mais e mais corretores oferecem contas de demonstração, então a escolha é sua. Use CommuniTraders ou use uma demonstração do seu corretor, mas não se esqueça que uma conta virtual não é a coisa real (ei, não há emoções na demo) e não é a resposta para todos os seus problemas, mas ajudará você a conectar pontos para se tornar um verdadeiro profissional.
Boa noite, Martin. Você pode por favor entrar em contato comigo. Há algo urgente que preciso discutir com você. Obrigado.
EU SOU JANAKA DE SRI LANKA, NÃO SOU UM HOMEM RICO. ÚLTIMO DOIS ANOS PAGUEI PARA O SOFTWARE GANHAR DINHEIRO EM LINHA QUE NÃO ESTÁ FUNCIONANDO. POR FAVOR, ME TELHA UMA VERDADEIRA VERDADEIRA CORRETORA DE OPÇÃO BINÁRIA & amp; A & # 8220; CONTA BINÁRIA DEMO & # 8221; OBRIGADO.
vá para & gt; encontre uma conta demo aqui.
Eu acho que as firmas de opções binárias são como os cassinos, mas ainda pior. Eles são muito enganosos sobre suas contas de demonstração, querendo que você deposite dinheiro. Existem desculpas sobre não oferecer uma conta demo completamente gratuita, pois em todas as formas de negociação você tem acesso a contas de demonstração. Por exemplo, basta olhar para quantas contas de demonstração gratuitas de forex existem! Além disso, os corretores de ações oferecem contas de demonstração gratuitas. É importante aprender como usar uma plataforma primeiro com dinheiro virtual. Eles sabem que, limitando o acesso a contas de demonstração, muitas pessoas perderão dinheiro e sua empresa ganhará muito dinheiro!
Eu concordo inteiramente que, embora pareça fácil, você precisa praticar diferentes formas de negociação para encontrar o que é mais bem-sucedido. Você pode perder um monte de $ aprender isso com uma conta ao vivo. e é nisso que os corretores estão contando.
OptionBit tem conta demo gratuita. Mas é confiável eu não sei.
Corretores de Binaryoption são alguns que scammers. Você pode tentar forex para ganhar dinheiro, os principais problemas dos corretores são o seu fácil de depositar dinheiro, mas não é fácil de retirar os lucros, e binaryoptions não são um sistema de comércio verificado de troca de segurança, mas a negociação forex é verificada pelo CBCE.
Banc De Binary BDB requer uma conta financiada antes de configurar uma conta de prática. A conta prática é boa para testar suas habilidades e vários aspectos da plataforma. Eu testei anyoption e trading247 plataformas e retiradas sem qualquer dificuldade. Todos eles viram variações de preços para dois provedores de terceiros e isso pode impactar os lucros às vezes; Nos últimos dias, pude usar essas variações de preço em meu benefício. Estou prestes a testar a retirada no BDB. Há processo de verificação é muito bom e há chat online é o melhor que eu já vi, até agora.
Robert & # 8211; Como você encontrou a função retirar com o binário Banc De? Eu tenho uma conta com eles, mas ainda não depositado, gostaria de saber como você começou antes de eu depositar.
AnyOption parece ter uma conta demo estagnada.
ok, não é um site promocional e está tudo bem, mas você pode me recomendar um corretor com uma conta demo gratuita no meu e-mail.
É absolutley executado como um casino. Você precisa saber o que está acontecendo. NÃO spreeds, então eles são pagos quando você perde. Você pode, quando às vezes, mas as probabilidades são empilhadas contra você. Também conseguir seu dinheiro é uma missão. Certifique-se de que você está configurado com um banco que é internacional como o HSBC, se não, pode levar até 2 semanas para obter seus ganhos ou não. BOA SORTE.
Vocês oferecem um gráfico de velas japonês na sua plataforma.
Por favor, aguarde 24-72 horas para rever o seu comentário.
Reservamo-nos o direito de decidir qual comentário será publicado.
Para perguntas sobre corretores - Por favor, use nossos fóruns.
Para reclamações detalhadas - Por favor, use o nosso sistema de reclamações na página inicial.
Liberdade Incorporada.
Blog técnico do Balau sobre hardware aberto, software livre e segurança.
Inicializando o Linux com o U-Boot no QEMU ARM.
Nos últimos meses, toquei com a emulação de QEMU de uma placa de plataforma ARM Versatile, fazendo com que ela executasse programas bare-metal, o carregador de inicialização U-Boot e um kernel Linux completo com um sistema de arquivos baseado em Busybox. Eu tentei colocar tudo junto para emular um procedimento de inicialização completo, mas não foi tão simples. O que segue é uma descrição do que eu fiz para emular uma inicialização completa para um sistema ARM emulado, e os princípios aplicados podem ser facilmente transferidos para outras plataformas diferentes.
Pré-requisitos
qemu-system-arm: pode ser instalado no Ubuntu com o & # 8220; sudo apt-get instala o qemu-kvm-extras & # 8220 ;, no Debian com o & # 8220; aptitude instalar o qemu & # 8221; como root. mkImage: pode ser instalado com o pacote uboot-mkimage. Alternativamente, é compilado a partir da origem do U-Boot. arm-none-eabi toolchain: pode ser baixado da página de ferramentas do CodeSourcery ARM EABI zImage: o kernel do Linux criado no meu post anterior aqui rootfs. img. gz: o sistema de arquivos baseado no Busybox criado no meu post anterior aqui.
O processo de inicialização
Em quadros físicos reais, o processo de inicialização geralmente envolve uma memória não volátil (por exemplo, um Flash) contendo um carregador de inicialização e o sistema operacional. Ao ligar, o núcleo carrega e executa o carregador de inicialização, que, por sua vez, carrega e executa o sistema operacional. O QEMU tem a possibilidade de emular memória Flash em muitas plataformas, mas não no VersatilePB. Existem procedimentos de anúncios de patches disponíveis que podem adicionar suporte a flash, mas por enquanto eu queria deixar o QEMU como está.
O QEMU pode carregar um kernel Linux usando as opções - kernel e - initrd; em um nível baixo, essas opções têm o efeito de carregar dois arquivos binários na memória emulada: o binário do kernel no endereço 0x10000 (64KiB) e o binário ramdisk no endereço 0x800000 (8MiB). Então o QEMU prepara os argumentos do kernel e salta para 0x10000 (64KiB) para executar o Linux. Eu queria recriar essa mesma situação usando o U-Boot, e para manter a situação semelhante a uma real eu queria criar uma única imagem binária contendo todo o sistema, assim como ter um Flash on board. A opção - kernel no QEMU será usada para carregar o binário do Flash na memória emulada, e isso significa que o endereço inicial da imagem binária será 0x10000 (64KiB).
Entender o uso da memória durante o processo de inicialização é importante, pois existe o risco de sobregravar algo durante a cópia e a realocação da memória. Um recurso do U-Boot é a auto-relocação, o que significa que, na execução, o código se copia para outro endereço, que por padrão é 0x1000000 (16MiB). Esse recurso é útil em nosso cenário porque libera menos espaço de memória para copiar o kernel do Linux. O tamanho da imagem do kernel comprimido é de cerca de 1,5 MiB, então o primeiro 1,5 MiB do endereço inicial deve ser livre e utilizável quando o U-Boot copiar o kernel. A figura a seguir mostra a solução que eu criei:
Linha do tempo do uso de memória.
No começo temos três imagens binárias juntas: U-Boot (cerca de 80KiB), kernel do Linux (cerca de 1.5MiB) e o ramdisk do sistema de arquivos raiz (cerca de 1.1MiB). As imagens são colocadas a uma distância de 2 MiB, começando pelo endereço 0x10000. No tempo de execução, o U-boot é realocado para o endereço 0x1000000, liberando assim 2MiB de memória do endereço inicial. O Bootm do comando U-Boot copia a imagem do kernel para 0x10000 e o sistema de arquivos raiz para 0x800000; depois disso, salta no início do kernel, criando assim a mesma situação de quando o QEMU inicia com as opções - kernel e - initrd.
Construindo o U-Boot.
O problema com essa solução é que o U-Boot, quando configurado para ser construído para o VersatilePB, não suporta o uso do ramdisk, o que significa que ele não copia o ramdisk durante o comando bootm e não fornece informações sobre o ramdisk para o kernel. Para dar a funcionalidade que eu preciso, atualizei o código-fonte original do U-Boot antes da compilação. O código a seguir é o patch a ser aplicado à árvore de código-fonte do u-boot-2010.03:
Eu também alterei os argumentos de inicialização (CONFIG_BOOTARGS) para que eles sejam os mesmos que aqueles fornecidos pela linha de comando do QEMU e, em seguida, adicionei um comando (CONFIG_BOOTCOMMAND) para iniciar a inicialização do Linux automaticamente. Para aplicar o patch:
salve o patch em um arquivo, por exemplo.
/u-boot-2010.03.patch download u-boot-2010.03 source tree e extrai-o, por exemplo em.
/u-boot-2010.03 cd no diretório da árvore de código-fonte aplica o patch, por exemplo, com & # 8220; patch - p1 & lt;
Depois de aplicar o patch, o U-Boot pode ser criado como visto no meu post anterior:
O processo de construção criará uma imagem do u-boot. bin que suporta ramdisks para o VersatilePB. Aliás, ele também irá construir o mkimage executável no diretório de ferramentas; ele pode ser usado em vez daquele instalado com pacotes Debian / Ubuntu.
Criando a imagem do Flash.
Como eu disse anteriormente, eu preciso criar uma imagem flash na qual as três imagens binárias são colocadas a uma distância de 2 MiB. O U-Boot precisa trabalhar com imagens binárias envolvidas com um cabeçalho personalizado, criado usando a ferramenta mkimage. Depois de criar as imagens do sistema de arquivos raiz e Linux, podemos escrevê-las dentro de um grande binário em um determinado endereço com o comando dd. Supondo que tenhamos no mesmo diretório: u-boot. bin, zImage e rootfs. img. gz, a lista de comandos a serem executados são:
Esses comandos fazem o seguinte:
crie as duas imagens do U-Boot, zImage. uimg e rootfs. uimg, que também contêm informações sobre onde realocá-las, crie um arquivo vazio de 6MiB chamado flash. bin copie o conteúdo do u-boot. bin no início do flash. bin copie o conteúdo de zImage. uimg em 2MiB desde o início de flash. bin copie o conteúdo de rootfs. uimg em 4MiB a partir do início de flash. bin.
No final, temos uma imagem binária, flash. bin, contendo o layout de memória que eu tinha em mente.
Inicializando o Linux.
Para inicializar o Linux, podemos finalmente chamar:
As mensagens relacionadas ao U-Boot aparecerão no console:
Então o kernel do Linux será executado dentro da tela emulada e a mensagem & # 8220; Por favor, pressione Enter para ativar este console & # 8221; aparecerá, indicando que o sistema de arquivos raiz está funcionando e, portanto, o processo de inicialização foi concluído com êxito. Se algo não funcionar, pode sempre verificar se o sistema funciona sem o U-Boot, com o seguinte comando:
O kernel deve descomprimir e executar até a ativação do console.
Este procedimento tem espaço para melhorias e otimizações, por exemplo, há muita cópia de memória aqui e ali, onde quase tudo pode ser executado no lugar. De qualquer forma, é um bom exercício e um bom ponto de partida que revela detalhes interessantes sobre o processo de inicialização em sistemas embarcados. Como de costume, isso é possível principalmente devido ao fato de que todas as ferramentas são gratuitas e de código aberto.
Relacionado
Pós-navegação.
Deixe uma resposta Cancelar resposta.
Thx para o tuto, funciona perfeitamente com rootfs personalizados, hospedando o ultimo Ubuntu.
Primeiro de tudo, muito obrigado por todos os tutoriais que você escreveu no blog, eles têm sido muito úteis para mim.
Eu estou tentando configurar um ambiente de emulação ARM que consiste em QEMU + U-Boot + Busybox.
Eu segui todos os passos para criar a imagem do kernel do linux (kernel linux versão 2.6.34.7) e o sistema de arquivos busybox (busybox versão 1.17.2) com os outros tutoriais que você tem no blog.
Também criei a imagem flash. bin conforme descrito neste post.
O problema é que quando tento executar o qemu com o flash como kernel, não consigo nada além de uma tela preta.
Nenhuma mensagem de inicialização.
Nenhuma mensagem do kernel.
Você sabe o que posso fazer ou onde o problema pode estar?
Obrigado pela sua atenção.
A tela deve estar preta no início, mas o terminal deve mostrar a contagem regressiva autoboot e algumas outras mensagens. Se você não vê nada no terminal, então certamente o problema não está no Linux ou no Busybox. Você está usando a versão u-boot 2010.03? Tente fazer apenas o trabalho de inicialização, depois de ter criado o u-boot. bin, com o seguinte comando:
$ qemu-system-arm - M versatilepb - m 128M - kernel u-boot. bin - serial stdio.
O autoboot deve falhar e deve exibir um prompt no terminal.
Verifique também se o seguinte comando funciona (ele pula o u-boot):
$ qemu-system-arm - M versatilepb - m 128M - kernel zImage - initrd rootfs. img. gz - append "root = / dev / mem-ram = 128M rdinit = / sbin / init" - série stdio.
Oi, obrigado pela resposta rápida.
Eu estou usando U-boot 2010-03 e também tentei com 2010-09.
Cada componente funciona separadamente. Quero dizer, a execução apenas da inicialização do Windows falha ao carregar a imagem, mas mostra o prompt.
Também rodando o busybox com o kernel linux funciona bem.
Com essa informação, a única coisa que acho que pode estar errada pode ser o arquivo flash. bin, mas tenho certeza de que acertei conforme explicado neste post.
$ hexdump - Cu-boot. bin | head & gt; u-boot. hex.
$ hexdump - C flash. bin | head & gt; flash. hex.
$ diff u-boot. hex flash. hex & amp; & amp; eco OK.
Os dois depósitos devem ser iguais.
Algum dos binários que compõem o flash é maior que 2MB? Porque eu assumi que eles eram menores e os espaçamos de acordo com o flash.
Ok, eu encontrei o problema. Eu estava usando o comando dd errado. Quando o PC está criando o arquivo 6M, o console não escreve nada. Eu interpretei isso como devo entrar, então o resto dos comandos dd. E quando eu acabei de entrar, eu estava terminando o primeiro processo.
O resultado foi um arquivo em branco.
Obrigado por me ajudar a perceber isso e parabéns pela ótima informação que você tem no blog. Tudo está funcionando bem agora
Obrigado pelo seu tutorial.
Parece-me que algo está faltando no texto do seu patch de inicialização.
Meu navegador mostra 29 linhas e os dois últimos são comentários abertos:
29 * Configuração estática ao atribuir um endereço fixo.
Pode haver algo de errado com o meu navegador, eu uso o Firefox 3.6.10 no Ubuntu 9.10?
Você pode esclarecer.
É apenas o contexto que ajuda o & # 8220; patch & # 8221; programa para verificar se está de fato modificando a parte correta do código. As linhas que são realmente alteradas no patch são aquelas com & # 8220; + & # 8221; ou & # 8220; - & # 8221; como o primeiro caractere da linha. Veja en. wikipedia / wiki / Diff # Context_format.
Atualmente estou trabalhando em arm-linux (sistema embarcado).
O processo da minha inicialização é que inicialmente eu tenho um bootloader (u-boot) que inicializa o kernel e depois o kernel cuida do descanso. Mas alguém pode me dizer mais sobre o básico:
1) O que acontece quando inicialmente a placa é ligada ou reiniciada (começando da cpu)?
2) bootloader inicializa o kernel, mas quem inicializa o bootloader? Eu quero dizer que algo deveria estar lá que é ativado por padrão ao ser ligado ou resetado, que por sua vez deve estar iniciando o bootloader? (Isto é o que eu penso)
Eu tentei pesquisar no google sobre isso, mas em todos os lugares eu recebo os resultados diretamente a partir do uboot, mas quem inicia o uboot, que eu não encontrei até agora.
Alguém pode me ajudar em relação a esses conceitos básicos?
Se possível, por favor me forneça os links onde eu posso obter esses detalhes tanto do ponto de vista de hardware e software.
agradecendo antecipadamente,
A resposta depende do sistema de hardware que você está usando. Por exemplo, se você estiver usando um BeagleBoard, é diferente de usar uma placa versátil do RealView. O QEMU tem sua própria implementação do boot, que prepara o mínimo para um kernel Linux e, em seguida, pula para o endereço 0x10000 e é muito diferente do que o hardware real faz.
Normalmente, você tem uma ROM em um determinado endereço (pode ser 0x00000000 ou 0xFFFF0000, & # 8230;) que é executado quando o hardware é redefinido. Ele deve ligar os relógios e configurar as interfaces de memória, então ele pode pular para um endereço fixo ou carregar algum código do Flash e executá-lo. Este procedimento e seu código são muito específicos para a arquitetura, portanto, você deve encontrar as informações no manual da plataforma de hardware.
Aqui estão alguns links para o Beagleboard:
Oh desculpe balau, obrigado pela sua resposta, mas eu esqueci de mencionar os detalhes sobre o conselho. Ele está usando um soc chamado S3C2440 com arquitetura arm9. Você pode, por favor, enviar-me um e-mail com o seu i. d (yahoo, gmail ou rediff) para que eu possa enviar-lhe o pdf introdutório referente à placa em que estou trabalhando.
By the way balu, você me enviou o link sobre o processo de inicialização do Android. Tanto quanto eu sei, o Android não é nada, mas um sabor diferente do Linux. Então, você pode me enviar qualquer link onde será mencionado sobre o processo de boot do Linux embutido (2.6.30.4) especificamente. O link que você enviou sobre o android é realmente conceitual e ao núcleo. Tanto quanto eu sinto, quase o mesmo princípio estaria trabalhando para o Linux. Ainda assim, se você puder me explicar sobre o processo de inicialização do Linux embutido ou pelo menos me enviar alguns links, o dat realmente seria ótimo. Ansioso por sua ajuda. 🙂
meu e-mail está na minha página Sobre mim.
Eu nunca olhei em detalhes o processo interno de inicialização do Linux, mas estou esperando que seja muito semelhante (se não o mesmo) para o Android e para qualquer distribuição Linux para o ARM.
O próprio kernel do Linux contém algumas informações que podem ser úteis:
Agradeço-lhe, mas por que quando eu siga as suas instruções, em seguida, a mensagem de erro:
& # 8220; Falha ao executar / init.
Kernel Panic & # 8211; não está sincronizando: nenhum init encontrado. Tente passar a opção init = para o kernel. & # 8221;
você pode ver a imagem.
Primeiras coisas que vêm à mente:
& # 8211; você definiu o bit de execução de & # 8220; sbin / init & # 8221; com & # 8220; cmod + x & # 8221; ?
Você pode me sugerir um caminho pelo qual podemos passar uma Árvore de Dispositivos do U-Boot para o kernel do Linux na plataforma ARM. Eu quero passar apenas um subconjunto do hardware disponível para o kernel do Linux.
Agradeço antecipadamente.
& # 8211; você definiu o bit de execução de “sbin / init” com “cmod + x”?
por como definir a execução quando Qemu não pode digitar teclado?
Eu não sei como fazer isso atualmente, mas sei que eles estão trabalhando ativamente nisso, especialmente Grant Likely of Secretlab.
A última atualização que li para o suporte à árvore de dispositivos no ARM é a seguinte: Relatório de status da árvore de dispositivos ARM.
Por favor, desculpe, eu quis dizer no seu computador host, antes de criar o sistema de arquivos com o & c. & # 820; cpio & # 8221 ;.
Bom tutorial! Bom trabalho Balau! Até eu mesmo sou um programador / pesquisador do MS Windows (alergia ao Linux) capaz de concluir este minicurso. huh .. demora 1 semana e meia para ser concluído (+ entenda o Linux + Embedded).
Eu estou tentando testar meu kernel embutido no qemu. Tendo problemas para criar o arquivo DRAM. Eu estou usando este script:
sudo virsh net-start padrão.
dd se = / dev / zero de = DRAM bs = 1024 contagem = 256.
sudo qemu-system-arm - M versatilepb - m 256 \
-nográfico - kernel u-boot \
Mas eu recebo este erro:
U-Boot 1.1.6 (27 de fevereiro de 2011 & # 8211; 12:25:20)
*** Atenção & # 8211; CRC ruim, usando o ambiente padrão.
Você tem alguma sugestão??
Se o seu problema é o & # 8220; - pflash & # 8221; suporte, você pode tentar estas instruções: Usando U-Boot e emulação de Flash no Qemu.
Além disso, você pode tentar uma versão mais recente do u-boot como o 2010.03, já que você está usando uma versão 1.1.6) de 5 anos atrás e talvez eles consertaram algo.
Você também pode ver que eu tenho erros semelhantes na minha saída (sem DRAM e sem Flash), mas a execução continua corretamente porque tudo está na RAM.
Muito obrigado por todos os posts! Eles foram altamente informativos.
Bem, eu estava experimentando o meathods diferente de inicializar o linux, e na maior parte do tempo funcionou bem.
Neste caso, no entanto, enquanto exeto o qemu, eu não obtenho a mensagem de inicialização automática, mas obtenho o prombo do uboot.
Então eu pensei em entrar no bootm 0x0021000 depois de olhar para a figura. Isso funcionou e a inicialização do kernel continuou. Quando se trata da parte do rootfs, o rootfs não foi detectado. Então, ao invés disso eu usei o bootm 0x0021000 0x0041000 .. não resolvi o problema.
Você poderia por favor me ajudar?
Acho que você sente falta de alguns zeros & # 8221; no final do endereço que você está usando. eles devem ser "0x210000" e "# 8221; e & # 8220; 0x410000 & # 8221;
Caso você tenha digitado errado neste comentário, mas você está usando os endereços corretos em seus testes:
O que é dito dentro do prompt do U-Boot se você executar o “#inimfo 0x210000 & # 8221; e & # 8220; iminfo 0x410000 & # 8221;
Se o U-Boot não for auto-boot, talvez haja algo errado no patch ou na compilação. Deve pelo menos dar-lhe as mesmas mensagens que obtém quando executa o & lt; 020210000 0 × 00410000 & # 8221; por você mesmo. Você pode verificar usando o & # 8220; - kernel u-boot. bin & # 8221; no comando qemu-system-arm em vez de & # 8220; flash. bin & # 8221 ;? Ele deve falhar, mas fornecer algumas mensagens de erro sobre a inicialização. Neste caso, o problema é a criação do & # 8220; flash. bin & # 8221; imagem com & # 8220; dd & # 8221; comando. Além disso, são todos os três arquivos que compõem o & lt; 8220; flash. bin & # 8221; abaixo de 2 MiB em tamanho?
Olá, obrigado pela resposta . Os zeros eram apenas um erro de digitação.
Agora está funcionando .. o patch foi o problema. em vez disso, foi o que eu fiz:
Depois de examinar o arquivo de correção, modifiquei o arquivo image. c e adicionei: || definido (CONFIG_VERSATILE)
e no versátil. h eu adicionei.
#define CONFIG_BOOTARGS & # 8220; raiz = / dev / ram mem = 128M rdinit = / sbin / init & # 8221;
#define CONFIG_INITRD_TAG 1.
Não adicionei o comando bootm como eu tive que criar um arquivo flash. bin maior, já que o rootfs. uimg tinha mais de 3 MB, assim como valores de memória diferentes.
No entanto, funciona bem. Obrigado uma tonelada!
Qual é a diferença entre & # 8220;.axf & # 8221; arquivo e & # 8220;.bin & # 8221 ;. O procedimento acima mencionado funcionará para a imagem de inicialização com a extensão. axf.
Desde já, obrigado.
& # 8220;.axf & # 8221; é um arquivo executável, com formato ELF, que contém o código e os dados, mas também informações sobre o endereço de carregamento, informações de seções, símbolos de depuração & # 8230; Geralmente é executado por um simulador ou um depurador.
& # 8220;.bin & # 8221; é um arquivo binário puro, contendo o código e os dados que podem ser gravados em um Flash para serem executados por uma plataforma de hardware.
Se você executar o QEMU passando um arquivo ELF com a opção kernel, o QEMU deverá ser capaz de reconhecer o executável. Mas se você criar uma imagem flash binária como eu faço no meu exemplo e colocar o arquivo. axf dentro dela, ela não funcionará.
Se você tiver um & # 8220;.axf & # 8221; arquivo, você pode gerar facilmente um & # 8220;.bin & # 8221; arquivo usando o & # 8220; arm - * - objcopy & # 8221; (no caso de toolchains do GCC) ou do & # 8220; fromelf & # 8221; (no caso de RVDS).
Olá Balau, eu recebo este erro quando tento inicializar o flash. bin. Tanto o boot u-boot quanto o zImage são inicializados de maneira apropriada e individual. Você poderia por favor me dizer onde eu estou indo errado.
Remote commit clonado UNKNOWN.
Último commit localmente DESCONHECIDO.
git state DESCONHECIDO.
## Desconhecido FLASH no Banco 1 & # 8211; Tamanho = 0x00000000 = 0 MB.
*** Atenção & # 8211; CRC ruim, usando o ambiente padrão.
Rede: chip ethernet LAN9118 detectado.
Esta placa não possui endereço MAC carregado automaticamente.
Pressione qualquer tecla para parar o autoboot: 0.
## Inicializando o kernel do Legacy Image em 00210000 & # 8230;
Tipo de imagem: ARM Linux Kernel Image (descompactado)
Tamanho dos dados: 1763072 bytes = 1,7 MB.
Endereço de carregamento: 00010000.
Ponto de entrada: 00010000.
Formato incorreto da imagem do Ramdisk.
A imagem do Ramdisk está corrompida ou é inválida.
Contd & # 8230; de cima,
Eu acho que esqueci de adicionar o sistema de arquivos no comentário previos, Agora, quando eu adiciono o sistema de arquivos, recebo o seguinte erro:
Remote commit clonado UNKNOWN.
Último commit localmente DESCONHECIDO.
git state DESCONHECIDO.
## Desconhecido FLASH no Banco 1 & # 8211; Tamanho = 0x00000000 = 0 MB.
*** Atenção & # 8211; CRC ruim, usando o ambiente padrão.
Rede: chip ethernet LAN9118 detectado.
Esta placa não possui endereço MAC carregado automaticamente.
Pressione qualquer tecla para parar o autoboot: 0.
## Inicializando o kernel do Legacy Image em 00210000 & # 8230;
Tipo de imagem: ARM Linux Kernel Image (descompactado)
Tamanho dos dados: 1763072 Bytes = 1,7 MB.
Endereço de carregamento: 00010000.
Ponto de entrada: 00010000.
## Carregando o Ramdisk do init a partir da imagem legada em 00410000 & # 8230;
Tipo de imagem: ARM Linux RAMDisk Imagem (descompactada)
Tamanho dos dados: 1118941 Bytes = 1,1 MB.
Endereço de carregamento: 00800000.
Ponto de entrada: 00800000.
Carregando Imagem do Kernel & # 8230; ESTÁ BEM.
Descompactando o Linux & # 8230;.qemu: fatal: Modo ruim 0.
R00 = 73200000 R01 = 00000000 R02 = 00000000 R03 = c035c804.
R04 = 00000000 R05 = e91d7679 R06 = 00000000 R07 = 00000000.
R08 = ffffffff R09 = 00000000 R10 = 73200000 R11 = 73200000.
R12 = 001be704 R13 = fffff0d0 R14 = 700100f4 R15 = 70023160.
PSR = 200001db & # 8211; C - A und32.
Abortado (core dumping)
Você pode me ajudar plz.
Parece-me que o código vai para um & # 8220; undefined & # 8221; exceção, como o valor do PSR diz (o PSR de 32 bits) e então o código tenta mudar o modo para 0 (o código que sai do QEMU pode ser encontrado na fonte do QEMU, file & # 8220; target-arm / helper. c & # 8221;
Os registradores R14 (link register) e R15 (program counter) possuem valores estranhos: no endereço de memória 0x70023160 não deve haver nenhuma memória e, portanto, qualquer código.
O zImage ainda funciona individualmente?
No seu exemplo, o u-boot, o kernel do Linux e o rootfs são colocados a uma distância de 2 MiB em flash. bin. Este 2MiB é requerido pelo u-boot ou pelo QEMU. Eu suspeito que é o u-boot, certo? But I am a little confused because this would limit the kernel size to be less than 2MiB. Also will the flash be loaded at 0x10000 (64KiB) so that QEMU can load u-boot?
Thanks for your contributions!
Actually the 2MiB size is not required, neither by U-Boot nor by Linux. I chose that size because the images of the three components were all less than 2MiB and I needed an easy way to know where they are. You can change that distance if you want, and it doesn’t need to be the same, it could be 3MiB and 5MiB, the only requirement is that it has enough space to contain the binary files. Once you create a flash. bin file with different placement, you must change the U-Boot “bootm” command with the right addresses.
Obrigado pela sua resposta!
But how could QEMU know these three binaries are 2MiB apart in flash. bin?
QEMU doesn’t need to know. The binary you give to QEMU with the “-kernel” option is placed at 0x10000, then the execution starts at that address. It is U-Boot that needs to know where the kernel and root filesystem are placed, and you need to pass this information with the “bootm” command.
Thanks a lot for your explanation! I believe “bootm 0x210000 0x410000” in your patch will let u-boot know that the kernel and file system are placed at a distance of 2MiB.
Thanks very much for the tutorials; they all work wonderfully! Now I hope to get an open core Microblaze clone (openfire2) working on my Spartan3e starter kit board. Then I will hopefully reproduce these experiments on real hardware and be on my way!
I am very grateful to your well organized and informative posts.
I am facing an issue while using qemu for booting with flash. bin.
“can’t open /dev/tty3: no such file or directory” message is being displayed repetitively.
If use ‘ls’ command File system directories are displaying.
Maybe the “/dev” directory is not populated correctly, so there could be a problem in “/etc/init. d/rcS” Arquivo. Can you check that your rcS file is executable?
Again On error after starting qemu with flash. bin.
“can’t open /dev/tty3: no such file or directory” message is being displayed repetitively.
On My Host PC(ubuntu-11.04) /etc/init. d/rcS is executable for root.
On QEMU terminal there is no /etc directory.
I tried to execute below command using root privileges but still problem exists.
sudo qemu-system-arm - M versatilepb - m 128M - kernel flash. bin.
Could you please tell me what might be the problem.
If you don’t have an /etc directory inside QEMU terminal then the rootfs image file has not been generated correctly.
On your host PC the “/etc/init. d/rcS” is not important, and executing “QEMU” with sudo does not change things. What is important is your custom rcS file that I created in my previous post here: balau82.wordpress/2010/03/27/busybox-for-arm-on-qemu/
In my tutorial the file must be placed in “_install/etc/init. d/rcS” into the busybox source tree after busybox compilation. Then with the “cpio” command you create a root filesystem image from the _install directory, and it must contain the local “etc” directory that must appear in the QEMU terminal when you do “ls /”
I hope it’s more clear now.
Thank you very much for your quick reply.
Now It’s working. I didn’t fallow your busybox post completely.
I want to get familiarization with u-boot code for versatile PB.
For that I want use GDB on Qemu. Could you please provide info.
for using GDB on QEMU(How to). And also could you please provide good URL’S or docs for learning u-boot functionality from scratch.
QEMU can easily act as a GDB server. When QEMU is run with the “-s - S” options, it will start waiting for a GDB connection on port 1234. Then you can connect using the “target remote localhost 1234” command inside a GDB session. See also my old post Hello world for bare metal ARM using QEMU for an example on debugging a bare metal ARM program, such as U-Boot.
Keep in mind that on Ubuntu the QEMU package does not support debugging very well. I had to compile it from source to make it work.
Debugging U-Boot is a little more complicated because it relocates itself. In this page there is a tutorial on how to debug it: Debugging of U-Boot. When you make the u-boot. elf program the debugging symbols should already be included by default (i mean the “-g” option of GCC).
There is much information in the “README” file inside the U-Boot source tree, and some other things in the “doc” directory, but I don’t think there is documentation to explain the internals of the source code.
I want to install linux on arm6410 with sd card or usb. but, when i insert the sd card to arm6410 i can see the documents in the sd card but i can’t start the boot linux. for that what i must do to firstly. can you examine the first steps. or after insert sd card, must i write some commands for starting install linux. thanks for answer.
Unfortunately I am not familiar with the hardware you’re working on. I suppose the hardware came with a manual, so maybe there’s some information about the boot procedure there. The boards often have some configuration switches that change the way the processor behaves during boot (for example they might have a “Boot from SD” configuration).
I think that you need to prepare the SD card from a PC, using a procedure similar to the one I used in this post and then writing directly on the SD card block device instead of a binary file. Then you can insert the SD card in the board and try to boot. I never did this procedure myself, though.
For anyone trying to reproduce this, at least on a recent Ubuntu host, you may need to pass “-cpu all” or “-cpu cortex-a8” to qemu. The libgcc that gets linked to u-boot appears to be compiled with thumb2 instructions which are not implemented in the Versatile cpu.
I don’t get any u-boot console output without this flag, and using gdb I can see that the cpu takes an exception during __udivsi3() called from serial_init().
Oops, I got the option wrong. Make that “-cpu any”.
Thanks for commenting, Grant. As an aside, I really appreciate your work.
The toolchain has “multilibs” and should link the correct libraries based on compiler flags. If I have time I’ll take a look, maybe it’s just a matter of configuring U-Boot for the correct ARM architecture, because the default expects a newer (thumb2-capable) processor.
Hello Balau, This information is really helpful for getting started. I was trying trying to get the same up in Ubuntu. I have not been able to build the image u-boot. bin. I made the patch fixes mentioned above but I am getting some undefined reference errors. Some of the errors are pasted below for reference:
lib_arm/libarm. a(board. o): In function `start_armboot’:
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board. c:304: undefined reference to `flash_init’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board. c:414: undefined reference to `copy_filename’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board. c:434: undefined reference to `eth_initialize’
/home/ritu/qemu_test/arm_downloads/u-boot-2010.03/lib_arm/board. c:442: undefined reference to `BootFile’
lib_arm/libarm. a(board. o):(.data+0x8): undefined reference to `env_init’
lib_arm/libarm. a(board. o):(.data+0x10): undefined reference to `serial_init’
common/libcommon. a(cmd_bootm. o): In function `bootm_load_os’:
Pls suggest if I am missing anything in the setup.
In my “uboot. map” file that is generated I see that all the functions are present in linking stage:
I suggest re-trying again from a clean state using “make distclean” and then redoing the “make CROSS_COMPILE=arm-none-eabi - versatilepb_config” and “make CROSS_COMPILE=arm-none-eabi - all” commands in my post.
If even that doesn’t work, you can retry by setting environmental variable “export ARCH=arm” and recompile.
Espero que isto ajude.
is flash emulation now support in latest qemu.15.0 for arm versatilepbqemu platform?
From a quick look at the source code it seems it’s not been added. The VersatilePB is an old hardware so I suppose it may never gain flash support in QEMU.
now i make the steps as good as i can but when i finally release flash. bin and try to simulate it on qemu i have this error.
R00=00000000 R01=33fb9880 R02=00049868 R03=00000000.
R04=00000000 R05=00000000 R06=00000000 R07=00000000.
R08=00000000 R09=00000000 R10=00000000 R11=00000000.
R12=000100fc R13=00000000 R14=000100fc R15=33f801f4.
PSR=800001d3 N— A svc32.
but when i try to simulate without u-boot just with rootfs and zimage, it works good.
first i was working with version of u-boot 1.7 , i expected that it was the error but i used the mentioned version in your explain and applied the patch and tried to make flash. bin again but i have the same error 😦
Hi Balau, I am following your procedure to run the latest linux kernel (stable version, 3.2.10) on an imx51 Freescale board with a cassini root filesystem of GenIVI. The uImage that I generate from my kernel zImage is 2.3MB and I packed it into my boot partition. However it turns out that the rootfile system(a. tgz file) which I downloaded is 723MB and when I tar it into my rootfs partition it has a size of 1.7GB. Is there some mistake? I am not able to correctly set the u-boot parameters as I am confused. I have the u-boot. imx after compiling u-boot sources. This is what I have:
sudo dd if=u-boot. imx of=$ seek=1 bs=1024.
Followed by setting of the partitions as follows:
ext4:rootfs:3.6GB(rest of the 4GB SD card)
I then copy the uImage, boot. scr to the boot partition and then I tar © the rootfs. tgz and kernel sources to the rootfs.
Here is what I set in boot. scr:
setenv bootcmd ‘fatload mmc 0:1 0x90800000 uImage; bootm 0x90800000’
setenv bootargs console=ttymxc0,115200 console=tty0 root=/dev/mmcblk0p2 rootwait ro rootfstype=ext4 mxcdi1fb:1280x720M@60.
How do I set the right addresses in the above file? I don’t understand it 😦
Perhaps because of this, while I boot up my imx device: I get the following message:
U-Boot 2011.12 (Mar 13 2012 – 14:15:41)
CPU: Freescale i. MX51 family rev3.0 at 800 MHz.
Reset cause: POR.
WARNING: Caches not enabled.
MMC: FSL_SDHC: 0, FSL_SDHC: 1.
MMC: no card present.
MMC init failed.
Using default environment.
Warning: failed to set MAC address.
Hit any key to stop autoboot: 0.
MMC: no card present.
Booting from net …
BOOTP broadcast 1.
BOOTP broadcast 2.
I’m sorry but my method will not work with a root filesystem that big. My method can be used to boot an intermediate initrd (ramdisk) that is able to load some modules and boot the real root. Depending on your hardware you can place the root filesystem on a server on the network, on an SD card, an USB disk/flash or a SATA drive. More information on the usage of initial ramdisk can be found in kernel source in “Documentation/initrd. txt”
qemu-system-arm - M versatilepb - m 128M - nographic - kernel u-boot. bin.
when i m giving this command then it is saying command not found….
It means the “ qemu-system-arm ” program has not been correctly installed. The installation depends on the Linux distribution you are using, I already specified the steps in the “prerequisites” seção. Be aware that this article has been written in 2010 so the way to install “ qemu-system-arm ” may have changed.
I have build my toolchain through buildroot. while building uboot I am getting following errors.
board. c: In function ‘__dram_init_banksize’:
board. c:233: error: ‘CONFIG_SYS_SDRAM_BASE’ undeclared (first use in this function)
board. c:233: error: (Each undeclared identifier is reported only once.
board. c:233: error: for each function it appears in.)
board. c: In function ‘board_init_f’:
board. c:279: error: ‘CONFIG_SYS_INIT_SP_ADDR’ undeclared (first use in this function)
board. c:312: error: ‘CONFIG_SYS_SDRAM_BASE’ undeclared (first use in this function)
make[1]: *** [board. o] Error 1.
make[1]: Leaving directory `/home/timberline/Android_devel/u-boot-2011.03/arch/arm/lib’
make: *** [arch/arm/lib/libarm. o] Error 2.
It’s not a problem of toolchain, it’s a problem of u-boot version. There are some versions in which old hardware does not compile properly because they changed some of the internals. If you try to do the same with the 2010.03 or 2011.12 they should compile fine.
qemu-system-arm - kernel file - initrd file …
What are the QEMU default load address’s for the kernel and initrd files?
In the post I already wrote:
QEMU can load a Linux kernel using the - kernel and - initrd options; at a low level, these options have the effect of loading two binary files into the emulated memory: the kernel binary at address 0x10000 (64KiB) and the ramdisk binary at address 0x800000 (8MiB).
Sorry but I don’t understand what information that you need is not present in this sentence.
Obrigado pela sua resposta.
What are the QEMU default load address’s into the emulated memory – not in this case but generally – for the kernel and initrd files without using U-Boot, in command like this.
qemu-system-arm - kernel file - initrd file …
The default addresses are indeed 0×10000 for the kernel and 0×800000 for the initrd.
I think I have confused you because in my example I used the same addresses for U-Boot booting.
& # 8211; I see what QEMU does when I pass kernel and ramdisk from command line.
& # 8211; I recreate the same state using U-Boot.
The result is that after the bootm command, the kernel and the ramdisk are in the same addresses that they would have been if I passed them to QEMU from the command line.
I hope I have clarified the situation.
Is it possible to launch successfull QEMU in the way like this.
qemu-system-arm - M versatilepb - m 128M - kernel flash. bin - initrd rootfs. img. gz - serial stdio.
where flash. bin = u-boot. bin + zImage. uimg ?
When U-Boot executes “ bootm 0x210000 0x410000 ” it copies the two images into their load addresses and then launches Linux with some parameters.
If you run QEMU as you want to do, you already have the ramdisk in place. For this reason, you don’t need the second argument to bootm , but you need to tell the kernel that the ramdisk is there. For this, I think you can append “ initrd=0x800000 ” to the BOOTARGS that U-Boot passes to Linux.
Did you try to do it?
I set of course.
#define CONFIG_BOOTCOMMAND “bootm 0x210000”
in UBOOT versatile. h file, and prepared flash. bin.
mkimage - A arm - C none - O linux - T kernel - d zImage - a 0x00010000 - e 0x00010000 zImage. uimg.
dd if=/dev/zero of=flash. bin bs=1 count=4M.
dd if=u-boot. bin of=flash. bin conv=notrunc bs=1.
dd if=zImage. uimg of=flash. bin conv=notrunc bs=1 seek=2M.
I launched qemu.
qemu-system-arm - M versatilepb - m 128M - kernel flash. bin - initrd rootfs. img. gz - serial stdio.
Next I stopped it in UBOOT and checked memory.
VersatilePB# md. b 0x800000 1000.
There wasn’t contents of rootfs. img. gz but only 000…
You are right: I just tried and the ramdisk is placed at 0xd00000 instead.
I discovered this address my doing “ md 0 64 ” and inspecting the data that looked like an address.
Then I misinterpreted the initrd parameter, it should be something like “ initrd=0xd00000,2M “, where the value after the comma is the size of the ramdisk (I rounded by eccess).
With these modifications it works for me.
Any idea why in this case ramdisk is placed at 0xd00000 instead at 0x800000?
No idea, but I haven’t investigated either.
It might have something to do with the kernel binary size, but it may also have been changed in QEMU source code.
In my opinion it should not change anything relevant, we could just accept the fact that the ramdisk is placed at an arbitrary address.
I’d like to launch linux in QEMU, in the way like this.
qemu-system-arm – M versatilepb – kernel flash. bin – initrd rootfs. img. gz …
Suppose that I’d like to pass to the linux kernel the following parameters :
console=ttyAMA0 root=/dev/ram rw initrd=0xd00000,2M.
Generally, I can pass these parameters, through :
& # 8211; append option in qemu command.
& # 8211; bootargs in UBOOT environment.
& # 8211; Boot options->kernel command string (at the time of kernel configuration)
It is possible to pass them in every of this mentioned above way but only in one at once?
Sometimes I’ve kernel image compiled with some parameters in kernel command string and u-boot. bin compiled with other parameters in bootargs. At time of software developing the most comfortable way for me is to change the kernel parameters in qemu command in append option.
Can I launch linux in QEMU in the way mentioned above with different parameters in qemu line, u-boot. bin and kernel image? If yes, which parameters will be passed to linux kernel?
The kernel parameters in your case are those passed by U-Boot. The one in QEMU “-append” option never reach the kernel.
This is because QEMU prepares ATAGS that U-Boot does not read, and then U-Boot prepares its own ATAGS (from bootargs) to be passed to the kernel.
See Documentation/arm/Booting. txt for information about what should be passed to Linux kernel.
In physical world scenario, U-Boot saves its environment in the flash, so you can have an U-Boot image with default parameters, and then a sector of the flash that contains your parameters.
Are you sure you need to use U-Boot? If you don’t use U-Boot then you can pass the kernel parameters with QEMU without problems.
I have a problem with booting Linux on versatilepb through QEMU.
I have used root=/dev/ram rw…
but still my FS not mounted…Can you help me whether I am missing any bootargs..
Here is the tail logs:
List of all partitions:
1f00 65536 mtdblock0 (driver?)
No filesystem could mount root, tried: ext2 cramfs minix romfs.
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
[] (unwind_backtrace+0x0/0xf4) from [] (panic+0x74/0x1c0)
[] (panic+0x74/0x1c0) from [] (mount_block_root+0x1e8/0x228)
[] (mount_block_root+0x1e8/0x228) from [] (mount_root+0xcc/0xf0)
[] (mount_root+0xcc/0xf0) from [] (prepare_namespace+0x160/0x1b8)
[] (prepare_namespace+0x160/0x1b8) from [] (kernel_init+0x158/0x19c)
[] (kernel_init+0x158/0x19c) from [] (kernel_thread_exit+0x0/0x8)
You can’t know if you missed any bootargs by looking only at the tail of the log.
You could add “ console=ttyAMA0 ” to the current bootargs (and QEMU must be launched with “ - serial stdio “) to display more info on the terminal.
Try to find a line near the beginning of the log starting with “ Kernel command line: “. Those are the bootargs.
Then in the middle of the log you should find a line such as “ Trying to unpack rootfs image as initramfs. & # 8220 ;. The lines around that could contain useful hints about why the kernel isn’t mounting the filesystem.
Exactly..I missed to give you the details about boot args.
setenv bootargs ‘console=ttyAMA0,115200n8 root=/dev/ram rw’
I have created uImage loaded at addr1 and created ramdisk of mkimage compatible loaded at.
addr2 (addr1 > addr2).
I did below command.
$ bootm $addr1 $addr2.
Where’s the “ rdinit=. & # 8221; bootarg? Why did you remove it?
No, I just need to mount ramdisk not any other app or init file.
I think rdinit required for explicit app running…correct me If am wrong.
The kernel has to run something (in userspace) when the boot ends, otherwise it panics. This “something” is usually the init program.
I don’t know if using both “ root=/dev/ram ” and “ rdinit=/sbin/init ” is the cleanest way to do it, but I noticed that without “ rdinit ” the kernel does not try to mount the ramdisk and so it panics.
Let me clear the entire scenario.
I have uImage and ramdisk with mkimages.
uImage – load and entry address are 0x800.
uramdisk - load and entry address are 0x800000.
$ tftp 0x100 uImage.
$ tftp 0x4000000 uramdisk. img.
$ setenv bootargs ‘console=ttyAMA0,115200 root=/dev/ram rw’
$ bootm 0x100 0x4000000.
Found the below issue :
No filesystem could mount root, tried: ext2 cramfs minix romfs.
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
[] (unwind_backtrace+0×0/0xf4) from [] (panic+0×74/0x1c0)
[] (panic+0×74/0x1c0) from [] (mount_block_root+0x1e8/0×228)
[] (mount_block_root+0x1e8/0×228) from [] (mount_root+0xcc/0xf0)
[] (mount_root+0xcc/0xf0) from [] (prepare_namespace+0×160/0x1b8)
[] (prepare_namespace+0×160/0x1b8) from [] (kernel_init+0×158/0x19c)
[] (kernel_init+0×158/0x19c) from [] (kernel_thread_exit+0×0/0×8)
Let me clear my complete opinion.
I am convinced that if you try “ setenv bootargs ‘console=ttyAMA0,115200 root=/dev/ram rw rdinit=/sbin/init’ “, it will work.
This is because, as said in Linux “ Documentation/early-userspace/README ” and in other parts of the web, the “initramfs” way of booting Linux expects that the ramdisk is a cpio archive, it mounts it and then tries to execute “ /init “. In our case we don’t have “ /init ” so we have two options:
1. creating a link such as “ ln - s ./sbin/init ./init ” in the busybox _install directory before creating the cpio archive (I haven’t tried it actually)
2. adding “ rdinit=/sbin/init ” to the kernel parameters (as specified in my blog post and in my past replies to you)
I think “ root=/dev/ram ” is superfluous, it should work without it because we don’t reach the point where we mount the root filesystem.
But implementing one of the two ways above is necessary to boot Linux with the ramdisk.
If it still doesn’t work, then you should also check the other parts of the kernel messages as I already said, because something could have gone wrong in mounting the initramfs.
Espero que isto ajude.
Why does Uboot informs on the console.
I don’t know, it seems to be printed by “ display_dram_config ” function in “ board. c ” file (in u-boot-2010.03 the file is in “lib_arm” directory).
Maybe the new u-boot versions fixed this information, but I don’t remember if they still support VersatilePB.
copy the dram_init code on to.
int dram_init (void)
/* dram_init must store complete ramsize in gd->ram_size */
gd->ram_size = get_ram_size((void *)CONFIG_SYS_SDRAM_BASE,
Thanks for your replies.
And what about Uboot commands history ?
What do you mean “what about Uboot commands history”? You wanted to ask why it does not work for you?
If that was the question, my answer is still “I don’t know” as before, and I don’t have time right now to check the source code to try to understand why it does not work.
You have (at least) two paths:
Ask U-Boot mailing list Try to find your answers yourself by trying to understand the source code.
I suggest trying 2 and then 1.
I understand that Uboot 2010.03 commands history on qemu not working at all?
In my environment, it is clear that it does not understand the “arrow” keys as “go up in history of commands”.
U-Boot is made to be small, I suppose giving it a command history is considered bloat for what it should do.
I tend to agree, because if everything works you should never need to access U-Boot command shell.
This is great Balau, thanks for your articles. It serves as a great reference point for my project which is to get u-boot and a linux kernel up and running on the ST-E U8500 platform. Unfortunately QEMU seems to have issues…
Fortunately uboot linaro has commands history and u-boot. bin size is roughly the same.
I try to practice Qemu by following your blog, but I face some problem, please help me, thanks a lot.
$ mkimage - A arm - C none - O linux - T kernel - d zImage - a 0x00010000 - e 0x00010000 uImage.
$ mkimage - A arm - C gzip - O linux - T ramdisk - d rootfs. cpio. gz - a 0x00800000 - e 0x00800000 rootfs. uimg.
$ dd if=/dev/zero of=flash. bin bs=1 count=10M.
$ dd if=u-boot. bin of=flash. bin conv=notrunc bs=1.
$ dd if=uImage of=flash. bin conv=notrunc bs=1 seek=2M.
$ dd if=rootfs. uimg of=flash. bin conv=notrunc bs=1 seek=4M.
VersatilePB # sete bootargs console=ttyAMA0 mem=128M root=/dev/ram rw rdinit=/sbin/init.
VersatilePB # bootm 0x210000 0x410000.
## Booting kernel from Legacy Image at 00210000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 1517816 Bytes = 1.4 MB.
Load Address: 00010000.
Entry Point: 00010000.
## Loading init Ramdisk from Legacy Image at 00410000 …
Image Type: ARM Linux RAMDisk Image (gzip compressed)
Data Size: 2579307 Bytes = 2.5 MB.
Load Address: 00800000.
Entry Point: 00800000.
Loading Kernel Image … ESTÁ BEM.
Uncompressing Linux… done, booting the kernel.
TCP: cubic registered.
NET: Registered protocol family 17.
VFP support v0.3: implementor 41 architecture 1 part 10 variant 9 rev 0.
drivers/rtc/hctosys. c: unable to open rtc device (rtc0)
RAMDISK: Couldn’t find valid RAM disk image starting at 0.
List of all partitions:
1f00 131072 mtdblock0 (driver?)
No filesystem could mount root, tried: ext2 cramfs squashfs vfat msdos romfs.
Kernel panic – not syncing: VFS: Unable to mount root fs on unknown-block(1,0)
How do I fix this rootfs problem.
By the way, it is working when I use.
$ qemu-system-arm - M versatilepb - kernel zImage - initrd rootfs. cpio. gz - nographic - append “console=ttyAMA0 mem=128M”
But why following command would fail with u-boot rootfs ?
$ qemu-system-arm - M versatilepb - kernel zImage - initrd rootfs. uimg - nographic - append “console=ttyAMA0 mem=128M root=/dev/ram rw”
It seem like first problem ?
Need your help, Thanks a lot.
About your first question:
uma. you could use the exact same versions that I used and the exact same configuration to make it work, and then little by little change from my setup to yours to see when things start to go bad. I used Linux 2.6.33, U-Boot 2010.03 and busybox 1.16.0. For example I see that your root filesystem is bigger than mine, in particular bigger than 2MiB. I don’t know if that could be a problem.
b. you could launch QEMU with - s - S options and then attach with arm-…-gdb using “target remote localhost:1234”, then put a breakpoint on the start of Linux execution (for example using “file vmlinux” and putting a breakpoint on start_kernel) and when the breakpoint is reached display the content of 0x00800000 to see if ramdisk has been corrupted (check if the data is the same as rootfs. cpio. gz).
About your second question:
rootfs. uimg is just rootfs. cpio. gz with a U-Boot header attached at the beginning. Linux can’t understand U-Boot headers so the second command will not work and I did not expect otherwise.
I am using U-Boot(compressed) and two kernel Image(uImage). I want to add some code in U-Boot which will select kernel based of time stamp(or using any other way if you have in mind). I am using MIPS architecture.
If kernel-1 is new, U-Boot will boot Kernel-1. and leave kernel-2 as it is.
If kernel-2 is new, U-Boot will boot kernel-2. and leave kernel-2 as it is.
Is it possible to do so?
How can I add such functionality in U-boot?
Where to chage the code for the same?
I don’t think U-Boot was made for something like that.
You could modify the source code of U-Boot around the autoboot functionality, and use the timestamp added by mkimage to choose.
I don’t think it’s simple, you could ask U-Boot mailing lists.
Take a look at this to understand what can be done without modifying the source code: omappedia/wiki/Multiboot_using_u-boot.
thank you for your reply.
Can you just tell me from where u-boot put the kernel image into RAM?
so that I can tel u-boot to put the proper image of kernel to RAM.
If I search the displayed message “Booting kernel from” in U-Boot source code (2010.03), it’s present in “ common/cmd_bootm. c “, in function boot_get_kernel . Following back the calls in the same C file it’s quite easy to find the point where the kernel is loaded.
Hi Balau. I have been following your post to run linux via uboot on qemu. I followed your steps and when I run the “flashed” image on qemu, i always get the error “Uncompressing Linux… done, booting the kernel.
Bad ram offset 8000000”.
I can run u-boot by itself and kernel also by itself (although with kernel, i keep getting spew about /dev/ttyxxx not found). But when I create a flash image, i get this error.
Wondering if you knew anything about it.
desde já, obrigado.
The error says “8000000” (0x08000000), but in my post I talk about address 0x00800000. Are you sure you didn’t put a zero more in the mkimage command or something like that?
Thanks for the reply! One important thing i should have mentioned is that i am running osx qemu.
I am using zynq_zc702 based U-Boot 2011.03 source for running on zynq’s based qemu. Individually i am able to run the u-boot. bin and zimage with rootfs from the qemu. As you suggested I combined u-boot, zimage and rootfs into a single image(flash. bin) for supporting autoboot and I made the changes to include/configs/zynq_common. h.
#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init”
#define CONFIG_BOOTCOMMAND “bootm 0x210000 0x410000”
#define CONFIG_INITRD_TAG 1.
When I run with the following command.
./arm-softmmu/qemu-system-arm - M xilinx-zynq-a9 - m 1024 - serial null - serial mon:stdio - kernel flash. bin - nographic.
I got the following error.
error reading QSPI block device.
error no mtd drive for nand flash.
a0mpcore_priv: smp_priv_base f8f00000.
error no sd drive for sdhci controller (0)
error no sd drive for sdhci controller (1)
Number of configured NICs 0x1.
ram_size 40000000, board_id d32, loader_start 0.
U-Boot 2011.03 (Apr 16 2013 – 12:13:30)
Using default environment.
Hit any key to stop autoboot: 0.
Wrong Image Format for bootm command.
ERROR: can’t get kernel image!
when i give the following command at u-boot level.
iminfo 0x210000 gave the following information.
## Checking Image at 00210000 …
Unknown image format!.
I am not able to see any content at 0x210000 location with md command.
I created flash. bin as you suggest and cross check it with hexdump command. Nothing wrong with flash. bin.
Please help me in this if it is a relevant question to you.
U-boot relocation overwrote your image The “-kernel” option does not place the binary at 0x00010000.
My suggestion is to try to run QEMU with - s - S options, attach with ARM GDB, analyze step by step the first instructions and check the memory with “x” GDB command.
Are there u-boot build config options to enable more verbose output from u-boot?
I could see CONFIG_TRACE but could not find how to enable this.
I believe it’s just a matter of adding “ #define DEBUG 1 ” somewhere like in “ include/config_defaults. h “.
U-Boot is full of “ debug(. ) ” calls that are enabled by this macro to be expanded as printf .
You can increase the value of DEBUG to print also “ debugX(level, . ) ” mensagens.
These macros are defined in “ include/common. h “.
I’m new to work on u-boot, it will be very helpful if someone let us know how to simulate port on qemu u-boot. desde já, obrigado.
What do you mean by “port”? If you mean “serial port”, you are probably looking for “ - serial stdio ” option when running qemu-system-arm.
QEMU doesn’t emulate WM8650 (“ qemu-system-arm - M ? ” doesnt’ show it) so you can’t do that.
on SD are 2 partitons:
2(ext3)-files from ArchLinuxARM-armv5te-latest. tar. gz, and from - xjf alarm-wm8650-modules. tar. bz2.
and otherwise you can not emulate the filesystem of this uzImage. bin (or uImage. bin)?
qemu-system-arm - M versatilepb - m 128M - kernel zImage - initrd rootfs. img. gz - append “root=/dev/ram mem=128M rdinit=/sbin/init” - serial stdio,
tudo funciona bem.
qemu-system-arm - M versatilepb - m 128M - kernel flash. bin - serial stdio.
uboot is able to find kernel image and ramdisk image, but when kernel starts, kernel is not able to find ramdisk.
Do you where is the problem?
The first partition is probably used only by the boot (u-boot?) to run the kernel with the chosen parameters. The second seems to be the root filesystem.
You can’t emulate u-boot, the kernel or the modules for the wm8650 with QEMU because they depend strictly on the hardware and the memory map, and QEMU does not emulate wm8650.
Is it possible that the ramdisk is too big (> 2MiB)?
You can also run QEMU with - s option, then when the kernel fails you connect to it with arm gdb, by executing “target remote localhost:1234” in the gdb prompt, and then check that the content of the memory containing the ramdisk is as expected, for example by executing “dump binary mem. bin 0x00800000 0x00A00000” and check that mem. bin corresponds to rootfs. img. gz (you can do an hexdump - C of both files and diff them graphically).
i got some problems with patchng u-boot from code posted above. I’m using same u-boot version(u-boot-2010.03). Error from applying patch is :
patching file common/image. c.
Hunk #1 FAILED at 941.
1 out of 1 hunk FAILED — saving rejects to file common/image. c.rej.
patching file include/configs/versatile. h.
Hunk #1 FAILED at 124.
1 out of 1 hunk FAILED — saving rejects to file include/configs/versatile. h.rej.
Any suggestions why this happened?
I don’t know why it happened but I recommend changing the source code manually since it’ a few lines of code, and in the process try to see if the source code is different from what it’s expected.
Another explanation is that you copied also the line numbers from the site, they don’t have to be copied.
Hi Balau, i followed your tutorial to boot flash. bin from qemu. MY problem is that when i start the qemu i got his error.
U-Boot 2010.03 (avril 05 2014 – 11:47:27)
Unknown FLASH on Bank 1 – Size = 0x00000000 = 0 MB.
*** Warning – bad CRC, using default environment.
Hit any key to stop autoboot: 0.
qemu: hardware error: pl011_write: Bad offset ff8.
R00=56190527 R01=00000000 R02=00000010 R03=00000000.
R04=00210000 R05=00210000 R06=00fddef4 R07=00000003.
R08=00fddfe0 R09=00000000 R10=01014ffc R11=01017e8c.
R12=00fddd03 R13=101f4000 R14=010105ac R15=010105a4.
PSR=600001d3 - ZC - A svc32.
When i test without u-booot it works perfectlly. So, i wanna know waht’s wrong.
The error is generated while executing U-Boot, Linux is not yet started.
R15 is program counter, R14 is return address; you can see where the program crashed from U-Boot disassembly. You can disassemble it by running something like arm-none-eabi-objdump - S u-boot >u-boot. dis . U-Boot should already be compiled with debugging symbols, otherwise try to enable them by adding - g to CFLAGS .
You can also try to run QEMU with - s - S options and then attach to it with arm-none-eabi-gdb using u-boot as file for symbols and debug info. Then you can break at do_bootm_linux (that’s the last function U-Boot should execute) or at abort_boot (that’s the last thing your U-Boot prints) and try to debug from there.
I try to debug decompress part of linux kernel. But my Breakpoint does not hit.
To run linux on qemu i ran following command.
qemu-system-arm - M versatilepb - m 128M - s - S - kernel arch/arm/boot/zImage.
and on gdb side ran this command.
arm-none-eabi-gdb target remote localhost:1234.
then add breakpoint.
like b __setup_mmu.
None of my breakpoint hit .
Only break point after MMU_ENABLE hit like start_kernel.
The part of software that runs before the decompression is position independent code. In my case (probably also in yours) the zImage is loaded in 0x60010000, and that’s the address containing start , but in the vmlinux ELF the address is 0. I tried the GDB command add-symbol-file arch/arm/boot/compressed/vmlinux 0x60010000 instead of file arch/arm/boot/compressed/vmlinux and it seems to load the symbols to their right addresses, try it also in your setup.
I followed your steps as mentioned. But Still not able to hit the breakpoints.
I checked with gdb and dump the 0x60010000 location.
0x60010000: 0x00000000 0x00000000 0x00000000 0x00000000.
0x60010010: 0x00000000 0x00000000 0x00000000 0x00000000.
0x60010020: 0x00000000 0x00000000.
It shows nothing . So might be in my case load address of zImage will be different.
I have question:-
1) How to find the address where zImage loaded in qemu.
I checked with gdb and dump the location 0x00010000 location. I got this location when i searched for zImage header magic number 0x016f2818.
I matched with my zImage Hexdump but when i load the elf file with add-symbol-file arch/arm/boot/compressed/vmlinux 0x00010000 and put some breakpoint.
It halt that place and show function input_data() with no code.
I checked with add-symbol-file arch/arm/boot/compressed/vmlinux 0x60010000.
but still breakpoints not hitting. When i dump the 0x60010000 on gdb it shows.
0x00000000 . When i dump the 0x00010000 on gdb it has same footprint as my zImage.
But when i add-symbol-file arch/arm/boot/compressed/vmlinux 0x00010000 and put breakpoint on this address. It stops there but function it shows input_data(). Please let me know how you find the load address 0x60010000 on your system.
I launched QEMU with - s - S (so it’s stopped before executing anything) and then connected with gdb. With something like x/10i $pc you can see the code at current program counter. At the beginning QEMU puts a couple of its own instructions to jump to the user code. So I stepi a few times until it jumps, and at that point it jumps to the beginning of the binary passed by - kernel option. That address should be the offset that you pass to add-symbol-file . I tried with versatilepb to make it similar to your setup and I find your same problem, and it is strange, but it is easily worked around if you stepi until you reach start or if you break start and then continue .
i used this command :-
add-symbol-file ./arch/arm/boot/compressed/vmlinux 0x00010000 - s. piggydata 0x00014610.
and now i am able to put break points and debug the code.
I found out that in arch/arm/boot/compressed/vmlinux.
.piggydata 001d28e0 00004610 00004610 0000c610 2**0.
which means. piggydata starthe at 0x4610 and length 001d28e0 which overlaps the 0x00010000 address. i. e. gdb not able put the breakpoints . so remap that section also .
Thanks for your help,
I compiled U-Boot and run QEMU with “u-boot” (ELF file) and I can see u-boot message.
$ qemu-system-arm - M vexpress-a9 – kernel u-boot - nographic.
But I just saw nothing when using “u-boot. bin”:
$ qemu-system-arm - M vexpress-a9 – kernel u-boot. bin - nographic.
The cross-compiler I use is “arm-linux-gnueabi” and my linux distrubution is Ubuntu 12.04.
I also tried to re-compiled U-Boot with “versatile_defconfig” and run qemu with “versatilepb”. I still can’t see any boot message.
Do you have any idea?
I am quite sure that if you give QEMU an ELF it will load it using the information about the segments of data, code, etc. and then it will execute from the entry point. But if you run a binary it will simply place it as is into a given address (different for each machine) and then jump to that address. You can try to run QEMU with - s - S and attach to it with GDB by running arm-linux-gnueabi-gdb u-boot and then (gdb) target remote localhost:1234 ; in this way you can run step-by-step and see what is happening with program counter and memory content.
I ran QEMU with GDB but u-boot. bin just can’t be executed.
I tried to decode u-boot ELF file and found entry point is 0×60800000.
So, I generated image file with mkimage and set entry point to 0×60800000. In this way, it worked.
I used it with latest kernel (linux-3.16.2) and u-boot (u-boot-2014.07) with these patch:
index 11b3cf5..4a92b6a 100644.
@@ -933,6 +933,15 @@ int boot_get_ramdisk(int argc, char * const argv[], bootm_headers_t images,
+ * We need to copy the ramdisk to SRAM to let Linux boot.
+ memmove ((void *)rd_load, (uchar *)rd_data, rd_len);
> else if (images->legacy_hdr_valid &&
index 29c32fe..56e4818 100644.
* High Level Configuration Options.
#define CONFIG_BOOTDELAY 2.
-#define CONFIG_BOOTARGS “root=/dev/nfs mem=128M ip=dhcp “\
+#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init console=ttyAMA0”
+#define CONFIG_BOOTCOMMAND “bootm 0x210000 0x410000”
+#define CONFIG_INITRD_TAG 1.
* Static configuration when assigning fixed address.
I think recent kernels needs a device tree to work. It’s possible that during compilation a “*.dtb” (Device Tree Binary) file is created, and then you need to pass it to qemu-system-arm with its - dtb file option.
Estou recebendo este erro. zImage runs without uboot.
*** Warning – bad CRC, using default environment.
Hit any key to stop autoboot: 0.
Booting kernel from Legacy Image at 00210000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 2023632 Bytes = 1.9 MB.
Load Address: 00010000.
Entry Point: 00010000.
Loading init Ramdisk from Legacy Image at 00510000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 2023632 Bytes = 1.9 MB.
Load Address: 00010000.
Entry Point: 00010000.
No Linux ARM Ramdisk Image.
Ramdisk image is corrupt or invalid.
It seems the ramdisk image you are providing has a wrong U-Boot header. With mkimage you prefix the binary with an header that contains also the image type, which you choose with - T option. One possible type is ramdisk , which should be the right type for what you want, and another type is kernel ; U-boot is telling you the type with the message “Image Type: ARM Linux Kernel Image (uncompressed)”, then it says it can’t find a Linux ARM Ramdisk image because the type of the image is kernel and not ramdisk . I thought you probably ran mkimage with - T kernel instead of - T ramdisk , but then I noticed the Data Size for the two images that you are trying to load is the same, so you probably created the combined U-Boot image (containing u-boot + kernel + ramdisk) using the kernel twice (once at 0x210000 and once at 0x510000) instead of using the ramdisk image.
i got this error when i apply the patch : patch - p1 <
patching file common/image. c.
Hunk #1 FAILED at 941.
1 out of 1 hunk FAILED — saving rejects to file common/image. c.rej.
patching file include/configs/versatile. h.
Hunk #1 FAILED at 124.
1 out of 1 hunk FAILED — saving rejects to file include/configs/versatile. h.rej.
i don’t know how to fix it and i don’t know how to modify the patch.
That’s a symptom that you are not applying the patch on u-boot version 2010.03.
Instead of applying the patch you can change the files by hand, by adding the “ defined(CONFIG_VERSATILE) ” in “ u-boot-2010.03/common/image. c ” and defining CONFIG_BOOTARGS, CONFIG_BOOTCOMMAND and CONFIG_INITRD in “ u-boot-2010.03/include/configs/versatile. h ” as in the patch.
Anyway I don’t know if my blog post will work if you change U-Boot version.
I change files by hand and i’m using u-boot version 2010.03.
/ #define CONFIG_BOOTARGS “root=/dev/nfs mem=128M ip=dhcp “\
#define CONFIG_BOOTARGS “root=/dev/ram mem=128M rdinit=/sbin/init”
#define CONFIG_BOOTCOMMAND “bootm 0x210000 0x410000”
#define CONFIG_INITRD_TAG 1.
#if defined(CONFIG_B2) || defined(CONFIG_EVB4510) || defined(CONFIG_ARMADILLO) || defined(CONFIG_VERSATILE)
i have done every thing exactly the way u do it , i use rootfs. img. gz : size= 1.1 MB.
zImage size=2.2 MB and u-boot. bin= 87.0 kB.
flash. bin siza=6.3 MB.
when i try qemu-system-arm - M versatilepb - m 128M - kernel flash. bin - serial stdio.
the host’s terminal keeps showing me : U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
U-Boot 2010.03 (Feb 19 2016 – 11:30:11)
and a black window for qemu.
the same thing when tried qemu-system-arm - M versatilepb - m 128M - kernel u-boot. bin - initrd rootfs. img. gz - append “root=/dev/ram mem=128M rdinit=/sbin/init” - serial stdio.
and it works perfectly when i tried qemu-system-armrsatilepb - m 128M - kernel zImage - initrd rootfs. img. gz - append “root=/dev/ram mem=128M rdinit=/sbin/init” - serial stdio.
i use ubuntu 12.04.
how can i fix that please.
I don’t know, it seems the code stops before printing DRAM size, if we compare it to my output that is displayed in the blog post.
You could try to debug it with gdb. Run QEMU with the “-s - S” options, it will open but not execute the program. Then go into another terminal, go in the u-boot-2010.03 directory and run “arm-none-eabi-gdb u-boot” to load u-boot ELF file containing symbols, then in gdb prompt use “target remote :1234” to connect to QEMU, then “break display_dram_config” to put a breakpoint in the function that seems to reset everything, then “continue” and see what happens when you reach that point by debugging step-by-step and printing local variables.
i just did what u said.
qemu-system-arm - s - S - M versatilepb - m 128M - kernel u-boot. bin - serial stdio.
(gdb) break display_dram_config.
Breakpoint 1 at 0x10003c0: file board. c, line 174.
Breakpoint 1, display_dram_config () at board. c:174.
174 size += gd->bd->bi_dram[i].size;
what that suppose to mean coz i don’t understand debugging symbols so much.
I could not replicate your problem so I was suggesting that you debug it with gdb. This could be an occasion to try debugging. Use “step” and “next” to run only one line of code (step falls into function calls, next does not), “continue” to run indefinitely, “p” to print variables by their names, “info stack” to see which function calls have been made to reach that point, “break” on function names to set breakpoint when calling, “help” for everything else. There are many tutorials on the net. If you have trouble with gdb in text mode, you could try DDD as a graphical front-end with “ddd –debugger arm-none-eabi-gdb — u-boot” instead of running gdb.
Anyway debugging your problem also means understanding what u-boot code is doing. I indicated you the “display_dram_config” because I searched the point where DRAM was printed in u-boot source code.
when i run qemu-system-arm - M versatilepb - m 128M - kernel flash. bin - serial stdio.
U-Boot 2010.03 (فبر 22 2016 – 12:08:22)
*** Warning – bad CRC, using default environment.
Hit any key to stop autoboot: 0.
Booting kernel from Legacy Image at 00210000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 2171552 Bytes = 2.1 MB.
Load Address: 00010000.
Entry Point: 00010000.
Loading init Ramdisk from Legacy Image at 00410000 …
Image Type: ARM Linux RAMDisk Image (uncompressed)
Data Size: 1098402 Bytes = 1 MB.
Load Address: 00800000.
Entry Point: 00800000.
Loading Kernel Image … ESTÁ BEM.
qemu: fatal: Trying to execute code outside RAM or ROM at 0xe781b200.
R00=e781b200 R01=00000005 R02=ff0ffff0 R03=00000010.
R04=00008000 R05=00010080 R06=e780b180 R07=00000183.
R08=00000100 R09=41069265 R10=e0866000 R11=e08aa000.
R12=00010494 R13=e7a2e440 R14=0001011c R15=e781b200.
PSR=400001d3 - Z– A svc32.
s00=00000000 s01=00000000 d00=0000000000000000.
s02=00000000 s03=00000000 d01=0000000000000000.
s04=00000000 s05=00000000 d02=0000000000000000.
s06=00000000 s07=00000000 d03=0000000000000000.
s08=00000000 s09=00000000 d04=0000000000000000.
s10=00000000 s11=00000000 d05=0000000000000000.
s12=00000000 s13=00000000 d06=0000000000000000.
s14=00000000 s15=00000000 d07=0000000000000000.
s16=00000000 s17=00000000 d08=0000000000000000.
s18=00000000 s19=00000000 d09=0000000000000000.
s20=00000000 s21=00000000 d10=0000000000000000.
s22=00000000 s23=00000000 d11=0000000000000000.
s24=00000000 s25=00000000 d12=0000000000000000.
s26=00000000 s27=00000000 d13=0000000000000000.
s28=00000000 s29=00000000 d14=0000000000000000.
s30=00000000 s31=00000000 d15=0000000000000000.
Abandon (core dumped)
qemu-system-arm - M versatilepb - m 128M - kernel zImage - initrd rootfs. img. gz - append “root=/dev/ram mem=128M rdinit=/sbin/init” - serial stdio.
Uncompressing Linux… done, booting the kernel. and qemu run normally.
rootfs. img. gz :1.1 Mo.
i use the same u-boot version and the same toolchaine as u.
The reason why in my post I place the three images at 2MiB of distance is because the images have a size of less than 2MiB. In your case zImage is bigger, so when you create the flash. bin, the rootfs overwrites the last piece of the kernel image, corrupting it. You have to place the rootfs at larger distance, and change the CONFIG_BOOTCOMMAND accordingly.
thanks a lot I placed the three images at 3MiB of distance and it worked well , i was just wondering if there is any possibility to booting linux with u-boot on qemu with 13 Mo size for the rootfs. gz. img ?
It’s probably necessary to compile uboot with a higher relocation address. I don’t know if it’s enough, I never tried.
Hmm, is there any good resource around about structure of u-boot flash file? So one can make it’s own from scratches containing u-boot + freebsd or linux kernel + world? Or even more kernels in one file so one can switch betwen them.
The “resource” I used to understand is mkimage source code. Now I see that U-Boot supports a new format called FIT. In both cases I see that this document contains many info: Multi image booting scenarios.
I went with the tutorial , U-Boot can perfectly load the kernel alone when.
I use “bootm 210000” , but when I add the file systems , U-Boot keeps loading itself infinitely.
*** Warning – bad CRC, using default environment.
Hit any key to stop autoboot: 0.
Booting kernel from Legacy Image at 00210000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 2351339 Bytes = 2.2 MB.
Load Address: 00010000.
Entry Point: 00010000.
Wrong Ramdisk Image Format.
Ramdisk image is corrupt or invalid.
VersatilePB # bootm 210000 510000.
Booting kernel from Legacy Image at 00210000 …
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 2351339 Bytes = 2.2 MB.
Load Address: 00010000.
Entry Point: 00010000.
Loading init Ramdisk from Legacy Image at 00510000 …
Image Type: ARM Linux RAMDisk Image (uncompressed)
Data Size: 10568192 Bytes = 10.1 MB.
Load Address: 00800000.
Entry Point: 00800000.
U-Boot 2010.03 (Mar 17 2017 – 23:33:54)
*** Warning – bad CRC, using default environment.
Hit any key to stop autoboot: 0.
Booting kernel from Legacy Image at 00210000 …
thank you for interesting post, however, I was unable to reproduce this. The problem is that new U-boot looks somewhat different and it’s not clear anymore, how to apply patch. I also failed to build U-boot 2010.03, because I use gcc 5.4 which older U-boot’s build system is not aware of. All in all, I stuck. I would like to combine u-boot + kernel (so far – I’m still learning and this is my primary task for now) into single image and run it on qemu-system-arm - M vexpress-a9 mimicking real flash. But I’m absolutely lost. How to prepare images, where to load them, what offsets to use. Here’re probably some more details stackoverflow/q/46239926/3443104 – what I’ve got and what I tried. I would be highly indebted if you ping me in right direction.
I am not sure what you are doing wrong, but it probably involves memory addresses and available emulated memory. I would suggest to start qemu with gdb server activated, then attach to it with gdb found I your toolchain and the u-boot elf file for symbols. Then you put a breakpoint on the bootz and maybe the fatload commands and run it. With gdb you can also examine memory content with something like x/10x 0x04000000.
Multithreaded Programming (POSIX pthreads Tutorial)
Introdução.
Code is often written in a serialized (or sequential) fashion. What is meant by the term serialized? Ignoring instruction level parallelism (ILP), code is executed sequentially, one after the next in a monolithic fashion, without regard to possibly more available processors the program could exploit. Often, there are potential parts of a program where performance can be improved through the use of threads.
What is a Thread?
Isn't that something you put through an eye of a sewing needle?
How does it relate to programming then?
Think of sewing needles as the processors and the threads in a program as the thread fiber. If you had two needles but only one thread, it would take longer to finish the job (as one needle is idle) than if you split the thread into two and used both needles at the same time. Taking this analogy a little further, if one needle had to sew on a button (blocking I/O), the other needle could continue doing other useful work even if the other needle took 1 hour to sew on a single button. If you only used one needle, you would be.
Definição.
Terminologia.
Before we can dive in depth into threading concepts, we need to get familiarized with a few terms related to threads, parallelism and concurrency.
Lightweight Process (LWP) can be thought of as a virtual CPU where the number of LWPs is usually greater than the number of CPUs in the system. Thread libraries communicate with LWPs to schedule threads. LWPs are also sometimes referred to as kernel threads . X-to-Y model. The mapping between LWPs and Threads. Depending upon the operating system implementation and/or user-level thread library in use, this can vary from 1:1, X:1, or X:Y. Linux, some BSD kernels, and some Windows versions use the 1:1 model. User-level threading libraries are commonly in the X:1 class as the underlying kernel does not have any knowledge of the user-level threads. The X:Y model is used in Windows 7. Contention Scope is how threads compete for system resources (i. e. scheduling). Bound threads have system-wide contention scope, in other words, these threads contend with other processes on the entire system. Unbound threads have process contention scope. Thread-safe means that the program protects shared data, possibly through the use of mutual exclusion. Reentrant code means that a program can have more than one thread executing concurrently. Async-safe means that a function is reentrant while handling a signal (i. e. can be called from a signal handler). Concurrency vs. Parallelism - They are not the same! Parallelism implies simultaneous running of code (which is not possible, in the strict sense, on uniprocessor machines) while concurrency implies that many tasks can run in any order and possibly in parallel.
Amdahl's Law and the Pareto Principle.
Threads can provide benefits. for the right applications! Don't waste your time multithreading a portion of code or an entire program that isn't worth multithreading.
Thread Design Patterns.
There are different ways to use threads within a program. Here, three common thread design patterns are presented. There is no hard and fast rule on which is the best. It depends on what the program is intended to tackle and in what context. It is up to you to decide which best pattern or patterns fit your needs.
Thread Pool (Boss/Worker)
One thread dispatches other threads to do useful work which are usually part of a worker thread pool . This thread pool is usually pre-allocated before the boss (or master) begins dispatching threads to work. Although threads are lightweight, they still incur overhead when they are created.
Peer (Workcrew)
The peer model is similar to the boss/worker model except once the worker pool has been created, the boss becomes the another thread in the thread pool, and is thus, a peer to the other threads.
Similar to how pipelining works in a processor, each thread is part of a long chain in a processing factory. Each thread works on data processed by the previous thread and hands it off to the next thread. You must be careful to equally distribute work and take extra steps to ensure non-blocking behavior in this thread model or you could experience pipeline "stalls."
Protecting Shared Resources.
Threads may operate on disparate data, but often threads may have to touch the same data. It is unsafe to allow concurrent access to such data or resources without some mechanism that defines a protocol for safe access ! Threads must be explicitly instructed to block when other threads may be potentially accessing the same resources.
Mutual Exclusion.
Mutual exclusion is the method of serializing access to shared resources. You do not want a thread to be modifying a variable that is already in the process of being modified by another thread! Another scenario is a dirty read where the value is in the process of being updated and another thread reads an old value.
Mutex Types.
There are different types of locks other than the standard simple blocking kind.
Recursive : allows a thread holding the lock to acquire the same lock again which may be necessary for recursive algorithms. Queuing : allows for fairness in lock acquisition by providing FIFO ordering to the arrival of lock requests. Such mutexes may be slower due to increased overhead and the possibility of having to wake threads next in line that may be sleeping. Reader/Writer : allows for multiple readers to acquire the lock simultaneously. If existing readers have the lock, a writer request on the lock will block until all readers have given up the lock. This can lead to writer starvation. Scoped : RAII-style semantics regarding lock acquisition and unlocking.
Depending upon the thread library or interface being used, only a subset of the additional types of locks may be available. POSIX pthreads allows recursive and reader/writer style locks.
Potential Traps with Mutexes.
An important problem associated with mutexes is the possibility of deadlock . A program can deadlock if two (or more) threads have stopped execution or are spinning permanently. For example, a simple deadlock situation: thread 1 locks lock A, thread 2 locks lock B, thread 1 wants lock B and thread 2 wants lock A. Instant deadlock. You can prevent this from happening by making sure threads acquire locks in an agreed order (i. e. preservation of lock ordering ). Deadlock can also happen if threads do not unlock mutexes properly.
Atomic Operations.
Atomic operations allow for concurrent algorithms and access to certain shared data types without the use of mutexes. For example, if there is sufficient compiler and system support, one can modify some variable (e. g., a 64-bit integer) within a multithreaded context without having to go through a locking protocol. Many atomic calls are non-portable and specific to the compiler and system. Intel Threading Building Blocks (see below), contains semi-portable atomic support under C++. The C++1x and C1x standards will also include atomic operations support. For gcc-specific atomic support, please see this and this.
Thread Synchronization Primitives.
As we have just discussed, mutexes are one way of synchronizing access to shared resources. There are other mechanisms available for not only coordinating access to resources but synchronizing threads.
A thread join is a protocol to allow the programmer to collect all relevant threads at a logical synchronization point. For example, in fork-join parallelism, threads are spawned to tackle parallel tasks and then join back up to the main thread after completing their respective tasks (thus performing an implicit barrier at the join point). Note that a thread that executes a join has terminated execution of their respective thread function.
Condition Variables.
Barriers are a method to synchronize a set of threads at some point in time by having all participating threads in the barrier wait until all threads have called the said barrier function. This, in essence, blocks all threads participating in the barrier until the slowest participating thread reaches the barrier call.
Spinlocks are locks which spin on mutexes. Spinning refers to continuously polling until a condition has been met. In the case of spinlocks, if a thread cannot obtain the mutex, it will keep polling the lock until it is free. The advantage of a spinlock is that the thread is kept active and does not enter a sleep-wait for a mutex to become available, thus can perform better in certain cases than typical blocking-sleep-wait style mutexes. Mutexes which are heavily contended are poor candidates for spinlocks.
Semaphores.
Semaphores are another type of synchronization primitive that come in two flavors: binary and counting. Binary semaphores act much like simple mutexes, while counting semaphores can behave as recursive mutexes . Counting semaphores can be initialized to any arbitrary value which should depend on how many resources you have available for that particular shared data. Many threads can obtain the lock simultaneously until the limit is reached. This is referred to as lock depth .
POSIX pthreads.
Now that we have a good foundation of thread concepts, lets talk about a particular threading implementation, POSIX pthreads. The pthread library can be found on almost any modern POSIX-compliant OS (and even under Windows, see pthreads-win32).
Preliminaries.
Before we begin, there are a few required steps you need to take before starting any pthreads coding:
Add #include <pthread. h> to your source file(s). If you are using gcc, you can simply specify - pthread which will set all proper defines and link-time libraries. On other compilers, you may have to define _REENTRANT and link against - lpthread . Optional: some compilers may require defining _POSIX_PTHREAD_SEMANTICS for certain function calls like sigwait() .
Creating pthreads.
A pthread is represented by the type pthread_t . To create a thread, the following function is available:
Let's digest the arguments required for pthread_create() :
pthread_t *thread : the actual thread object that contains pthread id pthread_attr_t *attr : attributes to apply to this thread void *(*start_routine)(void *) : the function this thread executes void *arg : arguments to pass to thread function above.
Before we dive into an example, let's first look at two other important thread functions:
pthread_exit() terminates the thread and provides the pointer *value_ptr available to any pthread_join() call.
This program creates NUM_THREADS threads and prints their respective user-assigned thread id. The first thing to notice is the call to pthread_create() in the main function. The syntax of the third and fourth argument are particularly important. Notice that the thr_func is the name of the thread function, while the fourth argument is the argument passed to said function. Here we are passing a thread function argument that we created as a thread_data_t struct. Of course, you can pass simple data types as pointers if that is all that is needed, or NULL if no arguments are required. However, it is good practice to be able to pass arguments of arbitrary type and size, and is thus illustrated for this purpose.
Make sure you check the return values for all important functions. The second argument to pthread_create() is NULL indicating to create a thread with default attributes. The defaults vary depend upon the system and pthread implementation. Notice that we have broken apart the pthread_join() from the pthread_create() . Why is it that you should not integrate the pthread_join() in to the thread creation loop? Although not explicitly required to call pthread_exit() at the end of the thread function, it is good practice to do so, as you may have the need to return some arbitrary data back to the caller via pthread_join() .
pthread Attributes.
Threads can be assigned various thread attributes at the time of thread creation. This is controlled through the second argument to pthread_create() . You must first pass the pthread_attr_t variable through:
Some attributes that can be set are:
Attributes can be retrieved via complimentary get functions. Consult the man pages for the effect of each of these attributes.
pthread Mutexes.
pthread mutexes are created through the following function:
The pthread_mutex_init() function requires a pthread_mutex_t variable to operate on as the first argument. Attributes for the mutex can be given through the second parameter. To specify default attributes, pass NULL as the second parameter. Alternatively, mutexes can be initialized to default values through a convenient macro rather than a function call:
Here a mutex object named lock is initialized to the default pthread mutex values.
Each of these calls requires a reference to the mutex object. The difference between the lock and trylock calls is that lock is blocking and trylock is non-blocking and will return immediately even if gaining the mutex lock has failed due to it already being held/locked. It is absolutely essential to check the return value of the trylock call to determine if the mutex has been successfully acquired or not. If it has not, then the error code EBUSY will be returned.
In the above example code, we add some shared data called shared_x and ensure serialized access to this variable through a mutex named lock_x . Within the thr_func() we call pthread_mutex_lock() before reading or modifying the shared data. Note that we continue to maintain the lock even through the printf() function call as releasing the lock before this and printing can lead to inconsistent results in the output. Recall that the code in-between the lock and unlock calls is called a critical section. Critical sections should be minimized for increased concurrency.
pthread Condition Variables.
pthread condition variables are created through the following function call or initializer macro similar to mutexes:
Similar to the mutex initialization call, condition variables can be given non-default attributes through the second parameter. To specify defaults, either use the initializer macro or specify NULL in the second parameter to the call to pthread_cond_init() .
pthread_cond_wait() puts the current thread to sleep. It requires a mutex of the associated shared resource value it is waiting on. pthread_cond_signal() signals one thread out of the possibly many sleeping threads to wakeup. pthread_cond_broadcast() signals all threads waiting on the cond condition variable to wakeup. Here is an example on using pthread condition variables:
In thr_func1() , we are locking the count_lock mutex so we can read the value of count without entering a potential race condition. The subsequent pthread_cond_wait() also requires a locked mutex as the second parameter to avoid a race condition where a thread prepares to wait on a condition variable and another thread signals the condition just before the first thread actually waits on it (as explained from the man page on pthread_cond_wait ). Notice how a while loop is used instead of an if statement for the pthread_cond_wait() call. This is because of spurious wakeups problem mentioned previously. If a thread has been woken, it does not mean it was due to a pthread_cond_signal() or pthread_cond_broadcast() call. pthread_cond_wait() if awoken, automatically tries to re-acquire the mutex, and will block if it cannot. Locks that other threads could be waiting on should be released before you signal or broadcast.
pthread Barrier.
pthreads can participate in a barrier to synchronize to some point in time. Before a barrier can be called, a pthread barrier object must be initialized first:
Barrier objects are initialized like mutexes or condition variables, except there is one additional parameter, count . The count variable defines the number threads that must join the barrier for the barrier to reach completion and unblock all threads waiting at the barrier. If default barrier attributes are used (i. e. NULL for the second parameter), one can use the initializer macro with the specified count .
This function would be inside thread code where the barrier is to take place. Once count number of threads have called pthread_barrier_wait() then the barrier condition is met and all threads are unblocked and progress continues.
Diversos.
Here are some suggestions and issues you should consider when using pthreads:
You should check all return values for important pthread function calls! Sometimes it is desirable for a thread not to terminate (e. g., a server with a worker thread pool). This can be solved by placing the thread code in an infinite loop and using condition variables. Of course, there needs to be some terminating condition(s) to the infinite loop (i. e., break when it is deemed necessary).
Additional useful pthread calls:
pthread_kill() can be used to deliver signals to specific threads. pthread_self() returns a handle on the calling thread. pthread_equal() compares for equality between two pthread ids pthread_once() can be used to ensure that an initializing function within a thread is only run once. There are many more useful functions in the pthread library. Consult pthreads man pages or the Nichols text (Appendix C).
Performance Considerations.
The performance gains from using threads can be substantial when done properly and in the right problem context, but can it be even better? You should consider the following when analyzing your program for potential bottlenecks:
Lock granularity - How "big" (coarse) or "small" (fine) are your mutexes? Do they lock your whole structure or fields of a structure? The more fine-grained you make your locks, the more concurrency you can gain, but at the cost of more overhead and potential deadlocks. Lock ordering - Make sure your locks are always locked in an agreed order (if they are not, make sure you take steps to rectify situations where locks are obtained in an out-of-order fashion, e. g. by using trylock/unlock calls). Lock frequency - Are you locking too often? Locking at unnecessary times? Reduce such occurences to fully exploit concurrency and reduce synchronization overhead. Critical sections - This has been mentioned before, but you should take extra steps to minimize critical sections which can be potentially large bottlenecks. Worker thread pool - If you are using a Boss/Worker thread model, make sure you pre-allocate your threads instead of creating threads on demand. It doesn't matter to the user how long it took your server to initialize, it only matters how fast it processes his or her request! Contention scope - Do your threads perform better when they are in contention with all of the system's processes? Or do they perform better when individually scheduled by the thread library itself? Only experimentation can give you the answers. Scheduling class - We have not touched on this topic, but changing the thread scheduling class from FIFO to RR can give better response times. Mas isso é o que você realmente quer? Refer to Nichols or Lewis book for more information on thread scheduling classes. Too many threads? - At what point are there too many threads? Can it serverely impact and degrade performance? Again, only experimentation will give you the real answers to this question.
Other Approaches.
C++ Template Libraries.
There are various template libraries available that ease implementation of multithreading in a (semi-)portable fashion. For those programming in C++, you may want to look at Boost, Intel Threading Building Blocks (TBB) and POCO.
Multiprocess and Shared Memory.
This tutorial has explored the very basics of multithreaded programming. What about multiprocess programming?
OpenMP is a portable interface for implementing fork-join parallelism on shared memory multi-processor machines. It is available for C/C++ and Fortran. For a quick introduction, please see the slides here.
The Message Passing Interface (MPI) is the de-facto standard for distributed memory parallel processing. Data can be sent/received from distinct computing machines with support for vectored I/O (scatter/gather), synchronization and collectives.
It is difficult to cover more than an introduction to threads with this short tutorial and overview. For more in-depth coverage on threads (like thread scheduling classes, thread-specific data (thread local storage), thread canceling, handling signals and reader/writer locks) and pthreads programming, I recommend these books:
Lewis, Bill and Daniel J. Berg. Multithreaded Programming with Pthreads . California: Prentice Hall, 1998. Nichols, Bradford, et. al. Pthreads Programming . Beijing: O'Reilly & Associates, Inc., 1998.
There are many excellent online resources regarding pthreads on the web. Use your favorite search engine to find these.
Notice: Please do not replicate or copy these pages and host them elsewhere. This is to ensure that the latest version can always be found here.
Capítulo 11 & # xA0; & # x2013; & # xAA; Opções de engenharia com aplicativos.
Este capítulo baseia-se na discussão anterior sobre precificação de opções e apresenta aplicativos de engenharia de opções. Primeiro, discutimos como as opções podem ser usadas para criar posições de ações sintéticas. Derivamos o teorema da paridade de put-call e apresentamos estratégias de arbitragem que podem resultar de sua violação. O capítulo explica as estratégias de aprimoramento de rendimento, como sobrescrita de chamadas. Passando para estratégias baseadas em volatilidade, discutimos estratégias de opções como straddles e estrangulamentos, bem como inversões de risco. Finalmente, apresentamos opções exóticas, como opções de barreira, opções de knock-in e knock-out e estratégias de borboleta, e explicamos como elas são relacionadas e precificadas em relação às opções de compra e venda simples de baunilha. Discutimos as estratégias de negociação relacionadas a opções e riscos exóticos, como o risco de alfinete.
opções de barreira; borboletas; chamar sobrescrevendo; opções de knock-in e knock-out; risco de alfinete; paridade de put-call; reversões de risco.
Direitos autorais & copy; 2015 Elsevier Inc. Todos os direitos reservados.
No comments:
Post a Comment