Ejemplo n.º 1
0
void RenderThread::run()
{
    int size = qMax(m_image.width()/20, m_image.height()/20);
    for (int s = size; s > 0; --s) {
        for (int c = 0; c < 400; ++c) {
//![processing the image (start)]
            int x1 = qMax(0, (qrand() % m_image.width()) - s/2);
            int x2 = qMin(x1 + s/2 + 1, m_image.width());
            int y1 = qMax(0, (qrand() % m_image.height()) - s/2);
            int y2 = qMin(y1 + s/2 + 1, m_image.height());
            int n = 0;
            int red = 0;
            int green = 0;
            int blue = 0;
            for (int i = y1; i < y2; ++i) {
                for (int j = x1; j < x2; ++j) {
                    QRgb pixel = m_image.pixel(j, i);
                    red += qRed(pixel);
                    green += qGreen(pixel);
                    blue += qBlue(pixel);
                    n += 1;
                }
            }
//![processing the image (finish)]
            Block block(QRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1),
                        QColor(red/n, green/n, blue/n));
            emit sendBlock(block);
            if (m_abort)
                return;
            msleep(10);
        }
    }
}
Ejemplo n.º 2
0
// create a new connection reading a file from server
void TFTPServer::ConnectRead(char* buff) {
    extern LaosFileSystem sd;
    remote_ip = client.get_address();
    remote_port = client.get_port();
    Ack(0);
    blockcnt = 0;
    dupcnt = 0;

    sprintf(filename, "%s", &buff[2]);
    
    if (modeOctet(buff))
        fp = sd.openfile(filename, "rb");
    else
        fp = sd.openfile(filename, "r");
    if (fp == NULL) {
        state  = listen;
        Err("Could not read file");
    } else {
        // file ready for reading
        blockcnt = 0;
        state = reading;
        #ifdef TFTP_DEBUG
            char debugmsg[256];
            sprintf(debugmsg, "Listen: Requested file %s from TFTP connection %d.%d.%d.%d port %d",
                filename, clientIp[0], clientIp[1], clientIp[2], clientIp[3], clientPort);
            TFTP_DEBUG(debugmsg);
        #endif
        getBlock();
        sendBlock();
    }
}
Ejemplo n.º 3
0
//! [Window constructor start]
Window::Window()
{
    thread = new RenderThread();
//! [Window constructor start] //! [set up widgets and connections]

    label = new QLabel();
    label->setAlignment(Qt::AlignCenter);

    loadButton = new QPushButton(tr("&Load image..."));
    resetButton = new QPushButton(tr("&Stop"));
    resetButton->setEnabled(false);

    connect(loadButton, SIGNAL(clicked()), this, SLOT(loadImage()));
    connect(resetButton, SIGNAL(clicked()), thread, SLOT(stopProcess()));
    connect(thread, SIGNAL(finished()), this, SLOT(resetUi()));
//! [set up widgets and connections] //! [connecting signal with custom type]
    connect(thread, SIGNAL(sendBlock(Block)), this, SLOT(addBlock(Block)));
//! [connecting signal with custom type]

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(loadButton);
    buttonLayout->addWidget(resetButton);
    buttonLayout->addStretch();

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(label);
    layout->addLayout(buttonLayout);

//! [Window constructor finish]
    setWindowTitle(tr("Queued Custom Type"));
}
Ejemplo n.º 4
0
void parse_ir(){
	// send control pulses
	if (stringComplete) {
		Serial.print("sending...");
		Serial.println(inputString);
		switch (inputString[0]) {
			case '0':
			sendBlock(IrCmd2, sizeof(IrCmd2));
			break;
			case '1':
			case '2':
			sendBlock(IrCmd1, sizeof(IrCmd1));
			break;
			case '4':
			sendBlock(IrCmd24, sizeof(IrCmd24));
			break;
		}
		stringComplete=false;
	}
}
Ejemplo n.º 5
0
unsigned long VideoCommunication::sendBlocks(){
    unsigned long blocks_sent = 0;
    if (imageBlocks.size() == 0)
        return 0;
    
    //transmit blocks one by one
    for (unsigned i = 0; i < numOfBlocksPerFrame; i++){
            sendBlock(compress.compress(imageBlocks.at(i))); //////////////////////// check is we send sqe = 0
            blocks_sent++;
    }
    
    //printf("%lu\n",blocks_sent);
    return blocks_sent;
}
Ejemplo n.º 6
0
ssize_t hbm::communication::SocketNonblocking::sendBlocks(const dataBlocks_t &blocks)
{
	std::vector < iovec > iovs(6); // reserve a reasonable number of entries!

	size_t completeLength = 0;
	iovec newIovec;

	for(dataBlocks_t::const_iterator iter=blocks.begin(); iter!=blocks.end(); ++iter) {
		const dataBlock_t& item = *iter;
		newIovec.iov_base = const_cast < void* > (item.pData);
		newIovec.iov_len = item.size;
		iovs.push_back(newIovec);
		completeLength += item.size;
	}


	ssize_t retVal = writev(m_fd, &iovs[0], iovs.size());
	if (retVal==0) {
		return retVal;
	} else if (retVal==-1) {
		if((errno!=EWOULDBLOCK) && (errno!=EAGAIN) && (errno!=EINTR) ) {
			return retVal;
		}
	}

	size_t bytesWritten = retVal;
	if(bytesWritten==completeLength) {
		// we are done!
		return bytesWritten;
	} else {
		size_t blockSum = 0;

		for(size_t index=0; index<iovs.size(); ++index) {
			blockSum += iovs[index].iov_len;
			if(bytesWritten<blockSum) {
				// this block was not send completely
				size_t bytesRemaining = blockSum - bytesWritten;
				size_t start = iovs[index].iov_len-bytesRemaining;
				retVal = sendBlock(static_cast < unsigned char* > (iovs[index].iov_base)+start, bytesRemaining, false);
				if(retVal>0) {
					bytesWritten += retVal;
				} else {
					return -1;
				}
			}
		}
	}

	return bytesWritten;
}
Ejemplo n.º 7
0
ssize_t hbm::communication::SocketNonblocking::sendBlocks(const dataBlocks_t &blocks)
{
	std::vector < WSABUF > buffers(blocks.size());

	size_t completeLength = 0;
	WSABUF newWsaBuf;

	for (dataBlocks_t::const_iterator iter = blocks.begin(); iter != blocks.end(); ++iter) {
		const dataBlock_t& item = *iter;
		newWsaBuf.buf = (CHAR*)item.pData;
		newWsaBuf.len = item.size;
		buffers.push_back(newWsaBuf);
		completeLength += item.size;
	}
	DWORD bytesWritten = 0;

	int retVal;
	
	retVal = WSASend(m_fd, &buffers[0], buffers.size(), &bytesWritten, 0, NULL, NULL);
	if (retVal < 0) {
		int retVal = WSAGetLastError();
		if ((retVal != WSAEWOULDBLOCK) && (retVal != WSAEINTR) && (retVal != WSAEINPROGRESS)) {
			return retVal;
		}
	}

	if (bytesWritten == completeLength) {
		// we are done!
		return bytesWritten;
	} else {
		size_t blockSum = 0;

		for (size_t index = 0; index < buffers.size(); ++index) {
			blockSum += buffers[index].len;
			if (bytesWritten < blockSum) {
				// this block was not send completely
				size_t bytesRemaining = blockSum - bytesWritten;
				size_t start = buffers[index].len - bytesRemaining;
				retVal = sendBlock(buffers[index].buf + start, bytesRemaining, false);
				if (retVal > 0) {
					bytesWritten += retVal;
				}
				else {
					return -1;
				}
			}
		}
	}
	return bytesWritten;
}
void RenderThread::run()
{
    // Note: The content of this method is executed inside the worker thread!

    // Iterate over the image pixel-by-pixel and calculate the color of the blocks
    int size = qMax(m_image.width() / 20, m_image.height() / 20);
    for (int s = size; s > 10; --s) {
        for (int c = 0; c < 400; ++c) {
//![processing the image (start)]
            int x1 = qMax(0, (qrand() % m_image.width()) - s / 2);
            int x2 = qMin(x1 + s / 2 + 1, m_image.width());
            int y1 = qMax(0, (qrand() % m_image.height()) - s / 2);
            int y2 = qMin(y1 + s / 2 + 1, m_image.height());
            int n = 0;
            int red = 0;
            int green = 0;
            int blue = 0;
            for (int i = y1; i < y2; ++i) {
                for (int j = x1; j < x2; ++j) {
                    QRgb pixel = m_image.pixel(j, i);
                    red += qRed(pixel);
                    green += qGreen(pixel);
                    blue += qBlue(pixel);
                    n += 1;
                }
            }
//![processing the image (finish)]
            if (qAlpha(m_image.pixel(x1, y1)) != 0) { // ignore transparent pixels
                // Create a corresponding color object
                const bb::cascades::Color color = bb::cascades::Color::fromRGBA(red / n / 255.0, green / n / 255.0, blue / n / 255.0, 1.0);

                // Create a block of the current block size
                Block block(QRect(x1, y1, x2 - x1 + 1, y2 - y1 + 1), color);

                // Send the result by emitting the signal
                emit sendBlock(block);
            }

            /**
             * If the user requested the abort of the worker thread, we simply return from the run() method,
             * which will cause the termination of the worker thread.
             */
            if (m_abort)
                return;

            msleep(10);
        }
    }
}
Ejemplo n.º 9
0
void ServerClient::onReadyRead()
{
    QDataStream in(mainSocket);
    while (mainSocket->bytesAvailable() > 0){
        if (blockSize == 0){
            if (mainSocket->bytesAvailable() < sizeof(quint16)){
                return;
            }
            in >> blockSize;
        }
        if (mainSocket->bytesAvailable() < blockSize){
            return;
        } else {
            blockSize = 0;
        }

        quint8 command = 0;
        in >> command;

        switch (command) {
        case testComm:
        {
            qDebug() << "Success!";
            break;
        }
        case loginComm:
        {
            QString logPass;
            QStringList logp;
            QString halls;
            in >> logPass;
            logp = logPass.split(" ");

            if (servPtr->login(logp.at(0),logp.at(1))){
                isLoggedIn = true;
                uId = servPtr->getId(logp.at(0));
                qDebug() << "user " << logp.at(0) << "connected";
                this->sendBlock(succLoginComm, NULL);
                halls = servPtr->getHalls();
                if (halls!="NULL"){
                    QByteArray block;
                    QDataStream out(&block, QIODevice::WriteOnly);
                    out << halls;
                    this->sendBlock(getHallsComm, &block);
                }
            } else {
                this->sendBlock(unSuccLoginComm, NULL);
            }
            break;
        }
        case getHallItems:
        {
            int hallid;
            in >> hallid;
            QString itemsInHalls = servPtr->getItemsHalls(hallid);
            if (itemsInHalls!="NULL"){
                QByteArray block;
                QDataStream out(&block, QIODevice::WriteOnly);
                out << itemsInHalls;
                this->sendBlock(getHallItems, &block);
            }else{
                //eRRoR
                sendBlock(err, NULL);
            }
            break;
        }
        case getItemGroups:
        {
            QString itemGroups = servPtr->getItemGroups();
            if (itemGroups!="NULL"){
                QByteArray block;
                QDataStream out(&block, QIODevice::WriteOnly);
                out << itemGroups;
                this->sendBlock(getItemGroups, &block);
            }else{
                //eRRoR
                sendBlock(err, NULL);
            }

            break;
        }
        case editItemGroup:
        {
            QString itemGroup;

            in >> itemGroup;
            if(servPtr->getPerms(uId).items){


                QJsonDocument itemGroupDoc = QJsonDocument::fromJson(itemGroup.toUtf8());
                QJsonObject group2edit = itemGroupDoc.object();

                if(!servPtr->updateGroups(group2edit["groupId"].toInt(),
                                          group2edit["groupName"].toString(),
                                          group2edit["groupComment"].toString()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succEditItem, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case addGroup:
        {
            QString itemGroup;

            in >> itemGroup;
            if(servPtr->getPerms(uId).items){


                QJsonDocument itemGroupDoc = QJsonDocument::fromJson(itemGroup.toUtf8());
                QJsonObject newGr = itemGroupDoc.object();

                if(!servPtr->insertGroup(newGr["groupName"].toString(),
                                         newGr["groupComment"].toString()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succAddGroup, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case delGroup:
        {
            QString itemGroup;

            in >> itemGroup;
            if(servPtr->getPerms(uId).items){


                QJsonDocument itemGroupDoc = QJsonDocument::fromJson(itemGroup.toUtf8());
                QJsonObject newGr = itemGroupDoc.object();

                if(!servPtr->deleteGroup(newGr["groupId"].toInt()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succDelGroup, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;

        }
        case addItem:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).items){
                //qDebug() << "addItem";

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->insertItem(newIt["itemName"].toString(),
                                        newIt["itemInventoryNum"].toString(),
                                        newIt["itemGroup"].toInt(),
                                        newIt["itemCount"].toInt(),
                                        newIt["itemComment"].toString(),
                                        newIt["itemHallId"].toInt()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succAddItem, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case modItem:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).items){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->updateItem(newIt["itemId"].toInt(),
                                        newIt["itemName"].toString(),
                                        newIt["itemInventoryNum"].toString(),
                                        newIt["itemGroup"].toInt(),
                                        newIt["itemCount"].toInt(),
                                        newIt["itemComment"].toString(),
                                        newIt["itemHallId"].toInt()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succAddItem, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case delItem:
        {
            QString itemGroup;

            in >> itemGroup;
            if(servPtr->getPerms(uId).items){


                QJsonDocument itemGroupDoc = QJsonDocument::fromJson(itemGroup.toUtf8());
                QJsonObject newGr = itemGroupDoc.object();

                if(!servPtr->deleteItem(newGr["itemId"].toInt(), newGr["hallId"].toInt()))
                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succDelItem, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case modHall:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).halls){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->updateHall(newIt["hallId"].toInt(),
                                        newIt["hallName"].toString(),
                                        newIt["hallAddr"].toString(),
                                        newIt["hallRoom"].toInt()))

                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    QByteArray block;
                    QDataStream out(&block, QIODevice::WriteOnly);
                    out << itm;

                    this->sendBlock(succModHall, &block);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case addHall:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).halls){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->insertHall(newIt["hallName"].toString(),
                                        newIt["hallAddr"].toString(),
                                        newIt["hallRoom"].toInt()))

                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succAddHall, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case delHall:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).halls){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->delHall(newIt["hallId"].toInt()))

                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succDelHall, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case getUsr:
        {
            qDebug() << "_______________________GUSR_____________________";
            if(servPtr->getPerms(uId).usr){
                QString itemGroups = servPtr->getUsers();
                if (itemGroups!="NULL"){
                    QByteArray block;
                    QDataStream out(&block, QIODevice::WriteOnly);
                    out << itemGroups;
                    this->sendBlock(getUsr, &block);
                }else{
                    //eRRoR
                    sendBlock(err, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case addUsr:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).usr){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->createAcc(newIt["userLogin"].toString(),
                                       newIt["userPassword"].toString(),
                                       newIt["userGroup"].toInt(),
                                       newIt["userName"].toString(),
                                       newIt["userSurname"].toString(),
                                       newIt["userFathername"].toString()))


                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succAddUsr, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case modUsr:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).usr){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->modUser(  newIt["userId"].toInt(),
                                       newIt["userLogin"].toString(),
                                       newIt["userPassword"].toString(),
                                       newIt["userGroup"].toInt(),
                                       newIt["userName"].toString(),
                                       newIt["userSurname"].toString(),
                                       newIt["userFathername"].toString()))


                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succModUsr, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        case delUsr:
        {
            QString itm;

            in >> itm;
            if(servPtr->getPerms(uId).usr){

                qDebug() << itm;

                QJsonDocument itmDoc = QJsonDocument::fromJson(itm.toUtf8());
                QJsonObject newIt = itmDoc.object();

                if(!servPtr->delUser(newIt["userId"].toInt()))


                {
                    //eRRoR
                    sendBlock(err, NULL);
                }else{
                    this->sendBlock(succDelUsr, NULL);
                }
            } else {
                sendBlock(permRestrict, NULL);
            }
            break;
        }
        default:
            break;
        }
    }
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	//MPI initialize
	MPI_Init (&argc, &argv);	
	int rank, size, master = 0;
	MPI_Comm_rank (MPI_COMM_WORLD, &rank);	
	MPI_Comm_size (MPI_COMM_WORLD, &size);
	MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);


	CheckPreprocessorMacros();

	/* -------------------------------------------------------------------- */
	/* .. Local variables. */
	/* -------------------------------------------------------------------- */
	timer_t start_t, end_t;
	const integer_t nrhs = 1;
	Error_t error;

	if(rank == master){

		fprintf(stderr, "\nShared Memory Spike Solver.\n");


		/* -------------------------------------------------------------------- */
		/* .. Load and initalize the system Ax=f. */
		/* -------------------------------------------------------------------- */
		matrix_t* A = matrix_LoadCSR("../Tests/spike/penta_15.bin");
		//matrix_t* A = matrix_LoadCSR("../Tests/pentadiagonal/large.bin");
		//matrix_t* A = matrix_LoadCSR("../Tests/dummy/tridiagonal.bin");
		matrix_PrintAsDense( A, "Original coeffient matrix" );

		// Compute matrix bandwidth
		block_t*  x = block_CreateEmptyBlock( A->n, nrhs, 0, 0, _RHS_BLOCK_, _WHOLE_SECTION_ );
		block_t*  f = block_CreateEmptyBlock( A->n, nrhs, 0, 0, _RHS_BLOCK_, _WHOLE_SECTION_ );

		block_InitializeToValue( x, __zero  ); // solution of the system
		block_InitializeToValue( f, __punit ); // rhs of the system

		start_t = GetReferenceTime();

		/* compute an optimal solving strategy */
		sm_schedule_t* S = spike_solve_analysis( A, nrhs, size-1 );

		/* create the reduced sytem in advanced, based on the solving strategy */
		matrix_t* R  = matrix_CreateEmptyReducedSystem ( S->p, S->n, S->ku, S->kl);
		block_t*  xr = block_CreateReducedRHS( S->p, S->ku, S->kl, nrhs );

		/* -------------------------------------------------------------------- */
		/* .. Factorization Phase. */
		/* -------------------------------------------------------------------- */
		for(integer_t p=0; p < S->p; p++)
		{
			sendSchedulePacked(S, p+1);
			const integer_t r0 = S->n[p];
			const integer_t rf = S->n[p+1];

			matrix_t* Aij = matrix_ExtractMatrix(A, r0, rf, r0, rf);
			sendMatrix(Aij, p+1);

			block_t*  fi  = block_ExtractBlock( f, r0, rf );
			block_t*  yi  = block_CreateEmptyBlock( rf - r0, nrhs, 0, 0, _RHS_BLOCK_, _WHOLE_SECTION_ );
			block_SetBandwidthValues( fi, A->ku, A->kl );
			block_SetBandwidthValues( yi, A->ku, A->kl );

			sendBlock(fi, p+1);
			sendBlock(yi, p+1);

			/* Add the tips of the yi block to the reduced RHS */
			block_t* yit = recvBlock(p+1);
			block_t* yib = recvBlock(p+1);
			block_AddTipTOReducedRHS( p, S->ku, S->kl, xr, yit );
			block_AddTipTOReducedRHS( p, S->ku, S->kl, xr, yib );

			/* clean up */
			block_Deallocate (fi );
			block_Deallocate (yi );
			block_Deallocate (yit);
			block_Deallocate (yib);
			
			if(p == 0){
				block_t* Vi = block_CreateEmptyBlock ( rf - r0, A->ku, A->ku, A->kl, _V_BLOCK_, _WHOLE_SECTION_ );
				block_t* Bi = matrix_ExtractBlock    ( A, r0, rf, rf, rf + A->ku, _V_BLOCK_ );
				
				sendBlock(Vi, p+1);
				sendBlock(Bi, p+1);
							
				block_t* Vit = recvBlock(p+1);
				block_t* Vib = recvBlock(p+1);

				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Vit );
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Vib );

				block_Deallocate( Bi );
				block_Deallocate( Vi );
				block_Deallocate( Vit);
				block_Deallocate( Vib);
			}
			else if (p == ( S->p -1)){
				block_t* Wi = block_CreateEmptyBlock( rf - r0, A->kl, A->ku, A->kl, _W_BLOCK_, _WHOLE_SECTION_ );
				block_t* Ci = matrix_ExtractBlock(A, r0, rf, r0 - A->kl, r0, _W_BLOCK_ );
				sendBlock(Wi, p+1);
				sendBlock(Ci, p+1);

				block_t* Wit = recvBlock(p+1);
				block_t* Wib = recvBlock(p+1);
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Wit );
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Wib );

				block_Deallocate( Ci );
				block_Deallocate( Wi );
				block_Deallocate( Wit);
				block_Deallocate( Wib);
			}
			else{
				block_t* Vi = block_CreateEmptyBlock ( rf - r0, A->ku, A->ku, A->kl, _V_BLOCK_, _WHOLE_SECTION_ );
				block_t* Bi = matrix_ExtractBlock    ( A, r0, rf, rf, rf + A->ku, _V_BLOCK_ );
				sendBlock(Vi, p+1);
				sendBlock(Bi, p+1);
			
				block_t* Vit = recvBlock(p+1);
				block_t* Vib = recvBlock(p+1);			
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Vit );
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Vib );

				block_Deallocate( Bi );
				block_Deallocate( Vi );
				block_Deallocate( Vit);
				block_Deallocate( Vib);
				
				block_t* Wi = block_CreateEmptyBlock( rf - r0, A->kl, A->ku, A->kl, _W_BLOCK_, _WHOLE_SECTION_ );
				block_t* Ci = matrix_ExtractBlock(A, r0, rf, r0 - A->kl, r0, _W_BLOCK_ );
				sendBlock(Wi, p+1);
				sendBlock(Ci, p+1);

				block_t* Wit = recvBlock(p+1);
				block_t* Wib = recvBlock(p+1);
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Wit );
				matrix_AddTipToReducedMatrix( S->p, p, S->n, S->ku, S->kl, R, Wib );

				block_Deallocate( Ci );
				block_Deallocate( Wi );
				block_Deallocate( Wit);
				block_Deallocate( Wib);
			}
			matrix_Deallocate( Aij);
		}
		
		MPI_Barrier(MPI_COMM_WORLD);
		/* -------------------------------------------------------------------- */
		/* .. Solution of the reduced system.                                   */
		/* -------------------------------------------------------------------- */

		block_t* yr = block_CreateEmptyBlock( xr->n, xr->m, 0, 0, _RHS_BLOCK_, _WHOLE_SECTION_ );
		fprintf(stderr, "\nSolving reduced linear system\n");
		system_solve ( R->colind, R->rowptr, R->aij, yr->aij, xr->aij, R->n, xr->m);
		block_Print(yr, "Solucion del sistema reducido");


		/* Free some memory, yr and R are not needed anymore */
		block_Deallocate ( xr );
		matrix_Deallocate( R  );

		/* -------------------------------------------------------------------- */
		/* .. Backward substitution phase. */
		/* -------------------------------------------------------------------- */
		for(integer_t p=0; p < S->p; p++)
		{
			fprintf(stderr, "Processing backward solution for the %d-th block\n", p);

			/* compute the limits of the blocks */
			const integer_t obs = S->n[p];        		/* original system starting row */
			const integer_t obe = S->n[p+1];	  		/* original system ending row   */
			const integer_t rbs = S->r[p];		  		/* reduceed system starting row */
			const integer_t rbe = S->r[p+1];			/* reduced system ending row    */
			const integer_t ni  = S->n[p+1] - S->n[p]; 	/* number of rows in the block  */

			/* allocate pardiso configuration parameters */
			MKL_INT pardiso_conf[64];

			/* extract xi sub-block */
			block_t*  xi  = block_ExtractBlock(x, obs, obe );
			sendBlock(xi, p+1);

			/* extract fi sub-block */
			block_t*  fi  = block_ExtractBlock(f, obs, obe );
			sendBlock(fi, p+1);
			printf("Lets go %d\n", p);
			
			if ( p == 0 ){

				block_t* xt_next = block_ExtractBlock ( yr, rbe, rbe + S->ku[p+1]);
				sendBlock(xt_next, p+1);
				block_Deallocate (xt_next);
			}

			else if ( p == ( S->p -1)){

				block_t* xb_prev = block_ExtractBlock ( yr, rbs - S->kl[p], rbs );
				sendBlock(xb_prev, p+1);
				block_Deallocate (xb_prev);
			}

			else{
				block_t* xt_next = block_ExtractBlock ( yr, rbe, rbe + S->ku[p+1]);
				sendBlock(xt_next, p+1);
				block_Deallocate (xt_next);
				
				block_t* xb_prev = block_ExtractBlock ( yr, rbs - S->kl[p], rbs );
				sendBlock(xb_prev, p+1);
				block_Deallocate (xb_prev);
			}
			xi = recvBlock(p+1);
			block_AddBlockToRHS(x, xi, obs, obe);
			block_Deallocate    ( xi );
			block_Deallocate 	( fi );
		}
		schedule_Destroy( S );
		block_Deallocate( yr);
	
		end_t = GetReferenceTime();

		fprintf(stderr, "\nSPIKE solver took %.6lf seconds", end_t - start_t);
		block_Print( x, "Solution of the linear system");

		ComputeResidualOfLinearSystem( A->colind, A->rowptr, A->aij, x->aij, f->aij, A->n, nrhs);
	
		fprintf(stderr, "\nPARDISO REFERENCE SOLUTION...\n");
		SolveOriginalSystem( A, x, f);

		/* -------------------------------------------------------------------- */
		/* .. Clean up. */
		/* -------------------------------------------------------------------- */
		matrix_Deallocate ( A );
		block_Deallocate  ( x );
		block_Deallocate  ( f );



		/* -------------------------------------------------------------------- */
		/* .. Load and initalize the system Ax=f. */
		/* -------------------------------------------------------------------- */
		fprintf(stderr, "\nProgram finished\n");

		debug("Number of malloc() calls %d, number of free() calls %d\n", cnt_alloc, cnt_free );
	}

	else{ //WORKERS

		/* -------------------------------------------------------------------- */
		/* .. Factorization Phase. */
		/* -------------------------------------------------------------------- */
		//fprintf(stderr, "Solving %d-th block\n", p);

		sm_schedule_t* S = recvSchedulePacked(master);
		/* compute the limits of the blocks */
		integer_t p = rank -1;
		const integer_t obs = S->n[p];        		/* original system starting row */
		const integer_t obe = S->n[p+1];	  		/* original system ending row   */
		const integer_t rbs = S->r[p];		  		/* reduceed system starting row */
		const integer_t rbe = S->r[p+1];			/* reduced system ending row    */
		const integer_t ni  = S->n[p+1] - S->n[p]; 	/* number of rows in the block  */

		MKL_INT pardiso_conf[64];

		/* allocate pardiso configuration parameters */
		DirectSolverHander_t *handler = directSolver_CreateHandler();

		directSolver_Configure( handler );

		/* factorize matrix */
		matrix_t* Aij = recvMatrix(master);

		directSolver_Factorize( handler,
			Aij->n,
			Aij->nnz,
			Aij->colind,
			Aij->rowptr,
			Aij->aij, Aij->n);

		/* -------------------------------------------------------------------- */
		/* .. Solve Ai * yi = fi                                                */
		/* Extracts the fi portion from f, creates a yi block used as container */
		/* for the solution of the system. Then solves the system.              */
		/* -------------------------------------------------------------------- */
		
		/* solve the system for the RHS value */
		block_t*  fi = recvBlock(master);
		block_t*  yi = recvBlock(master);

		/* solve Ai * yi = fi */
		directSolver_SolveForRHS( handler, nrhs, yi->aij, fi->aij );

		/* Extract the tips of the yi block */
		block_t* yit = block_ExtractTip( yi, _TOP_SECTION_   , _COLMAJOR_ );
		block_t* yib = block_ExtractTip( yi, _BOTTOM_SECTION_, _COLMAJOR_ );
		sendBlock(yit, master);
		sendBlock(yib, master);

		/* clean up */
		block_Deallocate (fi );
		block_Deallocate (yi );
		block_Deallocate (yit);
		block_Deallocate (yib);

		if ( rank == 1 ){
				
			block_t* Vi = recvBlock(master);
			block_t* Bi = recvBlock(master);

			/* solve Ai * Vi = Bi */
			directSolver_SolveForRHS( handler, Vi->m, Vi->aij, Bi->aij );

			block_t* Vit = block_ExtractTip( Vi, _TOP_SECTION_, _ROWMAJOR_ );
			block_t* Vib = block_ExtractTip( Vi, _BOTTOM_SECTION_, _ROWMAJOR_ );
			sendBlock(Vit, master);
			sendBlock(Vib, master);

			block_t* Bib = block_ExtractTip( Bi, _BOTTOM_SECTION_, _COLMAJOR_ );

			//block_Deallocate( Vi );
			block_Deallocate( Bi );
			block_Deallocate( Vi);
			block_Deallocate( Vit);
			block_Deallocate( Vib);

			//Here Master Resolve Reduced System
			MPI_Barrier(MPI_COMM_WORLD);
			
			block_t* xi = recvBlock(master);
			block_t* fi = recvBlock(master);
			block_t* xt_next = recvBlock(master);
			
			/* Backward substitution, implicit scheme: xi = -1.0 * Bi * xit  + fi */
			cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
				Bib->n,    						/* m - number of rows of A    */
				xt_next->m, 					/* n - number of columns of B */
				Bib->m,    						/* k - number of columns of A */
				__nunit,						/* alpha                      */
				Bib->aij, 						/* A block                    */
				Bib->n,    						/* lda - first dimension of A */
				xt_next->aij, 					/* B block                    */
				xt_next->n,    					/* ldb - first dimension of B */
				__punit,						/* beta                       */
				&fi->aij[ni - S->ku[p]], 		/* C block                    */
				ni ); 					 		/* ldc - first dimension of C */
			
			/* solve Ai * xi = fi */
			directSolver_SolveForRHS( handler, xi->m, xi->aij, fi->aij );

			sendBlock(xi, master);

			block_Deallocate ( Bib );
			block_Deallocate ( xt_next);
			block_Deallocate ( xi );
			block_Deallocate ( fi );
		}

		else if ( rank == size -1){
			
			block_t* Wi = recvBlock(master);
			block_t* Ci = recvBlock(master);

			/* solve Ai * Wi = Ci */
			directSolver_SolveForRHS( handler, Wi->m, Wi->aij, Ci->aij );


			block_t* Wit = block_ExtractTip( Wi, _TOP_SECTION_, _ROWMAJOR_ );
			block_t* Wib = block_ExtractTip( Wi, _BOTTOM_SECTION_, _ROWMAJOR_ );
			sendBlock(Wit, master);
			sendBlock(Wib, master);
			
			block_t* Cit = block_ExtractTip(Ci, _TOP_SECTION_, _COLMAJOR_ );			
		
			block_Deallocate( Ci );
			block_Deallocate( Wi );
			block_Deallocate( Wit);
			block_Deallocate( Wib);

			//Here Master Resolve Reduced System
			MPI_Barrier(MPI_COMM_WORLD);

			block_t* xi = recvBlock(master);
			block_t* fi = recvBlock(master);
			block_t* xb_prev = recvBlock(master);
			/* Backward substitution, implicit scheme: xi = -1.0 * Bi * xit  + fi */ 
			cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
				Cit->n,    						/* m - number of rows of A    */
				xb_prev->m, 					/* n - number of columns of B */
				Cit->m,    						/* k - number of columns of A */
				__nunit,						/* alpha                      */
				Cit->aij, 						/* A block                    */
				Cit->n,    						/* lda - first dimension of A */
				xb_prev->aij, 					/* B block                    */
				xb_prev->n,    					/* ldb - first dimension of B */
				__punit,						/* beta                       */
				fi->aij, 			 		    /* C block                    */
				ni );		 					/* ldc - first dimension of C */

			/* solve Ai * xi = fi */
			directSolver_SolveForRHS( handler, xi->m, xi->aij, fi->aij );

			sendBlock(xi, master);

			block_Deallocate ( Cit );
			block_Deallocate ( xb_prev);
			block_Deallocate ( xi );
			block_Deallocate ( fi );
		}

		else{
			block_t* Vi = recvBlock(master);
			block_t* Bi = recvBlock(master);

			/* solve Ai * Vi = Bi */
			directSolver_SolveForRHS( handler, Vi->m, Vi->aij, Bi->aij );

			block_t* Vit = block_ExtractTip( Vi, _TOP_SECTION_, _ROWMAJOR_ );
			block_t* Vib = block_ExtractTip( Vi, _BOTTOM_SECTION_, _ROWMAJOR_ );
			sendBlock(Vit, master);
			sendBlock(Vib, master);

			block_t* Bib = block_ExtractTip( Bi, _BOTTOM_SECTION_, _COLMAJOR_ );

			block_Deallocate( Bi );
			block_Deallocate( Vi );
			block_Deallocate( Vit);
			block_Deallocate( Vib);

			block_t* Wi = recvBlock(master);
			block_t* Ci = recvBlock(master);

			/* solve Ai * Wi = Ci */
			directSolver_SolveForRHS( handler, Wi->m, Wi->aij, Ci->aij );

			block_t* Wit = block_ExtractTip( Wi, _TOP_SECTION_, _ROWMAJOR_ );
			block_t* Wib = block_ExtractTip( Wi, _BOTTOM_SECTION_, _ROWMAJOR_ );
			sendBlock(Wit, master);
			sendBlock(Wib, master);
			
			block_t* Cit = block_ExtractTip(Ci, _TOP_SECTION_, _COLMAJOR_ );
			
			block_Deallocate( Ci );
			block_Deallocate( Wi );
			block_Deallocate( Wit);
			block_Deallocate( Wib);

			//Here Master Resolve Reduced System
			MPI_Barrier(MPI_COMM_WORLD);
			
			block_t* xi = recvBlock(master);
			block_t* fi = recvBlock(master);
			block_t* xt_next = recvBlock(master);
			
			/* Backward substitution, implicit scheme: xi = -1.0 * Bi * xit  + fi */
			cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
				Bib->n,    						/* m - number of rows of A    */
				xt_next->m, 					/* n - number of columns of B */
				Bib->m,    						/* k - number of columns of A */
				__nunit,						/* alpha                      */
				Bib->aij, 						/* A block                    */
				Bib->n,    						/* lda - first dimension of A */
				xt_next->aij, 					/* B block                    */
				xt_next->n,    					/* ldb - first dimension of B */
				__punit,						/* beta                       */
				&fi->aij[ni - S->ku[p]], 		/* C block                    */
				ni ); 					 		/* ldc - first dimension of C */

			directSolver_ApplyFactorToRHS( Aij->colind, Aij->rowptr, Aij->aij, xi->aij, fi->aij, Aij->n, xi->m, &pardiso_conf );

			/* solve Ai * xi = fi */
			directSolver_SolveForRHS( handler, xi->m, xi->aij, fi->aij );

			block_Deallocate ( Bib );
			block_Deallocate ( xt_next); 

			block_t* xb_prev = recvBlock(master);
			/* Backward substitution, implicit scheme: xi = -1.0 * Bi * xit  + fi */ 
			cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
				Cit->n,    						/* m - number of rows of A    */
				xb_prev->m, 					/* n - number of columns of B */
				Cit->m,    						/* k - number of columns of A */
				__nunit,						/* alpha                      */
				Cit->aij, 						/* A block                    */
				Cit->n,    						/* lda - first dimension of A */
				xb_prev->aij, 					/* B block                    */
				xb_prev->n,    					/* ldb - first dimension of B */
				__punit,						/* beta                       */
				fi->aij, 			 		    /* C block                    */
				ni );		 					/* ldc - first dimension of C */

			/* solve Ai * xi = fi */
			directSolver_SolveForRHS( handler, xi->m, xi->aij, fi->aij );

			sendBlock(xi, master);

			block_Deallocate ( Cit );
			block_Deallocate ( xb_prev);
			block_Deallocate ( xi );
			block_Deallocate ( fi );
		
		}
		/* Show statistics and clean up solver internal memory */
		directSolver_ShowStatistics(handler);
		directSolver_Finalize(handler);

		schedule_Destroy  ( S );
		matrix_Deallocate(Aij);	
		
		debug("Number of malloc() calls %d, number of free() calls %d\n", cnt_alloc, cnt_free );
	}
	debug("Rank %d Finished!\n", rank);
	MPI_Barrier(MPI_COMM_WORLD);
	MPI_Finalize();
	return 0;
}
Ejemplo n.º 11
0
// event driven routines to handle incoming packets
void TFTPServer::poll() {
    if ((state == suspended) || (state == deleted) || (state == tftperror)) {
        return;
    }
    ListenSock->set_blocking(false,1);
    char buff[592];
    int len = ListenSock->receiveFrom(client, buff, sizeof(buff));
    
    if (len == 0) {
        return;
    }
    printf("Got block with size %d\n\r", len);
    switch (state) {
        case listen: {
            switch (buff[1]) {
                case 0x01: // RRQ
                    ConnectRead(buff);
                    break;
                case 0x02: // WRQ
                    ConnectWrite(buff);
                    break;
                case 0x03: // DATA before connection established
                    Err("No data expected");
                    break;
                case 0x04:  // ACK before connection established
                    Err("No ack expected");
                    break;
                case 0x05: // ERROR packet received
                    #ifdef TFTP_DEBUG
                        TFTP_DEBUG("TFTP Eror received\n\r");
                    #endif
                    break;
                default:    // unknown TFTP packet type
                    Err("Unknown TFTP packet type");
                    break;
            } // switch buff[1]
            break; // case listen
        }
        case reading: {
            if (cmpHost())
	            switch (buff[1]) {
	                case 0x01:
	                    // if this is the receiving host, send first packet again
	                    if (blockcnt==1) {
                            Ack(0);
	                        dupcnt++;
	                    }
	                    if (dupcnt>10) { // too many dups, stop sending
	                        Err("Too many dups");
	                        fclose(fp);
	                        state=listen;
                            strcpy(remote_ip,"");
	                    }
	                    break;
	                case 0x02:
	                    // this should never happen, ignore
	                    Err("WRQ received on open read sochet");
                        fclose(fp);
                        state=listen;
                        strcpy(remote_ip,"");
	                    break; // case 0x02
	                case 0x03:
	                    // we are the sending side, ignore
	                    Err("Received data package on sending socket");
                        fclose(fp);
                        state=listen;
                        strcpy(remote_ip,"");
	                    break;
	                case 0x04:
	                    // last packet received, send next if there is one
	                    dupcnt = 0;
	                    if (len == 516) {
	                        getBlock();
	                        sendBlock();
	                    } else { //EOF
	                        fclose(fp);
	                        state = listen;
                            strcpy(remote_ip,"");
	                    }
	                    break;
	                default:  // this includes 0x05 errors
	                    Err("Received 0x05 error message");
	                    fclose(fp);
	                    state = listen;
                        strcpy(remote_ip,"");
	                    break;
	            } // switch (buff[1])
            else 
                printf("Ignoring package from other host during RRQ");
            break; // reading
        }
        case writing: {
            if (cmpHost()) 
	            switch (buff[1]) {
	                case 0x02: {
	                    // if this is a returning host, send ack again
	                    Ack(0);
	                    #ifdef TFTP_DEBUG
	                        TFTP_DEBUG("Resending Ack on WRQ");
	                    #endif
	                    break; // case 0x02
                    }
	                case 0x03: {
	                    int block = (buff[2] << 8) + buff[3];
	                    if ((blockcnt+1) == block) {
	                        Ack(block);
	                        // new packet
	                        char *data = &buff[4];
	                        fwrite(data, 1,len-4, fp);
	                        blockcnt++;
	                        dupcnt = 0;
	                    } else { // mismatch in block nr
	                        if ((blockcnt+1) < block) { // too high
                                Err("Packet count mismatch");
	                            fclose(fp);
	                            state = listen;
	                            remove(filename);
                                strcpy(remote_ip,"");
	                         } else { // duplicate packet, send ACK again
	                            if (dupcnt > 10) {
	                                Err("Too many dups");
	                                fclose(fp);
	                                remove(filename);
	                                state = listen;
	                            } else {
	                                Ack(blockcnt);
                                    dupcnt++;
	                            }
	                        }
	                    }
                        if (len<516) {
                            Ack(blockcnt);
                            fclose(fp);
                            state = listen;
                            strcpy(remote_ip,"");
                            filecnt++;
                            printf("File receive finished\n");
                        }
	                    break; // case 0x03
                    }
	                default: {
	                     Err("No idea why you're sending me this!");
	                     break; // default
                    }
	            } // switch (buff[1])
            else {
                printf("Ignoring packege from other host during WRQ");
            }
            break; // writing
        }
        case tftperror: {
        }
        case suspended: {
        }
        case deleted: {
        }
    } // state
}