Beispiel #1
0
void PhVideoDecoder::decodeFrame()
{
	if(!ready()) {
		PHDBG(24) << "not ready";
		return;
	}

	if (_requestedFrames.empty()) {
		// all pending requests have been cancelled
		return;
	}

	// now proceed with the first requested frame
	PhVideoBuffer *buffer = _requestedFrames.takeFirst();
	PhFrame frame = buffer->requestFrame();

	// resize the buffer if needed
	int bufferSize = avpicture_get_size(AV_PIX_FMT_BGRA, width(), height());
	if(bufferSize <= 0) {
		PHERR << "avpicture_get_size() returned" << bufferSize;
		return;
	}
	buffer->reuse(bufferSize);

	// clip to stream boundaries
	if(frame < 0)
		frame = 0;
	if (frame >= this->frameLength())
		frame = this->frameLength();

	// Stay with the same frame if the time has changed less than the time between two frames
	// Note that av_seek_frame will seek to the _closest_ frame, sometimes a little bit in the "future",
	// so it is necessary to use a little margin for the second comparison, otherwise a seek may
	// be performed on each call to decodeFrame
	if (frame == _currentFrame) {
		frameToRgb(_videoFrame, buffer);
		return;
	}

	// we need to perform a frame seek if the requested frame is:
	// 1) in the past
	// 2) after the next keyframe
	//      how to know when the next keyframe is ??
	//      -> for now we take a arbitrary threshold of 20 frames
	if((frame < _currentFrame) || (frame >= _currentFrame + 20)) {
		// seek to the closest keyframe in the past
		int flags = AVSEEK_FLAG_BACKWARD;
		int64_t timestamp = PhFrame_to_AVTimestamp(frame);
		PHDBG(24) << "seek:" << buffer << " " << _currentFrame << " " << frame - _currentFrame << " " << timestamp;
		av_seek_frame(_formatContext, _videoStream->index, timestamp, flags);

		avcodec_flush_buffers(_videoStream->codec);
	}

	AVPacket packet;

	bool lookingForVideoFrame = true;
	while(lookingForVideoFrame) {
		int error = av_read_frame(_formatContext, &packet);
		switch(error) {
		case 0:
			if(packet.stream_index == _videoStream->index) {
				int frameFinished = 0;
				avcodec_decode_video2(_videoStream->codec, _videoFrame, &frameFinished, &packet);
				if(frameFinished) {
					// update the current position of the engine
					// (Note that it is best not to do use '_currentTime = time' here, because the seeking operation may
					// not be 100% accurate: the actual time may be different from the requested time. So a time drift
					// could appear.)
					_currentFrame = AVTimestamp_to_PhFrame(av_frame_get_best_effort_timestamp(_videoFrame));

					PHDBG(24) << frame << _currentFrame;

					if (frame < _currentFrame) {
						// something went wrong with the seeking
						// this is not going to work! we cannot go backward!
						// the loop will go until the end of the file, which is bad...
						// So stop here and just return what we have.
						PHERR << "current video time is larger than requested time... returning current frame!";
						frameToRgb(_videoFrame, buffer);
						lookingForVideoFrame = false;
					}

					// convert and emit the frame if this is the one that was requested
					if (frame == _currentFrame) {
						PHDBG(24) << "decoded!";
						frameToRgb(_videoFrame, buffer);
						lookingForVideoFrame = false;
					}
				} // if frame decode is not finished, let's read another packet.
			}
			else if(_audioStream && (packet.stream_index == _audioStream->index)) {
				int ok = 0;
				avcodec_decode_audio4(_audioStream->codec, _audioFrame, &ok, &packet);
				if(ok) {
					PHDBG(24) << "audio:" << _audioFrame->nb_samples;
				}
			}
			break;
		case AVERROR_INVALIDDATA:
		case AVERROR_EOF:
		default:
			{
				char errorStr[256];
				av_strerror(error, errorStr, 256);
				PHDBG(24) << frame << "error:" << errorStr;
				lookingForVideoFrame = false;
				break;
			}
		}

		//Avoid memory leak
		av_free_packet(&packet);
	}
}
Beispiel #2
0
static bool 
chanrecv ( ChanType *t , Hchan* c , byte *ep , bool block , bool *received ) 
{ 
SudoG *sg; 
SudoG mysg; 
G *gp; 
int64 t0; 
#line 214 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( debug ) 
runtime·printf ( "chanrecv: chan=%p\n" , c ) ; 
#line 217 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c == nil ) { 
USED ( t ) ; 
if ( !block ) 
return false; 
runtime·park ( nil , nil , "chan receive (nil chan)" ) ; 
return false; 
} 
#line 225 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
t0 = 0; 
mysg.releasetime = 0; 
if ( runtime·blockprofilerate > 0 ) { 
t0 = runtime·cputicks ( ) ; 
mysg.releasetime = -1; 
} 
#line 232 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
runtime·lock ( c ) ; 
if ( c->dataqsiz > 0 ) 
goto asynch; 
#line 236 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c->closed ) 
goto closed; 
#line 239 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sg = dequeue ( &c->sendq ) ; 
if ( sg != nil ) { 
if ( raceenabled ) 
racesync ( c , sg ) ; 
runtime·unlock ( c ) ; 
#line 245 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( ep != nil ) 
c->elemtype->alg->copy ( c->elemsize , ep , sg->elem ) ; 
gp = sg->g; 
gp->param = sg; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
#line 253 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( received != nil ) 
*received = true; 
return true; 
} 
#line 258 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( !block ) { 
runtime·unlock ( c ) ; 
return false; 
} 
#line 263 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
mysg.elem = ep; 
mysg.g = g; 
mysg.selectdone = nil; 
g->param = nil; 
enqueue ( &c->recvq , &mysg ) ; 
runtime·parkunlock ( c , "chan receive" ) ; 
#line 270 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( g->param == nil ) { 
runtime·lock ( c ) ; 
if ( !c->closed ) 
runtime·throw ( "chanrecv: spurious wakeup" ) ; 
goto closed; 
} 
#line 277 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( received != nil ) 
*received = true; 
if ( mysg.releasetime > 0 ) 
runtime·blockevent ( mysg.releasetime - t0 , 2 ) ; 
return true; 
#line 283 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
asynch: 
if ( c->qcount <= 0 ) { 
if ( c->closed ) 
goto closed; 
#line 288 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( !block ) { 
runtime·unlock ( c ) ; 
if ( received != nil ) 
*received = false; 
return false; 
} 
mysg.g = g; 
mysg.elem = nil; 
mysg.selectdone = nil; 
enqueue ( &c->recvq , &mysg ) ; 
runtime·parkunlock ( c , "chan receive" ) ; 
#line 300 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
runtime·lock ( c ) ; 
goto asynch; 
} 
#line 304 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
runtime·raceacquire ( chanbuf ( c , c->recvx ) ) ; 
runtime·racerelease ( chanbuf ( c , c->recvx ) ) ; 
} 
#line 309 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( ep != nil ) 
c->elemtype->alg->copy ( c->elemsize , ep , chanbuf ( c , c->recvx ) ) ; 
c->elemtype->alg->copy ( c->elemsize , chanbuf ( c , c->recvx ) , nil ) ; 
if ( ++c->recvx == c->dataqsiz ) 
c->recvx = 0; 
c->qcount--; 
#line 316 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sg = dequeue ( &c->sendq ) ; 
if ( sg != nil ) { 
gp = sg->g; 
runtime·unlock ( c ) ; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
} else 
runtime·unlock ( c ) ; 
#line 326 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( received != nil ) 
*received = true; 
if ( mysg.releasetime > 0 ) 
runtime·blockevent ( mysg.releasetime - t0 , 2 ) ; 
return true; 
#line 332 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
closed: 
if ( ep != nil ) 
c->elemtype->alg->copy ( c->elemsize , ep , nil ) ; 
if ( received != nil ) 
*received = false; 
if ( raceenabled ) 
runtime·raceacquire ( c ) ; 
runtime·unlock ( c ) ; 
if ( mysg.releasetime > 0 ) 
runtime·blockevent ( mysg.releasetime - t0 , 2 ) ; 
return true; 
} 
Beispiel #3
0
static bool 
chansend ( ChanType *t , Hchan *c , byte *ep , bool block , void *pc ) 
{ 
SudoG *sg; 
SudoG mysg; 
G* gp; 
int64 t0; 
#line 82 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) 
runtime·racereadobjectpc ( ep , t->elem , runtime·getcallerpc ( &t ) , chansend ) ; 
#line 85 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c == nil ) { 
USED ( t ) ; 
if ( !block ) 
return false; 
runtime·park ( nil , nil , "chan send (nil chan)" ) ; 
return false; 
} 
#line 93 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( debug ) { 
runtime·printf ( "chansend: chan=%p; elem=" , c ) ; 
c->elemtype->alg->print ( c->elemsize , ep ) ; 
runtime·prints ( "\n" ) ; 
} 
#line 99 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
t0 = 0; 
mysg.releasetime = 0; 
if ( runtime·blockprofilerate > 0 ) { 
t0 = runtime·cputicks ( ) ; 
mysg.releasetime = -1; 
} 
#line 106 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
runtime·lock ( c ) ; 
if ( raceenabled ) 
runtime·racereadpc ( c , pc , chansend ) ; 
if ( c->closed ) 
goto closed; 
#line 112 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c->dataqsiz > 0 ) 
goto asynch; 
#line 115 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sg = dequeue ( &c->recvq ) ; 
if ( sg != nil ) { 
if ( raceenabled ) 
racesync ( c , sg ) ; 
runtime·unlock ( c ) ; 
#line 121 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
gp = sg->g; 
gp->param = sg; 
if ( sg->elem != nil ) 
c->elemtype->alg->copy ( c->elemsize , sg->elem , ep ) ; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
return true; 
} 
#line 131 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( !block ) { 
runtime·unlock ( c ) ; 
return false; 
} 
#line 136 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
mysg.elem = ep; 
mysg.g = g; 
mysg.selectdone = nil; 
g->param = nil; 
enqueue ( &c->sendq , &mysg ) ; 
runtime·parkunlock ( c , "chan send" ) ; 
#line 143 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( g->param == nil ) { 
runtime·lock ( c ) ; 
if ( !c->closed ) 
runtime·throw ( "chansend: spurious wakeup" ) ; 
goto closed; 
} 
#line 150 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( mysg.releasetime > 0 ) 
runtime·blockevent ( mysg.releasetime - t0 , 2 ) ; 
#line 153 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
return true; 
#line 155 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
asynch: 
if ( c->closed ) 
goto closed; 
#line 159 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c->qcount >= c->dataqsiz ) { 
if ( !block ) { 
runtime·unlock ( c ) ; 
return false; 
} 
mysg.g = g; 
mysg.elem = nil; 
mysg.selectdone = nil; 
enqueue ( &c->sendq , &mysg ) ; 
runtime·parkunlock ( c , "chan send" ) ; 
#line 170 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
runtime·lock ( c ) ; 
goto asynch; 
} 
#line 174 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
runtime·raceacquire ( chanbuf ( c , c->sendx ) ) ; 
runtime·racerelease ( chanbuf ( c , c->sendx ) ) ; 
} 
#line 179 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
c->elemtype->alg->copy ( c->elemsize , chanbuf ( c , c->sendx ) , ep ) ; 
if ( ++c->sendx == c->dataqsiz ) 
c->sendx = 0; 
c->qcount++; 
#line 184 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sg = dequeue ( &c->recvq ) ; 
if ( sg != nil ) { 
gp = sg->g; 
runtime·unlock ( c ) ; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
} else 
runtime·unlock ( c ) ; 
if ( mysg.releasetime > 0 ) 
runtime·blockevent ( mysg.releasetime - t0 , 2 ) ; 
return true; 
#line 197 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
closed: 
runtime·unlock ( c ) ; 
runtime·panicstring ( "send on closed channel" ) ; 
return false; 
} 
static void service_change_handler(BTDevice device,
                                   const BLEService services[],
                                   uint8_t num_services,
                                   BTErrno status) {

	// out with the old...
  node_ctx.node_service_1_characteristic = BLE_CHARACTERISTIC_INVALID;
  node_ctx.node_command_characteristic = BLE_CHARACTERISTIC_INVALID;
  node_ctx.node_service_4_characteristic = BLE_CHARACTERISTIC_INVALID;
  node_ctx.node_service_6_characteristic = BLE_CHARACTERISTIC_INVALID;
  
  for (uint8_t i = 0; i < num_services; ++i) {
    Uuid service_uuid = ble_service_get_uuid(services[i]);

		const Uuid node_service_uuid = 
								UuidMake(0xda, 0x2b, 0x84, 0xf1, 0x62, 0x79, 0x48, 0xde,
												 0xbd, 0xc0, 0xaf, 0xbe, 0xa0, 0x22, 0x60, 0x79);

    if (!uuid_equal(&service_uuid, &node_service_uuid)) {
      // Not the Bean's "Scratch Service"
      continue;
    }
    
    char uuid_buffer[UUID_STRING_BUFFER_LENGTH];
    uuid_to_string(&service_uuid, uuid_buffer);
    const BTDeviceAddress address = bt_device_get_address(device);
    APP_LOG(APP_LOG_LEVEL_INFO,
            "Discovered Node+ service %s (0x%08x) on " BT_DEVICE_ADDRESS_FMT,
            uuid_buffer,
            services[i],
            BT_DEVICE_ADDRESS_XPLODE(address));

    // Iterate over the characteristics within the "Scratch Service":
    BLECharacteristic characteristics[6];
    uint8_t num_characteristics =
    ble_service_get_characteristics(services[i], characteristics, 8);
    if (num_characteristics > 6) {
      num_characteristics = 6;
    }
    for (uint8_t c = 0; c < num_characteristics; ++c) {
      Uuid characteristic_uuid = ble_characteristic_get_uuid(characteristics[c]);

      // The characteristic UUIDs we're looking for:
      const Uuid node_service_1_uuid =
            UuidMake(0xa8, 0x79, 0x88, 0xb9, 0x69, 0x4c, 0x47, 0x9c,
                     0x90, 0x0e, 0x95, 0xdf, 0xa6, 0xc0, 0x0a, 0x24);
      const Uuid node_command_uuid =
            UuidMake(0xbf, 0x03, 0x26, 0x0c, 0x72, 0x05, 0x4c, 0x25,
            				 0xaf, 0x43, 0x93, 0xb1, 0xc2, 0x99, 0xd1, 0x59);
      const Uuid node_service_4_uuid =
            UuidMake(0x18, 0xcd, 0xa7, 0x84, 0x4b, 0xd3, 0x43, 0x70,
            				 0x85, 0xbb, 0xbf, 0xed, 0x91, 0xec, 0x86, 0xaf);
      const Uuid node_service_6_uuid =
            UuidMake(0xfd, 0xd6, 0xb4, 0xd3, 0x04, 0x6d, 0x43, 0x30, 
            				 0xbd, 0xec, 0x1f, 0xd0, 0xc9, 0x0c, 0xb4, 0x3b);

      uint8_t node_num = 0; // Just for logging purposes
      if (uuid_equal(&characteristic_uuid, &node_service_1_uuid)) {
        // Found node service 1
        node_ctx.node_service_1_characteristic = characteristics[c];
        node_num = 1;
      } else if (uuid_equal(&characteristic_uuid, &node_command_uuid)) {
        // Found node command 
        node_ctx.node_command_characteristic = characteristics[c];
        node_num = 2;
      } else if (uuid_equal(&characteristic_uuid, &node_service_4_uuid)) {
        // Found node command 
        node_ctx.node_service_4_characteristic = characteristics[c];
        node_num = 3;
      } else if (uuid_equal(&characteristic_uuid, &node_service_6_uuid)) {
        // Found node command 
        node_ctx.node_service_6_characteristic = characteristics[c];
        node_num = 4;
      } else {
        continue;
      }

      uuid_to_string(&characteristic_uuid, uuid_buffer);
      APP_LOG(APP_LOG_LEVEL_INFO, "-- Found %u: %s (0x%08x)",
              node_num, uuid_buffer, characteristics[c]);

      // Check if all characteristics are found
      if (node_ctx.node_service_1_characteristic != BLE_CHARACTERISTIC_INVALID &&
          node_ctx.node_command_characteristic != BLE_CHARACTERISTIC_INVALID &&
          node_ctx.node_service_4_characteristic != BLE_CHARACTERISTIC_INVALID &&
          node_ctx.node_service_6_characteristic != BLE_CHARACTERISTIC_INVALID) {
          
          ready();
      }
    }
  }
}
Beispiel #5
0
void ELoginAction::continue1()
{
    disconnect(&s_browser,SIGNAL(ready()),this,SLOT(continue1()));
    s_browser.loadPage("http://www.ontariots.ca//?q=user/login");
    connect(&s_browser,SIGNAL(ready()),this,SLOT(continue2()));
}
Beispiel #6
0
/*!
   called by callback when done reading data
 */
void AudioReaderPortAudio::emitAudioReady()
{
    bptr++;
    bptr = bptr % bpmax;
    emit(ready(buff, bptr));
}
Beispiel #7
0
/* ------------------------------------------------------------------------------*/
void DownloadBot(char *path)
{
	SOCKADDR_IN sin;
	SOCKET s = NULL;
	WSADATA wsaData;
	HANDLE file = NULL;
	int done = 0;
	char buf[BUF_SIZE];
	DWORD bytes = 0,written = 0;
	int iResult;
	char source_file[128];
	char source_host[128];
	char loader_version[255];
	
	strncpy(source_file, SOURCE_FILE, sizeof(source_file));
	strncpy(loader_version, LOADER_VERSION, sizeof(loader_version));
	strncpy(source_host, SOURCE_HOST, sizeof(source_host));

	while(!done) 
	{
		deb("entered download cycle");
		deb("source_host: %s", source_host);
		deb("loader_version: %s", loader_version);
		deb("source_file: %s", source_file);

		Sleep(100);
		if(file && file != INVALID_HANDLE_VALUE)
			CloseHandle(file);

		if(s && s != INVALID_SOCKET)
			closesocket(s);

		file = CreateFile(path,GENERIC_ALL,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		if(file == INVALID_HANDLE_VALUE) 
		{
			deb("DownloadFile: failed to create file %s\n", fmterr());
			continue;
		}
		iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

		sin.sin_family = AF_INET;
		sin.sin_port = htons(SOURCE_PORT);

		if(DnsResolve(source_host) == -1)
			continue;
		
		sin.sin_addr.s_addr = DnsResolve(source_host);

		s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (s == INVALID_SOCKET) 
		{
			deb("socket: %s", fmterr());
			continue;
		}

		if(connect( s, (SOCKADDR*) &sin, sizeof(sin) ) == SOCKET_ERROR) 
		{

			deb("connect: %s\n",fmterr());
			continue;
		}
		wsprintf(buf,"GET %s HTTP/1.0\r\n"
			     "User-Agent: %s\r\n"
			     "Host: %s\r\n\r\n",source_file, loader_version, source_host);

		int res = send(s,buf,lstrlen(buf),0);
		if(res == SOCKET_ERROR) 
		{
			deb("res == SOCKET_ERROR after send()");
			continue;
		}

		int code = GetHTTPRespCode(s);
		if(code != 200) 
		{
			deb("code: %d",code);
			continue;
		}
		while(ready(s,HTTP_TIMEOUT) == 0) 
		{
			res = recv(s,buf,BUF_SIZE,0);

			if(res == SOCKET_ERROR)
				break;

			if(res == 0)
			{
				done = 1;
				closesocket(s);
				CloseHandle(file);
				break;
			}

			bytes += res;

			WriteFile(file,buf,res,&written,NULL);

			if(written != (DWORD) res)
				break;
		}
	}
	deb("done. read %lu bytes.\n",bytes);
}
Beispiel #8
0
int main(int argc, char **argv)
{
    srand(time(NULL));
    int rank, size;

    MPI_Init(&argc, &argv);

    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Status status;

    // lista procesów ubiegających się o trupa
    int U[size];
    // tablica trupów - założyłem 100
    int T[100] = {0};
    // zegar lamporta
    int C = 0;

    int i = 0;
    for (i = 0; i < size; i++)
        U[i] = 0;


    while(!ready(T, 100))
    {
        int trup_id = rand() % 100; 
        printf("rank %d: chce %d", rank, trup_id);
        int message[MSG_LENGTH] = { rank, PROCESSED, trup_id, C };
        
        sendAllInU(message, size, U, rank, C);
        U[rank] = 1;
        T[trup_id] = 1;

        int status = 0;

        do
        {
            int response[4];
            MPI_Recv( &response, MSG_LENGTH, MPI_INT, MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            C = MAX(C, response[3]);
            printf("rank %d: dostałem od %d, trup_id: %d, C=%d\n", rank, response[0], response[2], response[3]);

            if ((response[2] == trup_id) && (response[0] < rank))
            {
                status = 1;
                break;
            }
            else if (response[1] == BURIED)
            {
                U[response[0]] = -1;
                T[response[2]] = BURIED;
            }
            else if (response[1] == BACK)
            {
                U[response[0]] = 0;
            }
            else 
            {
                T[response[2]] = PROCESSED;
                U[response[0]] = 1;
            }
        }
        while (!readyU(U,size));

        if (status)
            continue;

        C++;
        int request[4] = {
            rank, BURIED, trup_id, C
        };
        broadcast(request, size, rank, C);
        sleep(2); 
        int flag;
        MPI_Request req;
        MPI_Status stat;
        int response[4];
        do
        {
            MPI_Irecv( &response, MSG_LENGTH, MPI_INT, MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, &req);
            MPI_Test(&req, &flag, &stat);
        }
        while (flag);
    }
    MPI_Finalize();
}
Beispiel #9
0
void Game::message_handler(Server& server, int player, std::string msg)
{
    std::vector<std::string> words;
    boost::trim(msg);
    boost::split(words, msg, boost::is_any_of("\t "), boost::token_compress_on);

    if (words.empty()) {
        error(server, player);
        return;
    }

    if (words[0] == "ready") {
        if (ready(player)) {
            error(server, player);
            return;
        }

        ready(player) = true;
        player_color(player) = ready(other(player)) ? BLACK : WHITE;
        server.send(player, "color " + show(player_color(player)));

        if (ready1 && ready2) {
            reset_playing();
            server.broadcast("start");
        }
    } else if (words[0] == "say") {
        std::stringstream ss;
        ss << "say" << player;
        for (size_t i = 1; i < words.size(); ++i) {
            ss << " " << words[i];
        }
        server.broadcast(ss.str());
    } else if (words[0] == "move") {
        if (!playing || current_color != player_color(player) ||
            words.size() != 3) {
            server.send(player, "error move");
            return;
        }

        boost::optional<Square> maybe_from = read_square(words[1]);
        boost::optional<Square> maybe_to = read_square(words[2]);
        if (!maybe_from || !maybe_to) {
            error(server, player);
            return;
        }

        boost::optional<MoveResult> maybe_move_result =
            try_move(board, player_color(player), *maybe_from, *maybe_to);
        if (!maybe_move_result) {
            server.send(player, "error move");
            return;
        }

        current_color = current_color == WHITE ? BLACK : WHITE;
        if (maybe_move_result->opponent_cannot_move) {
            reset_waiting();
        }

        server.broadcast(show(*maybe_move_result));
    } else if (words[0] == "resign") {
        if (!playing || current_color != player_color(player)) {
            error(server, player);
            return;
        }

        reset_waiting();
        server.broadcast("resign");
    } else {
        error(server, player);
    }
}
Beispiel #10
0
/*
 *  create the first process
 */
void
userinit(void)
{
	Proc *p;
	Segment *s;
	KMap *k;
	Page *pg;

	/* no processes yet */
	up = nil;

	p = newproc();
	p->pgrp = newpgrp();
	p->egrp = smalloc(sizeof(Egrp));
	p->egrp->ref = 1;
	p->fgrp = dupfgrp(nil);
	p->rgrp = newrgrp();
	p->procmode = 0640;

	kstrdup(&eve, "");
	kstrdup(&p->text, "*init*");
	kstrdup(&p->user, eve);

	/*
	 * Kernel Stack
	 */
	p->sched.pc = PTR2UINT(init0);
	p->sched.sp = PTR2UINT(p->kstack+KSTACK-sizeof(up->s.args)-sizeof(uintptr));
	p->sched.sp = STACKALIGN(p->sched.sp);

	/*
	 * User Stack
	 *
	 * Technically, newpage can't be called here because it
	 * should only be called when in a user context as it may
	 * try to sleep if there are no pages available, but that
	 * shouldn't be the case here.
	 */
	s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
	p->seg[SSEG] = s;
	pg = newpage(1, 0, USTKTOP-BY2PG);
	segpage(s, pg);
	k = kmap(pg);
	bootargs(VA(k));
	kunmap(k);

	/*
	 * Text
	 */
	s = newseg(SG_TEXT, UTZERO, 1);
	s->flushme++;
	p->seg[TSEG] = s;
	pg = newpage(1, 0, UTZERO);
	memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
	segpage(s, pg);
	k = kmap(s->map[0]->pages[0]);
	memmove(UINT2PTR(VA(k)), initcode, sizeof initcode);
	kunmap(k);

	ready(p);
}
Beispiel #11
0
int GnuPGConnector::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDeclarativeItem::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: ready(); break;
        case 1: errorOccured(); break;
        case 2: gpgFinished((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 3: gpgError((*reinterpret_cast< QProcess::ProcessError(*)>(_a[1]))); break;
        case 4: { QString _r = encrypt((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 5: { QString _r = decrypt((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 6: { QString _r = showKeys();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 7: { QString _r = showSecretKeys();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 8: { QString _r = getData((*reinterpret_cast< bool(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 9: { QString _r = getFromClipboard();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 10: setToClipboard((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 11: { QString _r = getKey((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 12: { QString _r = getKey((*reinterpret_cast< int(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 13: { QString _r = getKeyByID((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 14: { QString _r = getPrivateKeyIDs((*reinterpret_cast< bool(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 15: { QString _r = getPrivateKeyIDs();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 16: { int _r = getNumOfPubKeys((*reinterpret_cast< int(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;
        case 17: { int _r = getNumOfPubKeys();
            if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;
        case 18: { bool _r = generateKeyPair((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 19: { bool _r = setOwnerTrust((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 20: { bool _r = checkGPGVersion((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 21: { QString _r = getGPGVersionString();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 22: { bool _r = importKeysFromFile((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 23: { bool _r = importKeysFromClipboard();
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 24: { bool _r = searchKeysOnKeyserver((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 25: { bool _r = importKeysFromKeyserver((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 26: { bool _r = deleteKey((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 27: { bool _r = signKey((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 28: { bool _r = exportKeys((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 29: { QString _r = getHistory();
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 30: { bool _r = saveHistory((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; }  break;
        case 31: settingsSetValue((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
        case 32: { QString _r = settingsGetValue((*reinterpret_cast< QString(*)>(_a[1])));
            if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; }  break;
        case 33: settingsReset(); break;
        default: ;
        }
        _id -= 34;
    }
    return _id;
}
Beispiel #12
0
void docommand(char ch)
{
int count;
char dateb[7];
switch (ch)
       	{
	 case ARROWR : if (status.stockprice != 3 + 1) exit(0);goright(); break;
         case ARROWL : if (status.stockprice != 5 - 1) exit(0);goleft(); break;
	 case ARROWU : if (status.stockprice != 2 + 2) exit(0);goup(); break;
	 case ARROWD : if (status.stockprice != 3 + 1) exit(0);godown(); break;
	 case HOME :  leavecell(sys.cell);
		     if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			  && page == PAGEDOWN)
		     {
		     sys.cell.row = 23;
		     sys.cell.col = MONTH;
		     }
		     else
                     if (sys.screen == SCREEN2)
		     {
		     sys.cell.row = 8;
		     sys.cell.col = SHARESPER;
		     }
		     else
		     {
		     sys.cell.row = 8;
		     sys.cell.col = MONTH;
		     }
		     entercell(sys.cell);
		     break;
	 case END :  leavecell(sys.cell);
		     if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			  && page == PAGEDOWN)
		     {
		     sys.cell.row = 37;
		     sys.cell.col = MONTH;
		     }
		     else
                     if (sys.screen == SCREEN2)
		     {
		     sys.cell.row = 22;
		     sys.cell.col = SHARESPER;
		     }
		     else
		     {
		     sys.cell.row = 22;
		     sys.cell.col = MONTH;
		     }
		     entercell(sys.cell);
		     break;

	 case PGUP	: if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			      && page == PAGEDOWN)
			{
			page = PAGEUP;
			if (sys.cell.row >= 8)
			sys.cell.row -= 15;
			disppage();
			}
			showall();
			entercell(sys.cell);
			break;
	 case PGDN	: if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
				&& page == PAGEUP)
			{
			page = PAGEDOWN;
			if (sys.cell.row >= 8)
			sys.cell.row += 15;
                        disppage();
			}
			showall();
			entercell(sys.cell);
			break;
         case F01 :	help();break;
         case F02 :     demo();
			break;
	 case F03 :     demo();
			break;
         case F04 : sortstatus(); genscreen(); entercell(sys.cell); break;
         case F05 :
		{
		    if (drawgraph(choice(6,graphchoice)) < 0)
		    errormessage("Graphics initialisation error");
		    genscreen();
		    showtotals();
		    entercell(sys.cell);
		 }
		    break;
         case F06 :
         	    leavecell(sys.cell);
		 switch (choice(3,screenchoice))
		 {
 		 case 1 :
		      if (tosavesys) savesys();
		      sys.screen = SCREEN1;
		      page = PAGEUP;
		      sys.cell.col = MONTH;
      		      sys.cell.row = 8;
		      sys.display = HELDS;
		      genscreen();
		      break;
		 case 2 :
		      sys.screen = SCREEN2;
		      sys.display = HELDS;
		      page = PAGEUP;
      		      sys.cell.row = 8;
		      sys.cell.col = EXPIRYDAY;
		      genscreen();
		      break;
		 case 3 :
		      if (tosavesys) savesys();
		      sys.cell.col = MONTH;
		      page = PAGEUP;
		      sys.screen = SCREEN3;
		      sys.display = INVVOL;
      		      sys.cell.row = 8;
		      wait();
		      if (recalcvolvalues)
		      calcallvol();
		      ready();
		      genscreen();
		      break;
		 }
		 showtotals();
		 entercell(sys.cell);
		 break;
            case F07 :
		   switch(choice(3,clearchoice))
		   {
		  case 1 :  if (sys.cell.row < 8 || sys.screen == SCREEN2) break;
			    wait();
			    clearrow();
				 calcall();
				 showall();
				 totals();
                              entercell(sys.cell);
			      break;
		   case 2 : wait();
			    switch( sys.cell.col)
			    {
                            case VOLC :
                            	case VALUEC :
				case VOLP :
				case DELTAC :
				case VALUEP :
                            	case DELTAP:
                            	case SHAREPRICE :break;
				case STOCKHELD : status.stockheld = 0; break;
				case VOLATILITY : status.volatility = 0.0;break;
				case INTEREST   : status.interest = 0.0; break;
				case  DATE      :
				case YEARMONTH :
				case SHARESPER : for (count =0;count <24; count++)
						   status.sizepay[count].sharesper = 1000;
						   break;               
				case EXPIRYDAY :
				case DAYSLEFT :
                            case MONTH : break;
                            case STRIKE : for (count = 0;count < 30; count++)
                                          {
					  status.data[count].strike = 0.0;
					  status.data[count].volc = 0.0;
					  status.data[count].volp = 0.0;
					  }
					  break;
				case MARKETC : for (count = 0;count < 30; count++)
                                        {
					status.data[count].marketc = 0.0;
					status.data[count].volc = 0.0;
					}
					  break;
				case HELDC :  for (count = 0;count < 30; count++)
					  status.data[count].heldc = 0;
					  break;
				case MARKETP : for (count = 0;count < 30; count++)
                                          {
					  status.data[count].marketp = 0.0;
					  status.data[count].volp = 0.0;
					  }
					  break;
				case HELDP :  for (count = 0;count < 30; count++)
					  status.data[count].heldp = 0;
					  break;
				case DIVIDENDDAY : for (count = 0;count < 24; count++)
					  status.sizepay[count].dday = 0;
					  break;
			        case DIVIDENDCENTS :  for (count = 0;count < 24; count++)
					  status.sizepay[count].payout = 0;
					  break;

			    }  wait();
				 calcall();
				 showall();
				 totals();  break;
			  case 3:   clearall();wait();   wait();
				 calcall();
				 showall();
				 totals();break;
			  /* clear all set shares per con */


		    }           showtotals();
				 ready();
				 entercell(sys.cell);
				 /* inverse vol now invalid */
		    break;


         case F08 :
			leavecell(sys.cell);
		   switch( choice(7, utilchoice))
		      {
			case 1 : getdir(); break;
			case 2 : bonusissue();
				 wait();
				 calcall();
				 showall();
				 totals();
				 showtotals();
				 ready();
				 break;
			case 3 : cashissue();
				 wait();
				 calcall();
				 showall();
				 totals();
				 showtotals();
				 ready();
				 break;
			 case 4: switch( choice(3,resolutionchoice))
				 {
				   case 1: numpts = 10; break;
				   case 2: numpts = 15; break;
				   case 3: numpts = 30; break;
				 }
                                    break;
			 case 5:switch (choice(3,printchoice))
				  {
				     case 1: printdetails(); break;
				     case 2: demo1();break;
				     case 3: demo1(); break;
					   } break;
			 case 6: filedelete(); break;
			 case 7 : reinstall();
		         }
			 entercell(sys.cell);
			 break;

         case F09 : switch (sys.screen)
			{
			case SCREEN1 :
			    leavecell(sys.cell);
			    if (sys.display == HELDS) sys.display = DELTAS;
			    else sys.display = HELDS;
		    	if (sys.cell.row >= 8)
		   	 sys.cell.col = MONTH;
		    	textcolor(sys.graphics.colors.heading);
		    	textbackground(sys.graphics.colors.databack);
		    	drawheadings();
		    	showall();
			showtotals();
		    	entercell(sys.cell);break;
			case SCREEN2 : break;
			case SCREEN3 :
			    leavecell(sys.cell);
			    if (sys.display == INVVOL) sys.display = OVERVALUED;
			    else sys.display = INVVOL;
 		    	    textcolor(sys.graphics.colors.heading);
		    	    textbackground(sys.graphics.colors.databack);
		    	    drawheadings();
		    	    showall();
			    showtotals();
		    	    entercell(sys.cell);break;
		       }
		    break;
         case F10 : switch (choice(3,quitchoice))
		    {
		    case 0 : break;
		    case 1 : wait();
	   		    textcolor(LIGHTGRAY);
			    textbackground(BLACK);
			    savesys();
			    clrscr();
			    gotoxy(2,2);
			    cprintf(" The Option Analyst is a product of");
			    gotoxy(2,3);
			    cprintf(" EFAM RESOURCES Pty. Ltd.\n");
			    retcursor();
			    exit(0);
			    break;
                    case 2 : demo();
			    break;
		    case 3 : break;
		    }
		    break;
	}
}
Beispiel #13
0
char editcell(celltype cell)
{
int x,y;
long z;
char ch;
char sharestring[12];
int  pageint;
if (page == PAGEUP || sys.screen == SCREEN2 || cell.row < 8) pageint = 0;
else pageint = 15;
x = endcell(cell.col)-1;
y = cell.row - pageint ;

   switch (cell.col)
       {case MONTH :  entercell(sys.cell);
		     if (status.data[cell.row-8].month == -1 &&
			 cell.row != 8 )
			 status.data[cell.row-8].month =
			inputmonth(x-2,y,(status.data[cell.row-9].month)-1);
			else
			 status.data[cell.row-8].month =
			inputmonth(x-2,y,status.data[cell.row-8].month);
		     wait();
		     if (sys.screen == SCREEN3) calcvolrow(cell.row);
                     calcrow(cell.row);
		     showrow(cell.row);
		     if ( cell.row != 22 && cell.row != 37)
		     {
		     cell.row += 1;
		     showcell(cell);
		     cell.row = cell.row -1;
		     }
		      /* show date of line below if it
			    had been hidden by showall suppression */
		     break;
	case STRIKE : entercell(sys.cell);
		      if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].strike =
		      inputreal(x,y,status.data[cell.row-8].strike,8,sys.decimal);
		      wait();
		     if (sys.screen == SCREEN3) calcvolrow(cell.row);
		      calcrow(cell.row);
                      showrow(cell.row);
		      break;
	case VALUEC : getch();break;
	case VALUEP : getch();break;
	case HELDC : entercell(sys.cell);
		     if (status.stockprice != 4.0) exit(0);
		     status.data[cell.row-8].heldc =
		     inputinteger(x,y,status.data[cell.row-8].heldc,4);
		     wait();
		     showcell(sys.cell);
		     break;
	case HELDP : entercell(sys.cell);
		     if (status.stockprice != 4.0) exit(0);
		     status.data[cell.row-8].heldp =
		     inputinteger(x,y,status.data[cell.row-8].heldp,4);
		     wait();
		     showcell(sys.cell);
		     break;
	case STOCKHELD :
			entercell(sys.cell);
			z = status.stockheld;
		     z =
		     inputlint(x,y,&z,8);
		     wait();
		     break;
	case SHAREPRICE : entercell(sys.cell);
			status.stockprice = 4.0;
			getch();
			demo();
			getch();
			break;
        case VOLATILITY : entercell(sys.cell);
			status.volatility =
			inputreal(x,y,status.volatility,5,2);
			wait();
			calcall();
			calcalloverval();
			showall();
			break;
        case INTEREST : entercell(sys.cell);
			status.interest=
			inputreal(x,y,status.interest,5,2);
			wait();
			initdivmtx(0);
			calcall();
			if (sys.screen == SCREEN3) calcallvol();
			else recalcvolvalues = TRUE;
			showall();
			break;
        case DATE    : 	entercell(sys.cell);
			inputdate(x,y,sys.date);
			wait();
			initdates();
			initsizepay();
			calcdays();
			initdivmtx(0);
			calcall();
			if (sys.screen == SCREEN3) calcallvol();
			else recalcvolvalues = TRUE;
			showall();
			break;
	case SHARESPER : entercell(sys.cell);
			status.sizepay[y].sharesper=
			inputinteger(x,y,status.sizepay[y].sharesper,4);
                        if (status.sizepay[y].sharesper < 1)
			status.sizepay[y].sharesper = 1;
			wait();
                        break;
	case EXPIRYDAY : entercell(sys.cell);
			sys.expiry[y].eday =inputinteger(x,y,sys.expiry[y].eday,2);
			if (sys.expiry[y].eday < 1) sys.expiry[y].eday = 1;
			else if (sys.expiry[y].eday > 31) sys.expiry[y].eday = 28;
			wait();
			initdates();
			calcdays();
			initdivmtx(0);
			calcall();
			tosavesys = TRUE;
		      	showall();
			break;
	case DIVIDENDDAY : entercell(sys.cell);
			status.sizepay[y].dday=inputinteger(x,y,status.sizepay[y].dday,2);
			if (status.sizepay[y].dday < 0)
			status.sizepay[y].dday = 0;
			else if (status.sizepay[y].dday > 31)
			status.sizepay[y].dday = 28;
			wait();
			calcdays();
			initdivmtx(0);
                        calcall();
			showrow(cell.row);
                        break;
	case DIVIDENDCENTS : entercell(sys.cell);
			status.sizepay[y].payout
			= inputinteger(x,y,status.sizepay[y].payout,3);
			if (status.sizepay[y].payout < 0)
			status.sizepay[y].payout = 0;
			wait();
			initdivmtx(0);
                        calcall();
			showrow(cell.row);
			break;
	case VOLC :     getch();
			break;
	case VOLP :     getch();
			break;
	case MARKETC : entercell(sys.cell);
			if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].marketc =
		      inputreal(x,y,status.data[cell.row-8].marketc,8,sys.decimal);
		      if (status.data[cell.row-8].marketc < 0)
		      status.data[cell.row-8].marketc = 0;
			wait();
			status.data[cell.row-8].volc = invertvolc(cell.row);
			calcoverval(cell.row);
			showrow(cell.row);
			break;
	case MARKETP : entercell(sys.cell);
		      if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].marketp =
		      inputreal(x,y,status.data[cell.row-8].marketp,8,sys.decimal);
		      if (status.data[cell.row-8].marketp < 0)
		      status.data[cell.row-8].marketp = 0;
			wait();
			status.data[cell.row-8].volp = invertvolp(cell.row);
			calcoverval(cell.row);
			showrow(cell.row);
			break;
       }
       entercell(cell);
       totals();
       showtotals();
       if (status.stockprice != 4.0) exit(0);
       ready();
       ch = getch();
       return(ch);
}
Beispiel #14
0
void
kforkexecac(Proc *p, int core, char *ufile, char **argv)
{
	Mach *m = machp();
	Khdr hdr;
	Tos *tos;
	Chan *chan;
	int argc, i, n, sno;
	char *a, *elem, *file, *args;
	int32_t hdrsz, magic, textsz, datasz, bsssz;
	uintptr_t textlim, datalim, bsslim, entry, tbase, tsize, dbase, dsize, bbase, bsize, sbase, ssize, stack;
	Mach *mp;
	//	static Pgrp *kpgrp;

	panic("kexec not done\n");
	// XXX: since this is kernel code we can't do attachimage,
	// we should be reading the file into kernel memory.
	// this only matters if we are using ufile.
	// YYY: look at dev reboot for help.

	file = nil;
	elem = nil;
	chan = nil;
	mp = nil;

	USED(chan);

	if(waserror()){
		DBG("kforkexecac: failing: %s\n", m->externup->errstr);
		if(file)
			free(file);
		if(elem)
			free(elem);
		if(chan)
			cclose(chan);
		if(core > 0 && mp != nil)
			mp->proc = nil;
		if(core != 0)
			p->ac = nil;
		nexterror();
	}

	if(core != 0)
		p->ac = getac(p, core);

	argc = 0;
	if(ufile != nil){
		panic("ufile not implemented yet");
		file = validnamedup(ufile, 1);
		DBG("kforkexecac: up %#p file %s\n", m->externup, file);
		chan = namec(file, Aopen, OEXEC, 0);
		kstrdup(&elem, m->externup->genbuf);

		hdrsz = chan->dev->read(chan, &hdr, sizeof(Khdr), 0);
		DBG("wrote ufile\n");

		if(hdrsz < 2)
			error(Ebadexec);
	}else{
		/* somebody already wrote in our text segment */
		for(sno = 0; sno < NSEG; sno++)
			if(p->seg[sno] != nil)
				if((p->seg[sno]->type & SG_EXEC) != 0)
					break;
		if(sno == NSEG)
			error("kforkexecac: no text segment!");
		hdr = *(Khdr*)p->seg[sno]->base;
		hdrsz = sizeof(Khdr);
	}

//	p = (char*)&hdr;
	magic = l2be(hdr.magic);
	DBG("badexec3\n");

	if(hdrsz != sizeof(Khdr) || magic != AOUT_MAGIC)
		error(Ebadexec);
	if(magic & HDR_MAGIC){
		entry = vl2be(hdr.hdr[0]);
		hdrsz = sizeof(Khdr);
	}
	else{
		entry = l2be(hdr.entry);
		hdrsz = sizeof(Exec);
	}

	textsz = l2be(hdr.text);
	datasz = l2be(hdr.data);
	bsssz = l2be(hdr.bss);

	panic("aki broke it before it even got working.");
/* TODO(aki): figure out what to do with this.
	tbase = p->seg[TSEG]->base;
	tsize = tbase - p->seg[TSEG]->top;
	dbase = p->seg[DSEG]->base;
	dsize = dbase - p->seg[DSEG]->top;
	bbase = p->seg[BSEG]->base;
	bsize = bbase - p->seg[BSEG]->top;
	sbase = p->seg[SSEG]->base;
	ssize = sbase - p->seg[SSEG]->top;
*/

	// XXX: we are no longer contiguous.
	textlim = ROUNDUP(hdrsz+textsz, BIGPGSZ);
	// XXX: we are going to be at least two pages here.
	datalim = BIGPGROUND(datasz);
	bsslim = BIGPGROUND(datalim+bsssz);

	// XXX: this is pretty fragile
	memmove((void*)dbase, (void*)(entry+textsz), datasz);
	DBG("writing data dbase %#p tbase %#p textsz %ld datasz %ld\n", dbase, tbase, textsz, datasz);
//	memmove((void*)dbase, (void*)"testing data", 13);
	/*
	 * Check the binary header for consistency,
	 * e.g. the entry point is within the text segment and
	 * the segments don't overlap each other.
	 */
	// XXX: max instruction size on amd64 is 15 bytes provide a check for consistency.
	DBG("kexec: entry %#p tbase %#p hdrsz %ld  textsz %ld\n", entry, tbase, hdrsz, textsz);
	if(entry < tbase+hdrsz || entry >= tbase+hdrsz+textsz)
		error(Ebadexec);
	// XXX: what about the kernel stack we are making here?
	DBG("kexec: testing if sizes overflow limits\n");
	if(textsz >= textlim || datasz > datalim || bsssz > bsslim)
		error(Ebadexec);
	DBG("kexec: do the top of the segments overflow limits?\n");
	if(textlim >= tbase+tsize || datalim >= dbase+dsize || bsslim >= bbase+bsize)
		error(Ebadexec);

	DBG("kexec: is bss below data?\n");
	if(bsslim < datalim)
		error(Ebadexec);
	/*
	Interesting thought, the previously allocated segments for
	data and text are shared and constant.  The BSS and the stack
	are not.  What you really want is the ability to make an
	executable text and data and then create child executables on
	top of that.  This will lower external fragmentation and allow
	a bunch of communicating shared memory processes (ie.  go) in
	kernel space.

	Fundamentally this means that the allocation of the text and
	the data should be separate from the bss and the stack.  This
	will require that you change the linkers as well to allow the
	separation of data and bss sections.
	*/

	/*
	 * Stack is a pointer into the temporary stack
	 * segment, and will move as items are pushed.
	 */

	 // need to work something out here with the stack.
	stack = sbase+ssize-sizeof(Tos);


	 /*
	  * XXX: When we are linking this how do we set the tos? We will need to change trap right?
	  */
	tos = (Tos*)stack;
	tos->cyclefreq = m->cyclefreq;
	cycles((uint64_t*)&tos->pcycles);
	tos->pcycles = -tos->pcycles;
	tos->kcycles = tos->pcycles;
	tos->clock = 0;

	DBG("kexec: argument processing\n");
	if(0)
	for(i = 0;; i++, argv++){
		a = *(char**)validaddr(argv, sizeof(char**), 0);
		if(a == nil)
			break;
		a = validaddr(a, 1, 0);
		n = ((char*)vmemchr(a, 0, 0x7fffffff) - a) + 1;

		if(argc > 0 && i == 0)
			continue;

		stack -= n;
		if(stack < sbase+ssize-4096)
			error(Enovmem);
		args = UINT2PTR(stack);
		memmove(args, a, n);
		args[n-1] = 0;
		argc++;
	}
	// DBG("kexec: ensuring we have argc\n");
	if(0)
	if(argc < 1)
		error(Ebadexec);

	a = args = UINT2PTR(stack);
	stack = sysexecstack(stack, argc);
	// XXX: look through math on this. look at ../../9/port/ exec.c
	// YYY: this looks like a Jimism for 9k.
	// DBG("kexec: ensuring the stack \n");
	if(0)
	if(stack-(argc+1)*sizeof(char**)-BIGPGSZ < sbase+ssize-4096)
		error(Ebadexec);

	argv = (char**)stack;
	*--argv = nil;
	// XXX: replace USTKTOP with a new variable representing the top of stack.
	if(0)
	for(i = 0; i < argc; i++){
		*--argv = args + (USTKTOP-sbase+ssize);
		args += strlen(args) + 1;
	}

	DBG("argsing\n");
	n = args - a;
	if(0)
	if(n <= 0)
		error(Egreg);
	if(n > 128)
		n = 128;
	DBG("kexec: allocating args\n");
	// XXX: hangs in smalloc, not sure why.
//	args = smalloc(n);
//	if(waserror()){
//		DBG("erroring\n");
//		free(args);
//		nexterror();
//	}
//	DBG("kexec: moving args\n");
//	memmove(args, a, n);
//	if(0)
//	while(n > 0 && (args[n-1] & 0xc0) == 0x80)
//		n--;
//	args[n-1] = '\0';

	kstrdup(&p->text, "kexecproc");
	p->args = nil;
	//elem;
//	elem = nil;
//	p->args = args;
//	p->nargs = n;
	poperror();				/* p (m->externup->args) */





/*
	qlock(&p->debug);

	sysprocsetup(p);
	qunlock(&p->debug);
*/

	// why is this sched and not ureg?
	p->sched.pc = entry;
	// the real question here is how do you set up the stack?
	p->sched.sp = PTR2UINT(stack-BY2SE);
	p->sched.sp = STACKALIGN(p->sched.sp);


	// XXX: what does it imply if you have a kproc that runs on an ac?
	if(core > 0){
		DBG("kexec: coring %d\n", core);
		mp = p->ac;
		mp->icc->flushtlb = 1;
		mp->icc->rc = ICCOK;

		DBG("kexec: exotic proc on cpu%d\n", mp->machno);
		qlock(&p->debug);
		if(waserror()){
			DBG("kexec: had error");
			qunlock(&p->debug);
			nexterror();
		}
		p->nicc++;
		p->state = Exotic;
		p->psstate = 0;
		DBG("kexec: unlocking");
		qunlock(&p->debug);
		poperror();
		mfence();
		mp->icc->fn = (void*)entry;
		sched();
	}else{
		DBG("kexec: readying\n");
		ready(p);
		p->newtlb = 1;
		mmuflush();
	}
	DBG("kforkexecac up %#p done\n"
		"textsz %lx datasz %lx bsssz %lx hdrsz %lx\n"
		"textlim %ullx datalim %ullx bsslim %ullx\n", m->externup,
		textsz, datasz, bsssz, hdrsz, textlim, datalim, bsslim);
}
Beispiel #15
0
void
runtime·chanrecv(ChanType *t, Hchan* c, byte *ep, bool *selected, bool *received)
{
	SudoG *sg;
	SudoG mysg;
	G *gp;

	if(runtime·gcwaiting)
		runtime·gosched();

	if(debug)
		runtime·printf("chanrecv: chan=%p\n", c);

	if(c == nil) {
		USED(t);
		if(selected != nil) {
			*selected = false;
			return;
		}
		g->status = Gwaiting;
		g->waitreason = "chan receive (nil chan)";
		runtime·gosched();
		return;  // not reached
	}

	runtime·lock(c);
	if(c->dataqsiz > 0)
		goto asynch;

	if(c->closed)
		goto closed;

	sg = dequeue(&c->sendq);
	if(sg != nil) {
		runtime·unlock(c);

		if(ep != nil)
			c->elemalg->copy(c->elemsize, ep, sg->elem);
		gp = sg->g;
		gp->param = sg;
		runtime·ready(gp);

		if(selected != nil)
			*selected = true;
		if(received != nil)
			*received = true;
		return;
	}

	if(selected != nil) {
		runtime·unlock(c);
		*selected = false;
		return;
	}

	mysg.elem = ep;
	mysg.g = g;
	mysg.selgen = NOSELGEN;
	g->param = nil;
	g->status = Gwaiting;
	g->waitreason = "chan receive";
	enqueue(&c->recvq, &mysg);
	runtime·unlock(c);
	runtime·gosched();

	if(g->param == nil) {
		runtime·lock(c);
		if(!c->closed)
			runtime·throw("chanrecv: spurious wakeup");
		goto closed;
	}

	if(received != nil)
		*received = true;
	return;

asynch:
	if(c->qcount <= 0) {
		if(c->closed)
			goto closed;

		if(selected != nil) {
			runtime·unlock(c);
			*selected = false;
			if(received != nil)
				*received = false;
			return;
		}
		mysg.g = g;
		mysg.elem = nil;
		mysg.selgen = NOSELGEN;
		g->status = Gwaiting;
		g->waitreason = "chan receive";
		enqueue(&c->recvq, &mysg);
		runtime·unlock(c);
		runtime·gosched();

		runtime·lock(c);
		goto asynch;
	}
	if(ep != nil)
		c->elemalg->copy(c->elemsize, ep, chanbuf(c, c->recvx));
	c->elemalg->copy(c->elemsize, chanbuf(c, c->recvx), nil);
	if(++c->recvx == c->dataqsiz)
		c->recvx = 0;
	c->qcount--;

	sg = dequeue(&c->sendq);
	if(sg != nil) {
		gp = sg->g;
		runtime·unlock(c);
		runtime·ready(gp);
	} else
		runtime·unlock(c);

	if(selected != nil)
		*selected = true;
	if(received != nil)
		*received = true;
	return;

closed:
	if(ep != nil)
		c->elemalg->copy(c->elemsize, ep, nil);
	if(selected != nil)
		*selected = true;
	if(received != nil)
		*received = false;
	runtime·unlock(c);
}
Beispiel #16
0
  void Scene::build (size_t threadIndex, size_t threadCount) 
  {
    /* all user worker threads properly enter and leave the tasking system */
    LockStepTaskScheduler::Init init(threadIndex,threadCount,&lockstep_scheduler);
    if (threadIndex != 0) return;

    /* allow only one build at a time */
    Lock<MutexSys> lock(mutex);

    if (isStatic() && isBuild()) {
      process_error(RTC_INVALID_OPERATION,"static geometries cannot get committed twice");
      return;
    }

    if (!ready()) {
      process_error(RTC_INVALID_OPERATION,"not all buffers are unmapped");
      return;
    }

    /* verify geometry in debug mode  */
#if 0 && defined(DEBUG) // FIXME: enable
    for (size_t i=0; i<geometries.size(); i++) {
      if (geometries[i]) {
        if (!geometries[i]->verify()) {
          process_error(RTC_INVALID_OPERATION,"invalid geometry specified");
          return;
        }
      }
    }
#endif

    /* select fast code path if no intersection filter is present */
    accels.select(numIntersectionFilters4,numIntersectionFilters8,numIntersectionFilters16);

    /* if user provided threads use them */
    if (threadCount)
      accels.build(threadIndex,threadCount);

    /* otherwise use our own threads */
    else
    {
      TaskScheduler::EventSync event;
      new (&task) TaskScheduler::Task(&event,_task_build_parallel,this,TaskScheduler::getNumThreads(),NULL,NULL,"scene_build");
      TaskScheduler::addTask(-1,TaskScheduler::GLOBAL_FRONT,&task);
      event.sync();
    }

    /* make static geometry immutable */
    if (isStatic()) 
    {
      accels.immutable();
      for (size_t i=0; i<geometries.size(); i++)
        if (geometries[i]) geometries[i]->immutable();
    }

    /* delete geometry that is scheduled for delete */
    for (size_t i=0; i<geometries.size(); i++) 
    {
      Geometry* geom = geometries[i];
      if (geom == NULL || geom->state != Geometry::ERASING) continue;
      remove(geom);
    }

    /* update bounds */
    bounds = accels.bounds;
    intersectors = accels.intersectors;
    is_build = true;

    /* enable only algorithms choosen by application */
    if ((aflags & RTC_INTERSECT1) == 0) {
      intersectors.intersector1.intersect = NULL;
      intersectors.intersector1.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT4) == 0) {
      intersectors.intersector4.intersect = NULL;
      intersectors.intersector4.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT8) == 0) {
      intersectors.intersector8.intersect = NULL;
      intersectors.intersector8.occluded = NULL;
    }
    if ((aflags & RTC_INTERSECT16) == 0) {
      intersectors.intersector16.intersect = NULL;
      intersectors.intersector16.occluded = NULL;
    }

    if (g_verbose >= 2) {
      std::cout << "created scene intersector" << std::endl;
      accels.print(2);
      std::cout << "selected scene intersector" << std::endl;
      intersectors.print(2);
    }
    
    /* update commit counter */
    commitCounter++;
  }
Beispiel #17
0
static void*
selectgo(Select **selp)
{
	Select *sel;
	uint32 o, i, j;
	Scase *cas, *dfl;
	Hchan *c;
	SudoG *sg;
	G *gp;
	byte *as;
	void *pc;

	sel = *selp;
	if(runtime·gcwaiting)
		runtime·gosched();

	if(debug)
		runtime·printf("select: sel=%p\n", sel);

	// The compiler rewrites selects that statically have
	// only 0 or 1 cases plus default into simpler constructs.
	// The only way we can end up with such small sel->ncase
	// values here is for a larger select in which most channels
	// have been nilled out.  The general code handles those
	// cases correctly, and they are rare enough not to bother
	// optimizing (and needing to test).

	// generate permuted order
	for(i=0; i<sel->ncase; i++)
		sel->pollorder[i] = i;
	for(i=1; i<sel->ncase; i++) {
		o = sel->pollorder[i];
		j = runtime·fastrand1()%(i+1);
		sel->pollorder[i] = sel->pollorder[j];
		sel->pollorder[j] = o;
	}

	// sort the cases by Hchan address to get the locking order.
	for(i=0; i<sel->ncase; i++) {
		c = sel->scase[i].chan;
		for(j=i; j>0 && sel->lockorder[j-1] >= c; j--)
			sel->lockorder[j] = sel->lockorder[j-1];
		sel->lockorder[j] = c;
	}
	sellock(sel);

loop:
	// pass 1 - look for something already waiting
	dfl = nil;
	for(i=0; i<sel->ncase; i++) {
		o = sel->pollorder[i];
		cas = &sel->scase[o];
		c = cas->chan;

		switch(cas->kind) {
		case CaseRecv:
			if(c->dataqsiz > 0) {
				if(c->qcount > 0)
					goto asyncrecv;
			} else {
				sg = dequeue(&c->sendq);
				if(sg != nil)
					goto syncrecv;
			}
			if(c->closed)
				goto rclose;
			break;

		case CaseSend:
			if(c->closed)
				goto sclose;
			if(c->dataqsiz > 0) {
				if(c->qcount < c->dataqsiz)
					goto asyncsend;
			} else {
				sg = dequeue(&c->recvq);
				if(sg != nil)
					goto syncsend;
			}
			break;

		case CaseDefault:
			dfl = cas;
			break;
		}
	}

	if(dfl != nil) {
		selunlock(sel);
		cas = dfl;
		goto retc;
	}


	// pass 2 - enqueue on all chans
	for(i=0; i<sel->ncase; i++) {
		o = sel->pollorder[i];
		cas = &sel->scase[o];
		c = cas->chan;
		sg = &cas->sg;
		sg->g = g;
		sg->selgen = g->selgen;

		switch(cas->kind) {
		case CaseRecv:
			enqueue(&c->recvq, sg);
			break;

		case CaseSend:
			enqueue(&c->sendq, sg);
			break;
		}
	}

	g->param = nil;
	g->status = Gwaiting;
	g->waitreason = "select";
	selunlock(sel);
	runtime·gosched();

	sellock(sel);
	sg = g->param;

	// pass 3 - dequeue from unsuccessful chans
	// otherwise they stack up on quiet channels
	for(i=0; i<sel->ncase; i++) {
		cas = &sel->scase[i];
		if(cas != (Scase*)sg) {
			c = cas->chan;
			if(cas->kind == CaseSend)
				dequeueg(&c->sendq);
			else
				dequeueg(&c->recvq);
		}
	}

	if(sg == nil)
		goto loop;

	cas = (Scase*)sg;
	c = cas->chan;

	if(c->dataqsiz > 0)
		runtime·throw("selectgo: shouldnt happen");

	if(debug)
		runtime·printf("wait-return: sel=%p c=%p cas=%p kind=%d\n",
			sel, c, cas, cas->kind);

	if(cas->kind == CaseRecv) {
		if(cas->receivedp != nil)
			*cas->receivedp = true;
	}

	selunlock(sel);
	goto retc;

asyncrecv:
	// can receive from buffer
	if(cas->receivedp != nil)
		*cas->receivedp = true;
	if(cas->sg.elem != nil)
		c->elemalg->copy(c->elemsize, cas->sg.elem, chanbuf(c, c->recvx));
	c->elemalg->copy(c->elemsize, chanbuf(c, c->recvx), nil);
	if(++c->recvx == c->dataqsiz)
		c->recvx = 0;
	c->qcount--;
	sg = dequeue(&c->sendq);
	if(sg != nil) {
		gp = sg->g;
		selunlock(sel);
		runtime·ready(gp);
	} else {
		selunlock(sel);
	}
	goto retc;

asyncsend:
	// can send to buffer
	c->elemalg->copy(c->elemsize, chanbuf(c, c->sendx), cas->sg.elem);
	if(++c->sendx == c->dataqsiz)
		c->sendx = 0;
	c->qcount++;
	sg = dequeue(&c->recvq);
	if(sg != nil) {
		gp = sg->g;
		selunlock(sel);
		runtime·ready(gp);
	} else {
		selunlock(sel);
	}
	goto retc;

syncrecv:
	// can receive from sleeping sender (sg)
	selunlock(sel);
	if(debug)
		runtime·printf("syncrecv: sel=%p c=%p o=%d\n", sel, c, o);
	if(cas->receivedp != nil)
		*cas->receivedp = true;
	if(cas->sg.elem != nil)
		c->elemalg->copy(c->elemsize, cas->sg.elem, sg->elem);
	gp = sg->g;
	gp->param = sg;
	runtime·ready(gp);
	goto retc;

rclose:
	// read at end of closed channel
	selunlock(sel);
	if(cas->receivedp != nil)
		*cas->receivedp = false;
	if(cas->sg.elem != nil)
		c->elemalg->copy(c->elemsize, cas->sg.elem, nil);
	goto retc;

syncsend:
	// can send to sleeping receiver (sg)
	selunlock(sel);
	if(debug)
		runtime·printf("syncsend: sel=%p c=%p o=%d\n", sel, c, o);
	if(sg->elem != nil)
		c->elemalg->copy(c->elemsize, sg->elem, cas->sg.elem);
	gp = sg->g;
	gp->param = sg;
	runtime·ready(gp);

retc:
	// return to pc corresponding to chosen case
	pc = cas->pc;
	as = (byte*)selp + cas->so;
	runtime·free(sel);
	*as = true;
	return pc;

sclose:
	// send on closed channel
	selunlock(sel);
	runtime·panicstring("send on closed channel");
	return nil;  // not reached
}
Beispiel #18
0
void
Irman::Close( ) {
    m_serial.Close();
    ready(FALSE);
}
Beispiel #19
0
/*
 *  if waking a sleeping process, this routine must hold both
 *  p->rlock and r->lock.  However, it can't know them in
 *  the same order as wakeup causing a possible lock ordering
 *  deadlock.  We break the deadlock by giving up the p->rlock
 *  lock if we can't get the r->lock and retrying.
 */
int
postnote(Proc *p, int dolock, char *n, int flag)
{
	Mpl pl;
	int ret;
	Rendez *r;
	Proc *d, **l;

	if(dolock)
		qlock(&p->debug);

	if(flag != NUser && (p->notify == 0 || p->notified))
		p->nnote = 0;

	ret = 0;
	if(p->nnote < NNOTE) {
		strcpy(p->note[p->nnote].msg, n);
		p->note[p->nnote++].flag = flag;
		ret = 1;
	}
	p->notepending = 1;

	/* NIX  */
	if(p->state == Exotic){
		/* it could be that the process is not running 
		 * in the AC when we interrupt the AC, but then
		 * we'd only get an extra interrupt in the AC, and
		 * nothing should happen.
		 */
		intrac(p);
	}

	if(dolock)
		qunlock(&p->debug);

	/* this loop is to avoid lock ordering problems. */
	for(;;){
		pl = splhi();
		lock(&p->rlock);
		r = p->r;

		/* waiting for a wakeup? */
		if(r == nil)
			break;	/* no */

		/* try for the second lock */
		if(canlock(r)){
			if(p->state != Wakeme || r->_p != p)
				panic("postnote: state %d %d %d", r->_p != p, p->r != r, p->state);
			p->r = nil;
			r->_p = nil;
			ready(p);
			unlock(r);
			break;
		}

		/* give other process time to get out of critical section and try again */
		unlock(&p->rlock);
		splx(pl);
		sched();
	}
	unlock(&p->rlock);
	splx(pl);

	if(p->state != Rendezvous){
		if(p->state == Semdown)
			ready(p);
		return ret;
	}
	/* Try and pull out of a rendezvous */
	lock(p->rgrp);
	if(p->state == Rendezvous) {
		p->rendval = ~0;
		l = &REND(p->rgrp, p->rendtag);
		for(d = *l; d; d = d->rendhash) {
			if(d == p) {
				*l = p->rendhash;
				break;
			}
			l = &d->rendhash;
		}
		ready(p);
	}
	unlock(p->rgrp);
	return ret;
}
Beispiel #20
0
BOOL Irman::Open( ) {
    if (ready())
        return TRUE;

    if (!m_sComPort.GetLength()) {
        return false;
    }
    const TCHAR * error = _T( "Error opening device" );

    CSerialMFC::EPort e = CSerialMFC::CheckPort(m_sComPort);
    if (e != CSerialMFC::EPortAvailable) {
        CString msg;
        msg << m_sComPort << " " << m_serial.EPortError(e);
        MBMessageBox("serial i/o error", msg);
        return false;
    }

    LONG o = m_serial.Open(m_sComPort, m_wndMsgHndlr, m_wmsg);
    if (o != ERROR_SUCCESS) {
        CString msg;
        msg << "unable to open " << m_sComPort << " error ["
            << o << "] " << MBFormatError(o);
        MBMessageBox("serial i/o error", msg);
        return false;
    }

    o = m_serial.Setup(CSerial::EBaud9600,CSerial::EData8,
                       CSerial::EParNone,CSerial::EStop1);
    if (o != ERROR_SUCCESS) {
        CString msg;
        msg << "unable to Setup " << m_sComPort << " error ["
            << o << "] " << MBFormatError(o);
        MBMessageBox("serial i/o error", msg);
        return false;
    }

    o = m_serial.SetupHandshaking(CSerial::EHandshakeOff);
    if (o != ERROR_SUCCESS) {
        CString msg;
        msg << "unable to Setup HandshakeOff " << m_sComPort << " error ["
            << o << "] " << MBFormatError(o);
        MBMessageBox("serial i/o error", msg);
        return false;
    }
    o = m_serial.SetupReadTimeouts(CSerial::EReadTimeoutNonblocking);
    if (o != ERROR_SUCCESS) {
        CString msg;
        msg << "unable to Setup TimeoutNonblocking" << m_sComPort << " error ["
            << o << "] " << MBFormatError(o);
        MBMessageBox("serial i/o error", msg);
        return false;
    }

    if (PowerOff( ) == FALSE)
        return FALSE;
    Sleep( 200 );
    if (PowerOn( ) == FALSE)
        return FALSE;

    Sleep( 100 );	// Time for the output to settle
    Flush( );		// Remove power up garbage

    m_serial.Write("I"); // These strings must be ASCII, not Unicode
    Sleep( 2 );			 // Need to have >500us between the 'I' & the 'R'
    m_serial.Write("R");
    m_OKreceived = 0;

    // Need to check that we receive "OK" back from Irman

    return RemoteReceiver::Open();
}
Beispiel #21
0
static void
releaseintr(Ureg* ureg, Timer *t)
{
	Proc *up = externup();
	Proc *p;
	extern int panicking;
	Sched *sch;
	Schedq *rq;

	if(panicking || active.exiting)
		return;

	p = t->ta;
	if((edflock(p)) == nil)
		return;
	sch = procsched(p);
	DPRINT("%lu releaseintr %d[%s]\n", now, p->pid, statename[p->state]);
	switch(p->state){
	default:
		edfunlock();
		return;
	case Ready:
		/* remove proc from current runq */
		rq = &sch->runq[p->priority];
		if(dequeueproc(sch, rq, p) != p){
			DPRINT("releaseintr: can't find proc or lock race\n");
			release(p);	/* It'll start best effort */
			edfunlock();
			return;
		}
		p->state = Waitrelease;
		/* fall through */
	case Waitrelease:
		release(p);
		edfunlock();
		if(p->state == Wakeme){
			iprint("releaseintr: wakeme\n");
		}
		ready(p);
		if(up){
			up->delaysched++;
			sch->delayedscheds++;
		}
		return;
	case Running:
		release(p);
		edfrun(p, 1);
		break;
	case Wakeme:
		release(p);
		edfunlock();
		if(p->trend)
			wakeup(p->trend);
		p->trend = nil;
		if(up){
			up->delaysched++;
			sch->delayedscheds++;
		}
		return;
	}
	edfunlock();
}
Beispiel #22
0
int main(int argc, char **argv)
{
#ifdef _WIN32
	u_long elapsed;
	struct _SYSTEMTIME ppst1;
	struct _SYSTEMTIME ppst2;
#else
	long elapsed;
	struct timeval tick;
    struct timeval tock;
#endif
    int sockfd;
    int portno = 0;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    int result;
    int protocol;
	char loop = 0;
	char udp = 0;
	int i = 0;

/* args processing */
	while (i < argc) {
		if (!strcmp(argv[i], "-t")) { loop = 1; }
		if (!s_is_portno_pp(argv[i])) { portno = atoi(argv[i]); }
		if (!strcmp(argv[i], "udp")) { udp = 1; }
		i++;
	}

    if (argc < 3) {
		fprintf(stderr, "Usage: %s hostname port [-t] [udp]\n\n", argv[0]);
		fprintf(stderr, "\t-t \tLoop ping given host and port\n"
		"\tudp \tSwitch to UDP (TCP is by default)\n");
        return 0;
    }

    if (!portno) {
        fprintf(stderr, "Invalid port number or port number not given.\n");
        return 0;
    }

#ifdef _WIN32
    if (pp_wsa_init()) {
        perror("Error during initialisation");
        return 1;
    }
#endif

    if (udp)
        protocol = SOCK_DGRAM;
    else
        protocol = SOCK_STREAM;

    do {
        sockfd = socket(AF_INET, protocol, 0);

        if (sockfd < 0) {
            perror("Error opening socket");
#ifdef _WIN32
			/* Unload Winsock resources. */
    		WSACleanup();
#endif
            return 1;
        }

        /* Set the socket to non-blocking. */
#ifdef _WIN32
        /* Cheat and reuse elapsed because we need a temporary long value. */
        elapsed = 1;
        result = ioctlsocket(sockfd, FIONBIO, &elapsed);
#else
        result = fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK);
#endif

        if (result < 0) {
            perror("Error setting socket to non-blocking");
#ifdef _WIN32
			/* Unload Winsock resources. */
    		WSACleanup();
#endif
            return 1;
        }

        /* Lookup the provided host. */
        server = gethostbyname(argv[1]);
        if (!server) {
            perror("DNS lookup failed");
#ifdef _WIN32
    		WSACleanup();
#endif
            return 1;
        }
#ifdef _WIN32
		GetSystemTime(&ppst1);
#else
        gettimeofday(&tick, 0);
#endif
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        memmove(&serv_addr.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
        serv_addr.sin_port = htons(portno);

        if (protocol == SOCK_STREAM) { /* TCP */
            connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

            /* The socket will only become ready if the connection succeeds. */
            result = ready(sockfd) - 1;
        } else { /* UDP */
            connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

            /* Sending to a closed UDP socket generates an error condition that
             * triggers on the next syscall with the socket. The error code
             * after this allows us to determine the status of the socket. This
             * method can generate false positives.
             */
            sendto(sockfd, 0, 0, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
            result = sendto(sockfd, 0, 0, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
#ifdef _WIN32
            if (errno == WSAECONNREFUSED)
#else
            if (errno == ECONNREFUSED)
#endif
                /* This will happen on ICMP error indicating a blocked port. */
                result = 1;
        }

#ifdef _WIN32
		GetSystemTime(&ppst2);
		elapsed = (ppst2.wSecond - ppst1.wSecond) * 1000 + (ppst2.wMilliseconds - ppst1.wMilliseconds);
#else
        gettimeofday(&tock, 0);
		elapsed = (tock.tv_sec - tick.tv_sec) * 1000 + (tock.tv_usec - tick.tv_usec) / 1000;
#endif


        switch(result) {
            case -1:
                printf("No response from");
                break;
            case 0:
                printf("Response from");
                break;
            default:
                printf("Connection blocked by");
                break;
        }
        printf(" %s:%s (time=%lums)\n", argv[1], argv[2], elapsed);

#ifdef _WIN32
        closesocket(sockfd);
        Sleep(1);
#else
        close(sockfd);
        sleep(1);
#endif
    } while (loop);

#ifdef _WIN32
    /* Unload Winsock resources. */
    WSACleanup();
#endif

    return 0;
}
Beispiel #23
0
ELoginAction::ELoginAction(EBrowser &browser, QString username, QString password) : EAction(browser), s_username(username), s_password(password)
{
    browser.loadPage("http://www.ontariots.ca//?q=logout");  // ensure that we're logged out.
    connect(&browser,SIGNAL(ready()),this,SLOT(continue1()));
}
Beispiel #24
0
void
userinit(void)
{
	void *v;
	Proc *p;
	Segment *s;
	Page *pg;

	p = newproc();
	p->pgrp = newpgrp();
	p->egrp = smalloc(sizeof(Egrp));
	p->egrp->ref = 1;
	p->fgrp = dupfgrp(nil);
	p->rgrp = newrgrp();
	p->procmode = 0640;

	kstrdup(&eve, "");
	kstrdup(&p->text, "*init*");
	kstrdup(&p->user, eve);

	p->fpstate = FPinit;
	fpoff();

	/*
	 * Kernel Stack
	 *
	 * N.B. make sure there's enough space for syscall to check
	 *	for valid args and 
	 *	4 bytes for gotolabel's return PC
	 */
	p->sched.pc = (ulong)init0;
	p->sched.sp = (ulong)p->kstack+KSTACK-(sizeof(Sargs)+BY2WD);

	/*
	 * User Stack
	 *
	 * N.B. cannot call newpage() with clear=1, because pc kmap
	 * requires up != nil.  use tmpmap instead.
	 */
	s = newseg(SG_STACK, USTKTOP-USTKSIZE, USTKSIZE/BY2PG);
	p->seg[SSEG] = s;
	pg = newpage(0, 0, USTKTOP-BY2PG);
	v = tmpmap(pg);
	memset(v, 0, BY2PG);
	segpage(s, pg);
	bootargs(v);
	tmpunmap(v);

	/*
	 * Text
	 */
	s = newseg(SG_TEXT, UTZERO, 1);
	s->flushme++;
	p->seg[TSEG] = s;
	pg = newpage(0, 0, UTZERO);
	memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
	segpage(s, pg);
	v = tmpmap(pg);
	memset(v, 0, BY2PG);
	memmove(v, initcode, sizeof initcode);
	tmpunmap(v);

	ready(p);
}
MenuSelection::MenuSelection() : Panel()
{
	Panel* selection_top = new Panel(1200, 200);
	this->add(selection_top, (Alignment::TOP | Alignment::LEFT));
	selection_top->setBgColor(Color::WHITE);
	selection_top->setBackground((*ServiceLocator::getTextureManager())["menuSelectTopBG"]);

	Label* j1 = new Label(150, 50, "Joueur 1 :", (*ServiceLocator::getFontManager())["LifeCraft"]);
	selection_top->add(j1);
	j1->setPositionX(100);
	j1->setPositionY(50);

	Label* j2 = new Label(150, 50, "Joueur 2 :", (*ServiceLocator::getFontManager())["LifeCraft"]);
	selection_top->add(j2);
	j2->setPositionX(1000);
	j2->setPositionY(50);

	choiceJ1 = new Button(75, 75);
	selection_top->add(choiceJ1);
	choiceJ1->setHover(false);
	choiceJ1->setPosition(110, 100);
	/*Texture t = (*ServiceLocator::getTextureManager())["obstacle_0"];
	choiceJ1->setBackground(t);
	choiceJ1->setHoverBackground(t);*/

	nameJ1 = new Label(150, 50, "J1", (*ServiceLocator::getFontManager())["LifeCraft"]);
	selection_top->add(nameJ1);
	nameJ1->setPositionX(325);
	nameJ1->setPositionY(110);

	choiceJ2 = new Button(75, 75);
	selection_top->add(choiceJ2);
	choiceJ2->setHover(false);
	choiceJ2->setPosition(1015, 100);
	/*Texture t2 = (*ServiceLocator::getTextureManager())["obstacle_1"];
	choiceJ2->setBackground(t2);
	choiceJ2->setHoverBackground(t2);*/

	nameJ2 = new Label(150, 50, "J2", (*ServiceLocator::getFontManager())["LifeCraft"]);
	selection_top->add(nameJ2);
	nameJ2->setPositionX(800);
	nameJ2->setPositionY(110);

	button_selec_1 = new Button(150, 50);
	selection_top->add(button_selec_1);
	button_selec_1->setText("Pret");
	button_selec_1->setTextAlignment(Alignment::CENTERX | Alignment::CENTERY);
	button_selec_1->setPositionY(100);
	button_selec_1->setPositionX(525);
	button_selec_1->setBackground((*ServiceLocator::getTextureManager())["BackgroundReady"]);
	button_selec_1->setHoverBackground((*ServiceLocator::getTextureManager())["BackgroundReadyHover"]);
	//button_selec_1->setBgColor(Color::RED);
	button_selec_1->Clickable::setCallback(new EventCallback([=](Event*) {ready(); }));

	Panel* selection_bottom = new Panel(1200, 700);
	this->add(selection_bottom);
	Texture selBottom = (*ServiceLocator::getTextureManager())["menuSelectBG"];
	selection_bottom->setBackground(selBottom);
	selection_bottom->setBgColor(Color::BLUE);
	selection_bottom->setPosition(0, 200);

	Button* flecheLeft = new Button(50, 50);
	selection_bottom->add(flecheLeft);
	flecheLeft->setPosition(20, 270);
	flecheLeft->Clickable::setCallback(new EventCallback([=](Event*) {clickArrow('l'); }));
	flecheLeft->setHoverBackground((*ServiceLocator::getTextureManager())["flecheG"]);
	flecheLeft->setBackground((*ServiceLocator::getTextureManager())["flecheG"]);

	Button* flecheRight = flecheLeft->clone();
	selection_bottom->add(flecheRight);
	flecheRight->setPosition(500, 270);
	flecheRight->Clickable::setCallback(new EventCallback([=](Event*) {clickArrow('r'); }));
	flecheRight->setHoverBackground((*ServiceLocator::getTextureManager())["flecheD"]);
	flecheRight->setBackground((*ServiceLocator::getTextureManager())["flecheD"]);

	showSelectChar = new Button(300, 300);
	selection_bottom->add(showSelectChar);
	showSelectChar->setPosition(150, 200);
	//showSelectChar->setHover(false);
	//showSelectChar->Clickable::setCallback(new EventCallback([=](Event*) {selectClass(a); }));
	showSelectChar->setHoverBackground((*ServiceLocator::getTextureManager())["icon_archer"]);
	showSelectChar->setBackground((*ServiceLocator::getTextureManager())["icon_archer"]);


/*	Button* choice1 = new Button(125, 125);
	selection_bottom->add(choice1);
	choice1->setPosition(200, 100);
	choice1->Clickable::setCallback(new EventCallback([=](Event*) {selectClass(a); }));
	choice1->setHoverBackground((*ServiceLocator::getTextureManager())["icon_archer"]);
	choice1->setBackground((*ServiceLocator::getTextureManager())["icon_archer"]);

	Button* choice2 = choice1->clone();
	selection_bottom->add(choice2);
	choice2->setPosition(200 - 62, 100 + 125);
	choice2->Clickable::setCallback(new EventCallback([=](Event*) {selectClass(k); }));
	choice2->setBackground((*ServiceLocator::getTextureManager())["icon_knight"]);
	choice2->setHoverBackground((*ServiceLocator::getTextureManager())["icon_knight"]);

	Button* choice3 = choice1->clone();
	selection_bottom->add(choice3);
	choice3->setPosition(200 + 63, 100 + 125);
	choice3->Clickable::setCallback(new EventCallback([=](Event*) {selectClass(m); }));
	choice3->setBackground((*ServiceLocator::getTextureManager())["icon_mage"]);
	choice3->setHoverBackground((*ServiceLocator::getTextureManager())["icon_mage"]);*/

	Panel* spellInfos = new Panel(500, 500);
	this->add(spellInfos);

	spellInfos->setBackground((*ServiceLocator::getTextureManager())["parchemin"]);
	int daX = 30; //décalage en X pour les labels (test de background texture)
	int daY = 30;//décalage en Y pour les labels (test de background texture)

	spellInfos->setPosition(600, 250);

	nomClasse = new Label(150, 25, "Nom Classe", (*ServiceLocator::getFontManager())["LifeCraft"]);
	spellInfos->add(nomClasse);
	nomClasse->setPosition(25 + daX, 10 + daY);

	descrClasse = new Label(400, 35, "Description de la classe : bla bla bla bla bla bla bla", (*ServiceLocator::getFontManager())["LifeCraft"]);
	//spellInfos->add(descrClasse);
	descrClasse->setPosition(15 + daX, 35 + daY);
	descrClasse->setTextSize(22);

	spell1 = new Button(75, 75);
	spellInfos->add(spell1);
	spell1->setPosition(50 + daX, 100 + daY);
	spell1->Clickable::setCallback(new EventCallback([=](Event*) {selectSpell(0); }));

	spell2 = new Button(75, 75);
	spellInfos->add(spell2);
	spell2->setPosition(50 + 100 + daX, 100 + daY);
	spell2->Clickable::setCallback(new EventCallback([=](Event*) {selectSpell(1); }));

	spell3 = new Button(75, 75);
	spellInfos->add(spell3);
	spell3->setPosition(50 + 100 + 100 + daX, 100 + daY);
	spell3->Clickable::setCallback(new EventCallback([=](Event*) {selectSpell(2); }));

	spell4 = new Button(75, 75);
	spellInfos->add(spell4);
	spell4->setPosition(50 + 100 + 100 + 100 + daX, 100 + daY);
	spell4->Clickable::setCallback(new EventCallback([=](Event*) {selectSpell(3); }));

	nomSpell = new Label(400, 50, "Nom Spell", (*ServiceLocator::getFontManager())["LifeCraft"]);
	spellInfos->add(nomSpell);
	nomSpell->setPosition(25 + daX, 175 + daY);

	descrSpell = new Label(500, 150, "Description du Spell : bla bla bla bla bla", (*ServiceLocator::getFontManager())["LifeCraft"]);
	spellInfos->add(descrSpell);
	descrSpell->setPosition(25 + daX, 205 + daY);
	descrSpell->setTextSize(22);
	descrSpell->setTextAlignment(Alignment::CENTERY | Alignment::LEFT);

	infos = new Label(400, 35, "Cost : X , Range : Y , inline / aoe", (*ServiceLocator::getFontManager())["LifeCraft"]);
	spellInfos->add(infos);
	infos->setPosition(25 + daX, 350 + daY);
	infos->setTextSize(22);

	unsigned int n = rand() % Grid::CELLS_NUMBER;
	while (GAMEINST->getGrid()->getCell(n)->getType() != Cell::Free)
	{
		n = rand() % Grid::CELLS_NUMBER;
	}
	a = new Archer(GAMEINST->getGrid()->getCell(n)->getPosX(), GAMEINST->getGrid()->getCell(n)->getPosY());

	while (GAMEINST->getGrid()->getCell(n)->getType() != Cell::Free)
	{
		n = rand() % Grid::CELLS_NUMBER;
	}
	k = new Knight(GAMEINST->getGrid()->getCell(n)->getPosX(), GAMEINST->getGrid()->getCell(n)->getPosY());
	while (GAMEINST->getGrid()->getCell(n)->getType() != Cell::Free)
	{
		n = rand() % Grid::CELLS_NUMBER;
	}
	m = new Mage(GAMEINST->getGrid()->getCell(n)->getPosX(), GAMEINST->getGrid()->getCell(n)->getPosY());
	selectClass(a);
}
Beispiel #26
0
void PropagateUploadFile::startNextChunk()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    if (! _jobs.isEmpty() &&  _currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        // We return now and when the _jobs are finished we will proceed with the last chunk
        // NOTE: Some other parts of the code such as slotUploadProgress also assume that the last chunk
        // is sent last.
        return;
    }
    quint64 fileSize = _item->_size;
    QMap<QByteArray, QByteArray> headers;
    headers["OC-Total-Length"] = QByteArray::number(fileSize);
    headers["OC-Async"] = "1";
    headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize()));
    headers["Content-Type"] = "application/octet-stream";
    headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime));

    if(_item->_file.contains(".sys.admin#recall#")) {
        // This is a file recall triggered by the admin.  Note: the
        // recall list file created by the admin and downloaded by the
        // client (.sys.admin#recall#) also falls into this category
        // (albeit users are not supposed to mess up with it)

        // We use a special tag header so that the server may decide to store this file away in some admin stage area
        // And not directly in the user's area (which would trigger redownloads etc).
        headers["OC-Tag"] = ".sys.admin#recall#";
    }

    if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag"
            && _item->_instruction != CSYNC_INSTRUCTION_NEW  // On new files never send a If-Match
            && _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE
            && !_deleteExisting
            ) {
        // We add quotes because the owncloud server always adds quotes around the etag, and
        //  csync_owncloud.c's owncloud_file_id always strips the quotes.
        headers["If-Match"] = '"' + _item->_etag + '"';
    }

    QString path = _item->_file;

    UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager);
    qint64 chunkStart = 0;
    qint64 currentChunkSize = fileSize;
    bool isFinalChunk = false;
    if (_chunkCount > 1) {
        int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
        // XOR with chunk size to make sure everything goes well if chunk size changes between runs
        uint transid = _transferId ^ chunkSize();
        qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid;
        path +=  QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);

        headers["OC-Chunked"] = "1";

        chunkStart = chunkSize() * quint64(sendingChunk);
        currentChunkSize = chunkSize();
        if (sendingChunk == _chunkCount - 1) { // last chunk
            currentChunkSize = (fileSize % chunkSize());
            if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size.
                currentChunkSize = chunkSize();
            }
            isFinalChunk = true;
        }
    } else {
        // if there's only one chunk, it's the final one
        isFinalChunk = true;
    }

    if (isFinalChunk && !_transmissionChecksumType.isEmpty()) {
        headers[checkSumHeaderC] = makeChecksumHeader(
                _transmissionChecksumType, _transmissionChecksum);
    }

    const QString fileName = _propagator->getFilePath(_item->_file);
    if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) {
        qDebug() << "ERR: Could not prepare upload device: " << device->errorString();

        // If the file is currently locked, we want to retry the sync
        // when it becomes available again.
        if (FileSystem::isFileLocked(fileName)) {
            emit _propagator->seenLockedFile(fileName);
        }

        // Soft error because this is likely caused by the user modifying his files while syncing
        abortWithError( SyncFileItem::SoftError, device->errorString() );
        delete device;
        return;
    }

    // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
    PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk);
    _jobs.append(job);
    connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
    job->start();
    _propagator->_activeJobList.append(this);
    _currentChunk++;

    bool parallelChunkUpload = true;
    QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK");
    if (!env.isEmpty()) {
        parallelChunkUpload = env != "false" && env != "0";
    } else {
        int versionNum = _propagator->account()->serverVersionInt();
        if (versionNum < 0x080003) {
            // Disable parallel chunk upload severs older than 8.0.3 to avoid too many
            // internal sever errors (#2743, #2938)
            parallelChunkUpload = false;
        }
    }

    if (_currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        parallelChunkUpload = false;
    }

    if (parallelChunkUpload && (_propagator->_activeJobList.count() < _propagator->maximumActiveJob())
            && _currentChunk < _chunkCount ) {
        startNextChunk();
    }
    if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
        emit ready();
    }
}
Beispiel #27
0
static void* 
selectgo ( Select **selp ) 
{ 
Select *sel; 
uint32 o , i , j , k , done; 
int64 t0; 
Scase *cas , *dfl; 
Hchan *c; 
SudoG *sg; 
G *gp; 
byte *as; 
void *pc; 
#line 663 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sel = *selp; 
#line 665 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( debug ) 
runtime·printf ( "select: sel=%p\n" , sel ) ; 
#line 668 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
t0 = 0; 
if ( runtime·blockprofilerate > 0 ) { 
t0 = runtime·cputicks ( ) ; 
for ( i=0; i<sel->ncase; i++ ) 
sel->scase[i].sg.releasetime = -1; 
} 
#line 684 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
for ( i=0; i<sel->ncase; i++ ) 
sel->pollorder[i] = i; 
for ( i=1; i<sel->ncase; i++ ) { 
o = sel->pollorder[i]; 
j = runtime·fastrand1 ( ) % ( i+1 ) ; 
sel->pollorder[i] = sel->pollorder[j]; 
sel->pollorder[j] = o; 
} 
#line 695 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
for ( i=0; i<sel->ncase; i++ ) { 
j = i; 
c = sel->scase[j].chan; 
while ( j > 0 && sel->lockorder[k= ( j-1 ) /2] < c ) { 
sel->lockorder[j] = sel->lockorder[k]; 
j = k; 
} 
sel->lockorder[j] = c; 
} 
for ( i=sel->ncase; i-->0; ) { 
c = sel->lockorder[i]; 
sel->lockorder[i] = sel->lockorder[0]; 
j = 0; 
for ( ;; ) { 
k = j*2+1; 
if ( k >= i ) 
break; 
if ( k+1 < i && sel->lockorder[k] < sel->lockorder[k+1] ) 
k++; 
if ( c < sel->lockorder[k] ) { 
sel->lockorder[j] = sel->lockorder[k]; 
j = k; 
continue; 
} 
break; 
} 
sel->lockorder[j] = c; 
} 
#line 730 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sellock ( sel ) ; 
#line 732 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
loop: 
#line 734 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
dfl = nil; 
for ( i=0; i<sel->ncase; i++ ) { 
o = sel->pollorder[i]; 
cas = &sel->scase[o]; 
c = cas->chan; 
#line 740 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
switch ( cas->kind ) { 
case CaseRecv: 
if ( c->dataqsiz > 0 ) { 
if ( c->qcount > 0 ) 
goto asyncrecv; 
} else { 
sg = dequeue ( &c->sendq ) ; 
if ( sg != nil ) 
goto syncrecv; 
} 
if ( c->closed ) 
goto rclose; 
break; 
#line 754 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
case CaseSend: 
if ( raceenabled ) 
runtime·racereadpc ( c , cas->pc , chansend ) ; 
if ( c->closed ) 
goto sclose; 
if ( c->dataqsiz > 0 ) { 
if ( c->qcount < c->dataqsiz ) 
goto asyncsend; 
} else { 
sg = dequeue ( &c->recvq ) ; 
if ( sg != nil ) 
goto syncsend; 
} 
break; 
#line 769 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
case CaseDefault: 
dfl = cas; 
break; 
} 
} 
#line 775 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( dfl != nil ) { 
selunlock ( sel ) ; 
cas = dfl; 
goto retc; 
} 
#line 783 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
done = 0; 
for ( i=0; i<sel->ncase; i++ ) { 
o = sel->pollorder[i]; 
cas = &sel->scase[o]; 
c = cas->chan; 
sg = &cas->sg; 
sg->g = g; 
sg->selectdone = &done; 
#line 792 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
switch ( cas->kind ) { 
case CaseRecv: 
enqueue ( &c->recvq , sg ) ; 
break; 
#line 797 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
case CaseSend: 
enqueue ( &c->sendq , sg ) ; 
break; 
} 
} 
#line 803 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
g->param = nil; 
runtime·park ( selparkcommit , sel , "select" ) ; 
#line 806 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sellock ( sel ) ; 
sg = g->param; 
#line 811 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
for ( i=0; i<sel->ncase; i++ ) { 
cas = &sel->scase[i]; 
if ( cas != ( Scase* ) sg ) { 
c = cas->chan; 
if ( cas->kind == CaseSend ) 
dequeueg ( &c->sendq ) ; 
else 
dequeueg ( &c->recvq ) ; 
} 
} 
#line 822 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( sg == nil ) 
goto loop; 
#line 825 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
cas = ( Scase* ) sg; 
c = cas->chan; 
#line 828 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( c->dataqsiz > 0 ) 
runtime·throw ( "selectgo: shouldn't happen" ) ; 
#line 831 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( debug ) 
runtime·printf ( "wait-return: sel=%p c=%p cas=%p kind=%d\n" , 
sel , c , cas , cas->kind ) ; 
#line 835 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( cas->kind == CaseRecv ) { 
if ( cas->receivedp != nil ) 
*cas->receivedp = true; 
} 
#line 840 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
if ( cas->kind == CaseRecv && cas->sg.elem != nil ) 
runtime·racewriteobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chanrecv ) ; 
else if ( cas->kind == CaseSend ) 
runtime·racereadobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chansend ) ; 
} 
#line 847 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
selunlock ( sel ) ; 
goto retc; 
#line 850 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
asyncrecv: 
#line 852 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
if ( cas->sg.elem != nil ) 
runtime·racewriteobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chanrecv ) ; 
runtime·raceacquire ( chanbuf ( c , c->recvx ) ) ; 
runtime·racerelease ( chanbuf ( c , c->recvx ) ) ; 
} 
if ( cas->receivedp != nil ) 
*cas->receivedp = true; 
if ( cas->sg.elem != nil ) 
c->elemtype->alg->copy ( c->elemsize , cas->sg.elem , chanbuf ( c , c->recvx ) ) ; 
c->elemtype->alg->copy ( c->elemsize , chanbuf ( c , c->recvx ) , nil ) ; 
if ( ++c->recvx == c->dataqsiz ) 
c->recvx = 0; 
c->qcount--; 
sg = dequeue ( &c->sendq ) ; 
if ( sg != nil ) { 
gp = sg->g; 
selunlock ( sel ) ; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
} else { 
selunlock ( sel ) ; 
} 
goto retc; 
#line 878 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
asyncsend: 
#line 880 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
runtime·raceacquire ( chanbuf ( c , c->sendx ) ) ; 
runtime·racerelease ( chanbuf ( c , c->sendx ) ) ; 
runtime·racereadobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chansend ) ; 
} 
c->elemtype->alg->copy ( c->elemsize , chanbuf ( c , c->sendx ) , cas->sg.elem ) ; 
if ( ++c->sendx == c->dataqsiz ) 
c->sendx = 0; 
c->qcount++; 
sg = dequeue ( &c->recvq ) ; 
if ( sg != nil ) { 
gp = sg->g; 
selunlock ( sel ) ; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
} else { 
selunlock ( sel ) ; 
} 
goto retc; 
#line 901 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
syncrecv: 
#line 903 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
if ( cas->sg.elem != nil ) 
runtime·racewriteobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chanrecv ) ; 
racesync ( c , sg ) ; 
} 
selunlock ( sel ) ; 
if ( debug ) 
runtime·printf ( "syncrecv: sel=%p c=%p o=%d\n" , sel , c , o ) ; 
if ( cas->receivedp != nil ) 
*cas->receivedp = true; 
if ( cas->sg.elem != nil ) 
c->elemtype->alg->copy ( c->elemsize , cas->sg.elem , sg->elem ) ; 
gp = sg->g; 
gp->param = sg; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
goto retc; 
#line 922 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
rclose: 
#line 924 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
selunlock ( sel ) ; 
if ( cas->receivedp != nil ) 
*cas->receivedp = false; 
if ( cas->sg.elem != nil ) 
c->elemtype->alg->copy ( c->elemsize , cas->sg.elem , nil ) ; 
if ( raceenabled ) 
runtime·raceacquire ( c ) ; 
goto retc; 
#line 933 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
syncsend: 
#line 935 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
if ( raceenabled ) { 
runtime·racereadobjectpc ( cas->sg.elem , c->elemtype , cas->pc , chansend ) ; 
racesync ( c , sg ) ; 
} 
selunlock ( sel ) ; 
if ( debug ) 
runtime·printf ( "syncsend: sel=%p c=%p o=%d\n" , sel , c , o ) ; 
if ( sg->elem != nil ) 
c->elemtype->alg->copy ( c->elemsize , sg->elem , cas->sg.elem ) ; 
gp = sg->g; 
gp->param = sg; 
if ( sg->releasetime ) 
sg->releasetime = runtime·cputicks ( ) ; 
runtime·ready ( gp ) ; 
#line 950 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
retc: 
#line 956 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
pc = cas->pc; 
if ( cas->so > 0 ) { 
as = ( byte* ) selp + cas->so; 
*as = true; 
} 
if ( cas->sg.releasetime > 0 ) 
runtime·blockevent ( cas->sg.releasetime - t0 , 2 ) ; 
runtime·free ( sel ) ; 
return pc; 
#line 966 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
sclose: 
#line 968 "/tmp/makerelease402042453/go/src/pkg/runtime/chan.goc"
selunlock ( sel ) ; 
runtime·panicstring ( "send on closed channel" ) ; 
return nil; 
} 
Beispiel #28
0
/*
 * generic single channel send/recv
 * if the bool pointer is nil,
 * then the full exchange will
 * occur. if pres is not nil,
 * then the protocol will not
 * sleep but return if it could
 * not complete.
 *
 * sleep can wake up with g->param == nil
 * when a channel involved in the sleep has
 * been closed.  it is easiest to loop and re-run
 * the operation; we'll see that it's now closed.
 */
void
runtime·chansend(ChanType *t, Hchan *c, byte *ep, bool *pres)
{
	SudoG *sg;
	SudoG mysg;
	G* gp;

	if(c == nil) {
		USED(t);
		if(pres != nil) {
			*pres = false;
			return;
		}
		g->status = Gwaiting;
		g->waitreason = "chan send (nil chan)";
		runtime·gosched();
		return;  // not reached
	}

	if(runtime·gcwaiting)
		runtime·gosched();

	if(debug) {
		runtime·printf("chansend: chan=%p; elem=", c);
		c->elemalg->print(c->elemsize, ep);
		runtime·prints("\n");
	}

	runtime·lock(c);
	if(c->closed)
		goto closed;

	if(c->dataqsiz > 0)
		goto asynch;

	sg = dequeue(&c->recvq);
	if(sg != nil) {
		runtime·unlock(c);

		gp = sg->g;
		gp->param = sg;
		if(sg->elem != nil)
			c->elemalg->copy(c->elemsize, sg->elem, ep);
		runtime·ready(gp);

		if(pres != nil)
			*pres = true;
		return;
	}

	if(pres != nil) {
		runtime·unlock(c);
		*pres = false;
		return;
	}

	mysg.elem = ep;
	mysg.g = g;
	mysg.selgen = NOSELGEN;
	g->param = nil;
	g->status = Gwaiting;
	g->waitreason = "chan send";
	enqueue(&c->sendq, &mysg);
	runtime·unlock(c);
	runtime·gosched();

	if(g->param == nil) {
		runtime·lock(c);
		if(!c->closed)
			runtime·throw("chansend: spurious wakeup");
		goto closed;
	}

	return;

asynch:
	if(c->closed)
		goto closed;

	if(c->qcount >= c->dataqsiz) {
		if(pres != nil) {
			runtime·unlock(c);
			*pres = false;
			return;
		}
		mysg.g = g;
		mysg.elem = nil;
		mysg.selgen = NOSELGEN;
		g->status = Gwaiting;
		g->waitreason = "chan send";
		enqueue(&c->sendq, &mysg);
		runtime·unlock(c);
		runtime·gosched();

		runtime·lock(c);
		goto asynch;
	}
	c->elemalg->copy(c->elemsize, chanbuf(c, c->sendx), ep);
	if(++c->sendx == c->dataqsiz)
		c->sendx = 0;
	c->qcount++;

	sg = dequeue(&c->recvq);
	if(sg != nil) {
		gp = sg->g;
		runtime·unlock(c);
		runtime·ready(gp);
	} else
		runtime·unlock(c);
	if(pres != nil)
		*pres = true;
	return;

closed:
	runtime·unlock(c);
	runtime·panicstring("send on closed channel");
}
Beispiel #29
0
/*
 * Entered in AP core context, upon traps (system calls go through acsyscall)
 * using up->dbgreg means cores MUST be homogeneous.
 *
 * BUG: We should setup some trapenable() mechanism for the AC,
 * so that code like fpu.c could arrange for handlers specific for
 * the AC, instead of doint that by hand here.
 *
 * All interrupts are masked while in the "kernel"
 */
void
actrap(Ureg *u)
{
	panic("actrap");
#if 0
	char *n;
	ACVctl *v;

	n = nil;

	_pmcupdate(m);
	if(m->proc != nil){
		m->proc->nactrap++;
		m->proc->actime1 = fastticks(nil);
	}
	if(u->type < nelem(acvctl)){
		v = acvctl[u->type];
		if(v != nil){
			DBG("actrap: cpu%d: %ulld\n", machp()->machno, u->type);
			n = v->f(u, v->a);
			if(n != nil)
				goto Post;
			return;
		}
	}
	switch(u->type){
	case IdtDF:
		print("AC: double fault\n");
		dumpregs(u);
		ndnr();
	case IdtIPI:
		m->intr++;
		DBG("actrap: cpu%d: IPI\n", machp()->machno);
		apiceoi(IdtIPI);
		break;
	case IdtTIMER:
		apiceoi(IdtTIMER);
		panic("timer interrupt in an AC");
		break;
	case IdtPF:
		/* this case is here for debug only */
		m->pfault++;
		DBG("actrap: cpu%d: PF cr2 %#ullx\n", machp()->machno, cr2get());
		break;
	default:
		print("actrap: cpu%d: %ulld\n", machp()->machno, u->type);
	}
Post:
	m->icc->rc = ICCTRAP;
	m->cr2 = cr2get();
	memmove(m->proc->dbgreg, u, sizeof *u);
	m->icc->note = n;
	fpuprocsave(m->proc);
	_pmcupdate(m);
	mfence();
	m->icc->fn = nil;
	ready(m->proc);

	mwait(&m->icc->fn);

	if(m->icc->flushtlb)
		acmmuswitch();
	if(m->icc->fn != actrapret)
		acsched();
	DBG("actrap: ret\n");
	memmove(u, m->proc->dbgreg, sizeof *u);
	if(m->proc)
		m->proc->actime += fastticks2us(fastticks(nil) - m->proc->actime1);
#endif
}
Beispiel #30
0
void PropagateUploadFileQNAM::startNextChunk()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    if (! _jobs.isEmpty() &&  _currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        // We return now and when the _jobs will be finished we will proceed the last chunk
        // NOTE: Some other part of the code such as slotUploadProgress assume also that the last chunk
        // is sent last.
        return;
    }
    quint64 fileSize = _item._size;
    QMap<QByteArray, QByteArray> headers;
    headers["OC-Total-Length"] = QByteArray::number(fileSize);
    headers["OC-Async"] = "1";
    headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize()));
    headers["Content-Type"] = "application/octet-stream";
    headers["X-OC-Mtime"] = QByteArray::number(qint64(_item._modtime));
    if (!_item._etag.isEmpty() && _item._etag != "empty_etag" &&
            _item._instruction != CSYNC_INSTRUCTION_NEW  // On new files never send a If-Match
            ) {
        // We add quotes because the owncloud server always add quotes around the etag, and
        //  csync_owncloud.c's owncloud_file_id always strip the quotes.
        headers["If-Match"] = '"' + _item._etag + '"';
    }

    QString path = _item._file;

    UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager);
    qint64 chunkStart = 0;
    qint64 currentChunkSize = fileSize;
    if (_chunkCount > 1) {
        int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
        // XOR with chunk size to make sure everything goes well if chunk size change between runs
        uint transid = _transferId ^ chunkSize();
        path +=  QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);

        headers["OC-Chunked"] = "1";

        chunkStart = chunkSize() * quint64(sendingChunk);
        currentChunkSize = chunkSize();
        if (sendingChunk == _chunkCount - 1) { // last chunk
            currentChunkSize = (fileSize % chunkSize());
            if( currentChunkSize == 0 ) { // if the last chunk pretents to be 0, its actually the full chunk size.
                currentChunkSize = chunkSize();
            }
        }
    }

    if (! device->prepareAndOpen(_propagator->getFilePath(_item._file), chunkStart, currentChunkSize)) {
        qDebug() << "ERR: Could not prepare upload device: " << device->errorString();
        // Soft error because this is likely caused by the user modifying his files while syncing
        abortWithError( SyncFileItem::SoftError, device->errorString() );
        delete device;
        return;
    }

    // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
    PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk);
    _jobs.append(job);
    connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
    connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
    job->start();
    _propagator->_activeJobs++;
    _currentChunk++;

    bool parallelChunkUpload = true;
    QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK");
    if (!env.isEmpty()) {
        parallelChunkUpload = env != "false" && env != "0";
    } else {
        auto version = _propagator->account()->serverVersion();
        auto components = version.split('.');
        int versionNum = (components.value(0).toInt() << 16)
                       + (components.value(1).toInt() << 8)
                       + components.value(2).toInt();
        if (versionNum < 0x080003) {
            // Disable parallel chunk upload severs older than 8.0.3 to avoid too many
            // internal sever errors (#2743, #2938)
            parallelChunkUpload = false;
        }
    }

    if (_currentChunk + _startChunk >= _chunkCount - 1) {
        // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
        // https://github.com/owncloud/core/issues/11106
        parallelChunkUpload = false;
    }

    if (parallelChunkUpload && (_propagator->_activeJobs < _propagator->maximumActiveJob())
            && _currentChunk < _chunkCount ) {
        startNextChunk();
    }
    if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
        emit ready();
    }
}