aboutsummaryrefslogtreecommitdiffstats
path: root/Demos/Device/ClassDriver/VirtualSerialMassStorage/Lib/DataflashManager.c
blob: 146ad69b18f7b56060db4287f8f56c9af09941ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/*
             LUFA Library
     Copyright (C) Dean Camera, 2012.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/

/*
  Copyright 2012  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Functions to manage the physical Dataflash media, including reading and writing of
 *  blocks of data. These functions are called by the SCSI layer when data must be stored
 *  or retrieved to/from the physical storage media. If a different media is used (such
 *  as a SD card or EEPROM), functions similar to these will need to be generated.
 */

#define  INCLUDE_FROM_DATAFLASHMANAGER_C
#include "DataflashManager.h"

/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
 *  the pre-selected data OUT endpoint. This routine reads in OS sized blocks from the endpoint and writes
 *  them to the Dataflash in Dataflash page sized blocks.
 *
 *  \param[in] MSInterfaceInfo  Pointer to a structure containing a Mass Storage Class configuration and state
 *  \param[in] BlockAddress  Data block starting address for the write sequence
 *  \param[in] TotalBlocks   Number of blocks of data to write
 */
void DataflashManager_WriteBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo,
                                  const uint32_t BlockAddress,
                                  uint16_t TotalBlocks)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
	bool     UsingSecondBuffer   = false;

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
	/* Copy selected dataflash's current page contents to the Dataflash buffer */
	Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
	Dataflash_SendAddressBytes(CurrDFPage, 0);
	Dataflash_WaitWhileBusy();
#endif

	/* Send the Dataflash buffer write command */
	Dataflash_SendByte(DF_CMD_BUFF1WRITE);
	Dataflash_SendAddressBytes(0, CurrDFPageByte);

	/* Wait until endpoint is ready before continuing */
	if (Endpoint_WaitUntilReady())
	  return;

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if the endpoint is currently empty */
			if (!(Endpoint_IsReadWriteAllowed()))
			{
				/* Clear the current endpoint bank */
				Endpoint_ClearOUT();

				/* Wait until the host has sent another packet */
				if (Endpoint_WaitUntilReady())
				  return;
			}

			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Write the Dataflash buffer contents back to the Dataflash page */
				Dataflash_WaitWhileBusy();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
				Dataflash_SendAddressBytes(CurrDFPage, 0);

				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
				if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
				  UsingSecondBuffer = !(UsingSecondBuffer);

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
				/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
				if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
				{
					/* Copy selected dataflash's current page contents to the Dataflash buffer */
					Dataflash_WaitWhileBusy();
					Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
					Dataflash_SendAddressBytes(CurrDFPage, 0);
					Dataflash_WaitWhileBusy();
				}
#endif

				/* Send the Dataflash buffer write command */
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
				Dataflash_SendAddressBytes(0, 0);
			}

			/* Write one 16-byte chunk of data to the Dataflash */
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;

			/* Check if the current command is being aborted by the host */
			if (MSInterfaceInfo->State.IsMassStoreReset)
			  return;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Write the Dataflash buffer contents back to the Dataflash page */
	Dataflash_WaitWhileBusy();
	Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
	Dataflash_SendAddressBytes(CurrDFPage, 0x00);
	Dataflash_WaitWhileBusy();

	/* If the endpoint is empty, clear it ready for the next packet from the host */
	if (!(Endpoint_IsReadWriteAllowed()))
	  Endpoint_ClearOUT();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
 *  the pre-selected data IN endpoint. This routine reads in Dataflash page sized blocks from the Dataflash
 *  and writes them in OS sized blocks to the endpoint.
 *
 *  \param[in] MSInterfaceInfo  Pointer to a structure containing a Mass Storage Class configuration and state
 *  \param[in] BlockAddress  Data block starting address for the read sequence
 *  \param[in] TotalBlocks   Number of blocks of data to read
 */
void DataflashManager_ReadBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo,
                                 const uint32_t BlockAddress,
                                 uint16_t TotalBlocks)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

	/* Send the Dataflash main memory page read command */
	Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
	Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);

	/* Wait until endpoint is ready before continuing */
	if (Endpoint_WaitUntilReady())
	  return;

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if the endpoint is currently full */
			if (!(Endpoint_IsReadWriteAllowed()))
			{
				/* Clear the endpoint bank to send its contents to the host */
				Endpoint_ClearIN();

				/* Wait until the endpoint is ready for more data */
				if (Endpoint_WaitUntilReady())
				  return;
			}

			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

				/* Send the Dataflash main memory page read command */
				Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
				Dataflash_SendAddressBytes(CurrDFPage, 0);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
			}

			/* Read one 16-byte chunk of data from the Dataflash */
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;

			/* Check if the current command is being aborted by the host */
			if (MSInterfaceInfo->State.IsMassStoreReset)
			  return;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* If the endpoint is full, send its contents to the host */
	if (!(Endpoint_IsReadWriteAllowed()))
	  Endpoint_ClearIN();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
 *  the given RAM buffer. This routine reads in OS sized blocks from the buffer and writes them to the
 *  Dataflash in Dataflash page sized blocks. This can be linked to FAT libraries to write files to the
 *  Dataflash.
 *
 *  \param[in] BlockAddress  Data block starting address for the write sequence
 *  \param[in] TotalBlocks   Number of blocks of data to write
 *  \param[in] BufferPtr     Pointer to the data source RAM buffer
 */
void DataflashManager_WriteBlocks_RAM(const uint32_t BlockAddress,
                                      uint16_t TotalBlocks,
                                      uint8_t* BufferPtr)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
	bool     UsingSecondBuffer   = false;

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
	/* Copy selected dataflash's current page contents to the Dataflash buffer */
	Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
	Dataflash_SendAddressBytes(CurrDFPage, 0);
	Dataflash_WaitWhileBusy();
#endif

	/* Send the Dataflash buffer write command */
	Dataflash_SendByte(DF_CMD_BUFF1WRITE);
	Dataflash_SendAddressBytes(0, CurrDFPageByte);

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Write the Dataflash buffer contents back to the Dataflash page */
				Dataflash_WaitWhileBusy();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
				Dataflash_SendAddressBytes(CurrDFPage, 0);

				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
				if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
				  UsingSecondBuffer = !(UsingSecondBuffer);

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
				/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
				if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
				{
					/* Copy selected dataflash's current page contents to the Dataflash buffer */
					Dataflash_WaitWhileBusy();
					Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
					Dataflash_SendAddressBytes(CurrDFPage, 0);
					Dataflash_WaitWhileBusy();
				}
#endif

				/* Send the Dataflash buffer write command */
				Dataflash_ToggleSelectedChipCS();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
				Dataflash_SendAddressBytes(0, 0);
			}

			/* Write one 16-byte chunk of data to the Dataflash */
			for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
			  Dataflash_SendByte(*(BufferPtr++));

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Write the Dataflash buffer contents back to the Dataflash page */
	Dataflash_WaitWhileBusy();
	Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
	Dataflash_SendAddressBytes(CurrDFPage, 0x00);
	Dataflash_WaitWhileBusy();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
 *  the preallocated RAM buffer. This routine reads in Dataflash page sized blocks from the Dataflash
 *  and writes them in OS sized blocks to the given buffer. This can be linked to FAT libraries to read
 *  the files stored on the Dataflash.
 *
 *  \param[in] BlockAddress  Data block starting address for the read sequence
 *  \param[in] TotalBlocks   Number of blocks of data to read
 *  \param[out] BufferPtr    Pointer to the data destination RAM buffer
 */
void DataflashManager_ReadBlocks_RAM(const uint32_t BlockAddress,
                                     uint16_t TotalBlocks,
                                     uint8_t* BufferPtr)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

	/* Send the Dataflash main memory page read command */
	Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
	Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

				/* Send the Dataflash main memory page read command */
				Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
				Dataflash_SendAddressBytes(CurrDFPage, 0);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
			}

			/* Read one 16-byte chunk of data from the Dataflash */
			for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
			  *(BufferPtr++) = Dataflash_ReceiveByte();

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Disables the Dataflash memory write protection bits on the board Dataflash ICs, if enabled. */
void DataflashManager_ResetDataflashProtections(void)
{
	/* Select first Dataflash chip, send the read status register command */
	Dataflash_SelectChip(DATAFLASH_CHIP1);
	Dataflash_SendByte(DF_CMD_GETSTATUS);

	/* Check if sector protection is enabled */
	if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
	{
		Dataflash_ToggleSelectedChipCS();

		/* Send the commands to disable sector protection */
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
	}

	/* Select second Dataflash chip (if present on selected board), send read status register command */
	#if (DATAFLASH_TOTALCHIPS == 2)
	Dataflash_SelectChip(DATAFLASH_CHIP2);
	Dataflash_SendByte(DF_CMD_GETSTATUS);

	/* Check if sector protection is enabled */
	if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
	{
		Dataflash_ToggleSelectedChipCS();

		/* Send the commands to disable sector protection */
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
	}
	#endif

	/* Deselect current Dataflash chip */
	Dataflash_DeselectChip();
}

/** Performs a simple test on the attached Dataflash IC(s) to ensure that they are working.
 *
 *  \return Boolean true if all media chips are working, false otherwise
 */
bool DataflashManager_CheckDataflashOperation(void)
{
	uint8_t ReturnByte;

	/* Test first Dataflash IC is present and responding to commands */
	Dataflash_SelectChip(DATAFLASH_CHIP1);
	Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
	ReturnByte = Dataflash_ReceiveByte();
	Dataflash_DeselectChip();

	/* If returned data is invalid, fail the command */
	if (ReturnByte != DF_MANUFACTURER_ATMEL)
	  return false;

	#if (DATAFLASH_TOTALCHIPS == 2)
	/* Test second Dataflash IC is present and responding to commands */
	Dataflash_SelectChip(DATAFLASH_CHIP2);
	Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
	ReturnByte = Dataflash_ReceiveByte();
	Dataflash_DeselectChip();

	/* If returned data is invalid, fail the command */
	if (ReturnByte != DF_MANUFACTURER_ATMEL)
	  return false;
	#endif

	return true;
}
nt)conn->id : -1, strerror(saved_errno), str); _exit(2); } TDB_CONTEXT *tdb_context(struct connection *conn) { /* conn = NULL used in manual_node at setup. */ if (!conn || !conn->transaction) return tdb_ctx; return tdb_transaction_context(conn->transaction); } bool replace_tdb(const char *newname, TDB_CONTEXT *newtdb) { if (rename(newname, xs_daemon_tdb()) != 0) return false; tdb_close(tdb_ctx); tdb_ctx = talloc_steal(talloc_autofree_context(), newtdb); return true; } static char *sockmsg_string(enum xsd_sockmsg_type type) { switch (type) { case XS_DEBUG: return "DEBUG"; case XS_DIRECTORY: return "DIRECTORY"; case XS_READ: return "READ"; case XS_GET_PERMS: return "GET_PERMS"; case XS_WATCH: return "WATCH"; case XS_UNWATCH: return "UNWATCH"; case XS_TRANSACTION_START: return "TRANSACTION_START"; case XS_TRANSACTION_END: return "TRANSACTION_END"; case XS_INTRODUCE: return "INTRODUCE"; case XS_RELEASE: return "RELEASE"; case XS_GET_DOMAIN_PATH: return "GET_DOMAIN_PATH"; case XS_WRITE: return "WRITE"; case XS_MKDIR: return "MKDIR"; case XS_RM: return "RM"; case XS_SET_PERMS: return "SET_PERMS"; case XS_WATCH_EVENT: return "WATCH_EVENT"; case XS_ERROR: return "ERROR"; default: return "**UNKNOWN**"; } } static void trace_io(const struct connection *conn, const char *prefix, const struct buffered_data *data) { char string[64]; unsigned int i; if (tracefd < 0) return; write(tracefd, prefix, strlen(prefix)); sprintf(string, " %p ", conn); write(tracefd, string, strlen(string)); write(tracefd, sockmsg_string(data->hdr.msg.type), strlen(sockmsg_string(data->hdr.msg.type))); write(tracefd, " (", 2); for (i = 0; i < data->hdr.msg.len; i++) { if (data->buffer[i] == '\0') write(tracefd, " ", 1); else write(tracefd, data->buffer + i, 1); } write(tracefd, ")\n", 2); } void trace_create(const void *data, const char *type) { char string[64]; if (tracefd < 0) return; write(tracefd, "CREATE ", strlen("CREATE ")); write(tracefd, type, strlen(type)); sprintf(string, " %p\n", data); write(tracefd, string, strlen(string)); } void trace_destroy(const void *data, const char *type) { char string[64]; if (tracefd < 0) return; write(tracefd, "DESTROY ", strlen("DESTROY ")); write(tracefd, type, strlen(type)); sprintf(string, " %p\n", data); write(tracefd, string, strlen(string)); } void trace(const char *fmt, ...) { va_list arglist; char *str; if (tracefd < 0) return; va_start(arglist, fmt); str = talloc_vasprintf(NULL, fmt, arglist); va_end(arglist); write(tracefd, str, strlen(str)); talloc_free(str); } static bool write_messages(struct connection *conn) { int ret; struct buffered_data *out; out = list_top(&conn->out_list, struct buffered_data, list); if (out == NULL) return true; if (out->inhdr) { if (verbose) xprintf("Writing msg %s (%s) out to %p\n", sockmsg_string(out->hdr.msg.type), out->buffer, conn); ret = conn->write(conn, out->hdr.raw + out->used, sizeof(out->hdr) - out->used); if (ret < 0) return false; out->used += ret; if (out->used < sizeof(out->hdr)) return true; out->inhdr = false; out->used = 0; /* Second write might block if non-zero. */ if (out->hdr.msg.len && !conn->domain) return true; } ret = conn->write(conn, out->buffer + out->used, out->hdr.msg.len - out->used); if (ret < 0) return false; out->used += ret; if (out->used != out->hdr.msg.len) return true; trace_io(conn, "OUT", out); list_del(&out->list); talloc_free(out); return true; } static int destroy_conn(void *_conn) { struct connection *conn = _conn; /* Flush outgoing if possible, but don't block. */ if (!conn->domain) { fd_set set; struct timeval none; FD_ZERO(&set); FD_SET(conn->fd, &set); none.tv_sec = none.tv_usec = 0; while (!list_empty(&conn->out_list) && select(conn->fd+1, NULL, &set, NULL, &none) == 1) if (!write_messages(conn)) break; close(conn->fd); } list_del(&conn->list); trace_destroy(conn, "connection"); return 0; } static int initialize_set(fd_set *inset, fd_set *outset, int sock, int ro_sock) { struct connection *i; int max; FD_ZERO(inset); FD_ZERO(outset); FD_SET(sock, inset); max = sock; FD_SET(ro_sock, inset); if (ro_sock > max) max = ro_sock; FD_SET(event_fd, inset); if (event_fd > max) max = event_fd; list_for_each_entry(i, &connections, list) { if (i->domain) continue; FD_SET(i->fd, inset); if (!list_empty(&i->out_list)) FD_SET(i->fd, outset); if (i->fd > max) max = i->fd; } return max; } static int destroy_fd(void *_fd) { int *fd = _fd; close(*fd); return 0; } /* Return a pointer to an fd, self-closing and attached to this pathname. */ int *talloc_open(const char *pathname, int flags, int mode) { int *fd; fd = talloc(pathname, int); *fd = open(pathname, flags, mode); if (*fd < 0) { int saved_errno = errno; talloc_free(fd); errno = saved_errno; return NULL; } talloc_set_destructor(fd, destroy_fd); return fd; } /* Is child a subnode of parent, or equal? */ bool is_child(const char *child, const char *parent) { unsigned int len = strlen(parent); /* / should really be "" for this algorithm to work, but that's a * usability nightmare. */ if (streq(parent, "/")) return true; if (strncmp(child, parent, len) != 0) return false; return child[len] == '/' || child[len] == '\0'; } /* If it fails, returns NULL and sets errno. */ static struct node *read_node(struct connection *conn, const char *name) { TDB_DATA key, data; uint32_t *p; struct node *node; key.dptr = (void *)name; key.dsize = strlen(name); data = tdb_fetch(tdb_context(conn), key); if (data.dptr == NULL) { if (tdb_error(tdb_context(conn)) == TDB_ERR_NOEXIST) errno = ENOENT; else errno = EIO; return NULL; } node = talloc(name, struct node); node->name = talloc_strdup(node, name); node->parent = NULL; node->tdb = tdb_context(conn); talloc_steal(node, data.dptr); /* Datalen, childlen, number of permissions */ p = (uint32_t *)data.dptr; node->num_perms = p[0]; node->datalen = p[1]; node->childlen = p[2]; /* Permissions are struct xs_permissions. */ node->perms = (void *)&p[3]; /* Data is binary blob (usually ascii, no nul). */ node->data = node->perms + node->num_perms; /* Children is strings, nul separated. */ node->children = node->data + node->datalen; return node; } static bool write_node(struct connection *conn, const struct node *node) { TDB_DATA key, data; void *p; key.dptr = (void *)node->name; key.dsize = strlen(node->name); data.dsize = 3*sizeof(uint32_t) + node->num_perms*sizeof(node->perms[0]) + node->datalen + node->childlen; data.dptr = talloc_size(node, data.dsize); ((uint32_t *)data.dptr)[0] = node->num_perms; ((uint32_t *)data.dptr)[1] = node->datalen; ((uint32_t *)data.dptr)[2] = node->childlen; p = data.dptr + 3 * sizeof(uint32_t); memcpy(p, node->perms, node->num_perms*sizeof(node->perms[0])); p += node->num_perms*sizeof(node->perms[0]); memcpy(p, node->data, node->datalen); p += node->datalen; memcpy(p, node->children, node->childlen); /* TDB should set errno, but doesn't even set ecode AFAICT. */ if (tdb_store(tdb_context(conn), key, data, TDB_REPLACE) != 0) { errno = ENOSPC; return false; } return true; } static enum xs_perm_type perm_for_conn(struct connection *conn, struct xs_permissions *perms, unsigned int num) { unsigned int i; enum xs_perm_type mask = XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER; if (!conn->can_write) mask &= ~XS_PERM_WRITE; /* Owners and tools get it all... */ if (!conn->id || perms[0].id == conn->id) return (XS_PERM_READ|XS_PERM_WRITE|XS_PERM_OWNER) & mask; for (i = 1; i < num; i++) if (perms[i].id == conn->id) return perms[i].perms & mask; return perms[0].perms & mask; } static char *get_parent(const char *node) { char *slash = strrchr(node + 1, '/'); if (!slash) return talloc_strdup(node, "/"); return talloc_asprintf(node, "%.*s", (int)(slash - node), node); } /* What do parents say? */ static enum xs_perm_type ask_parents(struct connection *conn, const char *name) { struct node *node; do { name = get_parent(name); node = read_node(conn, name); if (node) break; } while (!streq(name, "/")); /* No permission at root? We're in trouble. */ if (!node) corrupt(conn, "No permissions file at root"); return perm_for_conn(conn, node->perms, node->num_perms); } /* We have a weird permissions system. You can allow someone into a * specific node without allowing it in the parents. If it's going to * fail, however, we don't want the errno to indicate any information * about the node. */ static int errno_from_parents(struct connection *conn, const char *node, int errnum, enum xs_perm_type perm) { /* We always tell them about memory failures. */ if (errnum == ENOMEM) return errnum; if (ask_parents(conn, node) & perm) return errnum; return EACCES; } /* If it fails, returns NULL and sets errno. */ struct node *get_node(struct connection *conn, const char *name, enum xs_perm_type perm) { struct node *node; if (!name || !is_valid_nodename(name)) { errno = EINVAL; return NULL; } node = read_node(conn, name); /* If we don't have permission, we don't have node. */ if (node) { if ((perm_for_conn(conn, node->perms, node->num_perms) & perm) != perm) node = NULL; } /* Clean up errno if they weren't supposed to know. */ if (!node) errno = errno_from_parents(conn, name, errno, perm); return node; } static struct buffered_data *new_buffer(void *ctx) { struct buffered_data *data; data = talloc(ctx, struct buffered_data); if (data == NULL) return NULL; data->inhdr = true; data->used = 0; data->buffer = NULL; return data; } /* Return length of string (including nul) at this offset. */ static unsigned int get_string(const struct buffered_data *data, unsigned int offset) { const char *nul; if (offset >= data->used) return 0; nul = memchr(data->buffer + offset, 0, data->used - offset); if (!nul) return 0; return nul - (data->buffer + offset) + 1; } /* Break input into vectors, return the number, fill in up to num of them. */ unsigned int get_strings(struct buffered_data *data, char *vec[], unsigned int num) { unsigned int off, i, len; off = i = 0; while ((len = get_string(data, off)) != 0) { if (i < num) vec[i] = data->buffer + off; i++; off += len; } return i; } void send_reply(struct connection *conn, enum xsd_sockmsg_type type, const void *data, unsigned int len) { struct buffered_data *bdata; /* Message is a child of the connection context for auto-cleanup. */ bdata = new_buffer(conn); bdata->buffer = talloc_array(bdata, char, len); /* Echo request header in reply unless this is an async watch event. */ if (type != XS_WATCH_EVENT) { memcpy(&bdata->hdr.msg, &conn->in->hdr.msg, sizeof(struct xsd_sockmsg)); } else { memset(&bdata->hdr.msg, 0, sizeof(struct xsd_sockmsg)); } /* Update relevant header fields and fill in the message body. */ bdata->hdr.msg.type = type; bdata->hdr.msg.len = len; memcpy(bdata->buffer, data, len); /* Queue for later transmission. */ list_add_tail(&bdata->list, &conn->out_list); } /* Some routines (write, mkdir, etc) just need a non-error return */ void send_ack(struct connection *conn, enum xsd_sockmsg_type type) { send_reply(conn, type, "OK", sizeof("OK")); } void send_error(struct connection *conn, int error) { unsigned int i; for (i = 0; error != xsd_errors[i].errnum; i++) { if (i == ARRAY_SIZE(xsd_errors) - 1) { eprintf("xenstored: error %i untranslatable", error); i = 0; /* EINVAL */ break; } } send_reply(conn, XS_ERROR, xsd_errors[i].errstring, strlen(xsd_errors[i].errstring) + 1); } static bool valid_chars(const char *node) { /* Nodes can have lots of crap. */ return (strspn(node, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789-/_@") == strlen(node)); } bool is_valid_nodename(const char *node) { /* Must start in /. */ if (!strstarts(node, "/")) return false; /* Cannot end in / (unless it's just "/"). */ if (strends(node, "/") && !streq(node, "/")) return false; /* No double //. */ if (strstr(node, "//")) return false; return valid_chars(node); } /* We expect one arg in the input: return NULL otherwise. */ static const char *onearg(struct buffered_data *in) { if (!in->used || get_string(in, 0) != in->used) return NULL; return in->buffer; } static char *perms_to_strings(const void *ctx, struct xs_permissions *perms, unsigned int num, unsigned int *len) { unsigned int i; char *strings = NULL; char buffer[MAX_STRLEN(unsigned int) + 1]; for (*len = 0, i = 0; i < num; i++) { if (!xs_perm_to_string(&perms[i], buffer)) return NULL; strings = talloc_realloc(ctx, strings, char, *len + strlen(buffer) + 1); strcpy(strings + *len, buffer); *len += strlen(buffer) + 1; } return strings; } char *canonicalize(struct connection *conn, const char *node) { const char *prefix; if (!node || strstarts(node, "/")) return (char *)node; prefix = get_implicit_path(conn); if (prefix) return talloc_asprintf(node, "%s/%s", prefix, node); return (char *)node; } bool check_event_node(const char *node) { if (!node || !strstarts(node, "@")) { errno = EINVAL; return false; } return true; } static void send_directory(struct connection *conn, const char *name) { struct node *node; name = canonicalize(conn, name); node = get_node(conn, name, XS_PERM_READ); if (!node) { send_error(conn, errno); return; } send_reply(conn, XS_DIRECTORY, node->children, node->childlen); } static void do_read(struct connection *conn, const char *name) { struct node *node; name = canonicalize(conn, name); node = get_node(conn, name, XS_PERM_READ); if (!node) { send_error(conn, errno); return; } send_reply(conn, XS_READ, node->data, node->datalen); } static void delete_node_single(struct connection *conn, struct node *node) { TDB_DATA key; key.dptr = (void *)node->name; key.dsize = strlen(node->name); if (tdb_delete(tdb_context(conn), key) != 0) corrupt(conn, "Could not delete '%s'", node->name); } /* Must not be / */ static char *basename(const char *name) { return strrchr(name, '/') + 1; } static struct node *construct_node(struct connection *conn, const char *name) { const char *base; unsigned int baselen; struct node *parent, *node; char *children, *parentname = get_parent(name); /* If parent doesn't exist, create it. */ parent = read_node(conn, parentname); if (!parent) parent = construct_node(conn, parentname); if (!parent) return NULL; /* Add child to parent. */ base = basename(name); baselen = strlen(base) + 1; children = talloc_array(name, char, parent->childlen + baselen); memcpy(children, parent->children, parent->childlen); memcpy(children + parent->childlen, base, baselen); parent->children = children; parent->childlen += baselen; /* Allocate node */ node = talloc(name, struct node); node->tdb = tdb_context(conn); node->name = talloc_strdup(node, name); /* Inherit permissions, except domains own what they create */ node->num_perms = parent->num_perms; node->perms = talloc_memdup(node, parent->perms, node->num_perms * sizeof(node->perms[0])); if (conn->id) node->perms[0].id = conn->id; /* No children, no data */ node->children = node->data = NULL; node->childlen = node->datalen = 0; node->parent = parent; return node; } static int destroy_node(void *_node) { struct node *node = _node; TDB_DATA key; if (streq(node->name, "/")) corrupt(NULL, "Destroying root node!"); key.dptr = (void *)node->name; key.dsize = strlen(node->name); tdb_delete(node->tdb, key); return 0; } /* Be careful: create heirarchy, put entry in existing parent *last*. * This helps fsck if we die during this. */ static struct node *create_node(struct connection *conn, const char *name, void *data, unsigned int datalen) { struct node *node, *i; node = construct_node(conn, name); if (!node) return NULL; node->data = data; node->datalen = datalen; /* We write out the nodes down, setting destructor in case * something goes wrong. */ for (i = node; i; i = i->parent) { if (!write_node(conn, i)) return NULL; talloc_set_destructor(i, destroy_node); } /* OK, now remove destructors so they stay around */ for (i = node; i; i = i->parent) talloc_set_destructor(i, NULL); return node; } /* path, data... */ static void do_write(struct connection *conn, struct buffered_data *in) { unsigned int offset, datalen; struct node *node; char *vec[1] = { NULL }; /* gcc4 + -W + -Werror fucks code. */ char *name; /* Extra "strings" can be created by binary data. */ if (get_strings(in, vec, ARRAY_SIZE(vec)) < ARRAY_SIZE(vec)) { send_error(conn, EINVAL); return; } offset = strlen(vec[0]) + 1; datalen = in->used - offset; name = canonicalize(conn, vec[0]); node = get_node(conn, name, XS_PERM_WRITE); if (!node) { /* No permissions, invalid input? */ if (errno != ENOENT) { send_error(conn, errno); return; } node = create_node(conn, name, in->buffer + offset, datalen); if (!node) { send_error(conn, errno); return; } } else { node->data = in->buffer + offset; node->datalen = datalen; if (!write_node(conn, node)){ send_error(conn, errno); return; } } add_change_node(conn->transaction, name, false); fire_watches(conn, name, false); send_ack(conn, XS_WRITE); } static void do_mkdir(struct connection *conn, const char *name) { struct node *node; name = canonicalize(conn, name); node = get_node(conn, name, XS_PERM_WRITE); /* If it already exists, fine. */ if (!node) { /* No permissions? */ if (errno != ENOENT) { send_error(conn, errno); return; } node = create_node(conn, name, NULL, 0); if (!node) { send_error(conn, errno); return; } add_change_node(conn->transaction, name, false); fire_watches(conn, name, false); } send_ack(conn, XS_MKDIR); } static void delete_node(struct connection *conn, struct node *node) { unsigned int i; /* Delete self, then delete children. If something goes wrong, * consistency check will clean up this way. */ delete_node_single(conn, node); /* Delete children, too. */ for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) { struct node *child; child = read_node(conn, talloc_asprintf(node, "%s/%s", node->name, node->children + i)); if (!child) corrupt(conn, "No child '%s' found", child); delete_node(conn, child); } } /* Delete memory using memmove. */ static void memdel(void *mem, unsigned off, unsigned len, unsigned total) { memmove(mem + off, mem + off + len, total - off - len); } static bool delete_child(struct connection *conn, struct node *node, const char *childname) { unsigned int i; for (i = 0; i < node->childlen; i += strlen(node->children+i) + 1) { if (streq(node->children+i, childname)) { memdel(node->children, i, strlen(childname) + 1, node->childlen); node->childlen -= strlen(childname) + 1; return write_node(conn, node); } } corrupt(conn, "Can't find child '%s' in %s", childname, node->name); } static void do_rm(struct connection *conn, const char *name) { struct node *node, *parent; name = canonicalize(conn, name); node = get_node(conn, name, XS_PERM_WRITE); if (!node) { /* Didn't exist already? Fine, if parent exists. */ if (errno == ENOENT) { node = read_node(conn, get_parent(name)); if (node) { send_ack(conn, XS_RM); return; } /* Restore errno, just in case. */ errno = ENOENT; } send_error(conn, errno); return; } if (streq(name, "/")) { send_error(conn, EINVAL); return; } /* Delete from parent first, then if something explodes fsck cleans. */ parent = read_node(conn, get_parent(name)); if (!parent) { send_error(conn, EINVAL); return; } if (!delete_child(conn, parent, basename(name))) { send_error(conn, EINVAL); return; } delete_node(conn, node); add_change_node(conn->transaction, name, true); fire_watches(conn, name, true); send_ack(conn, XS_RM); } static void do_get_perms(struct connection *conn, const char *name) { struct node *node; char *strings; unsigned int len; name = canonicalize(conn, name); node = get_node(conn, name, XS_PERM_READ); if (!node) { send_error(conn, errno); return; } strings = perms_to_strings(node, node->perms, node->num_perms, &len); if (!strings) send_error(conn, errno); else send_reply(conn, XS_GET_PERMS, strings, len); } static void do_set_perms(struct connection *conn, struct buffered_data *in) { unsigned int num; char *name, *permstr; struct node *node; num = xs_count_strings(in->buffer, in->used); if (num < 2) { send_error(conn, EINVAL); return; } /* First arg is node name. */ name = canonicalize(conn, in->buffer); permstr = in->buffer + strlen(in->buffer) + 1; num--; /* We must own node to do this (tools can do this too). */ node = get_node(conn, name, XS_PERM_WRITE|XS_PERM_OWNER); if (!node) { send_error(conn, errno); return; } node->perms = talloc_array(node, struct xs_permissions, num); node->num_perms = num; if (!xs_strings_to_perms(node->perms, num, permstr)) { send_error(conn, errno); return; } if (!write_node(conn, node)) { send_error(conn, errno); return; } add_change_node(conn->transaction, name, false); fire_watches(conn, name, false); send_ack(conn, XS_SET_PERMS); } /* Process "in" for conn: "in" will vanish after this conversation, so * we can talloc off it for temporary variables. May free "conn". */ static void process_message(struct connection *conn, struct buffered_data *in) { struct transaction *trans; trans = transaction_lookup(conn, in->hdr.msg.tx_id); if (IS_ERR(trans)) { send_error(conn, -PTR_ERR(trans)); return; } assert(conn->transaction == NULL); conn->transaction = trans; switch (in->hdr.msg.type) { case XS_DIRECTORY: send_directory(conn, onearg(in)); break; case XS_READ: do_read(conn, onearg(in)); break; case XS_WRITE: do_write(conn, in); break; case XS_MKDIR: do_mkdir(conn, onearg(in)); break; case XS_RM: do_rm(conn, onearg(in)); break; case XS_GET_PERMS: do_get_perms(conn, onearg(in)); break; case XS_SET_PERMS: do_set_perms(conn, in); break; case XS_DEBUG: if (streq(in->buffer, "print")) xprintf("debug: %s", in->buffer + get_string(in, 0)); #ifdef TESTING /* For testing, we allow them to set id. */ if (streq(in->buffer, "setid")) { conn->id = atoi(in->buffer + get_string(in, 0)); send_ack(conn, XS_DEBUG); } else if (streq(in->buffer, "failtest")) { if (get_string(in, 0) < in->used) srandom(atoi(in->buffer + get_string(in, 0))); send_ack(conn, XS_DEBUG); failtest = true; } #endif /* TESTING */ break; case XS_WATCH: do_watch(conn, in); break; case XS_UNWATCH: do_unwatch(conn, in); break; case XS_TRANSACTION_START: do_transaction_start(conn, in); break; case XS_TRANSACTION_END: do_transaction_end(conn, onearg(in)); break; case XS_INTRODUCE: do_introduce(conn, in); break; case XS_RELEASE: do_release(conn, onearg(in)); break; case XS_GET_DOMAIN_PATH: do_get_domain_path(conn, onearg(in)); break; default: eprintf("Client unknown operation %i", in->hdr.msg.type); send_error(conn, ENOSYS); break; } conn->transaction = NULL; } static int out_of_mem(void *data) { longjmp(*(jmp_buf *)data, 1); } static void consider_message(struct connection *conn) { jmp_buf talloc_fail; if (verbose) xprintf("Got message %s len %i from %p\n", sockmsg_string(conn->in->hdr.msg.type), conn->in->hdr.msg.len, conn); /* For simplicity, we kill the connection on OOM. */ talloc_set_fail_handler(out_of_mem, &talloc_fail); if (setjmp(talloc_fail)) { talloc_free(conn); goto end; } process_message(conn, conn->in); talloc_free(conn->in); conn->in = new_buffer(conn); end: talloc_set_fail_handler(NULL, NULL); if (talloc_total_blocks(NULL) != talloc_total_blocks(talloc_autofree_context()) + 1) { talloc_report_full(NULL, stderr); abort(); } } /* Errors in reading or allocating here mean we get out of sync, so we * drop the whole client connection. */ static void handle_input(struct connection *conn) { int bytes; struct buffered_data *in = conn->in; /* Not finished header yet? */ if (in->inhdr) { bytes = conn->read(conn, in->hdr.raw + in->used, sizeof(in->hdr) - in->used); if (bytes <= 0) goto bad_client; in->used += bytes; if (in->used != sizeof(in->hdr)) return; if (in->hdr.msg.len > PATH_MAX) { #ifndef TESTING syslog(LOG_DAEMON, "Client tried to feed us %i", in->hdr.msg.len); #endif goto bad_client; } in->buffer = talloc_array(in, char, in->hdr.msg.len); if (!in->buffer) goto bad_client; in->used = 0; in->inhdr = false; return; } bytes = conn->read(conn, in->buffer + in->used, in->hdr.msg.len - in->used); if (bytes < 0) goto bad_client; in->used += bytes; if (in->used != in->hdr.msg.len) return; trace_io(conn, "IN ", in); consider_message(conn); return; bad_client: /* Kill it. */ talloc_free(conn); } static void handle_output(struct connection *conn) { if (!write_messages(conn)) talloc_free(conn); } struct connection *new_connection(connwritefn_t *write, connreadfn_t *read) { struct connection *new; new = talloc(talloc_autofree_context(), struct connection); if (!new) return NULL; memset(new, 0, sizeof(*new)); new->fd = -1; new->write = write; new->read = read; new->can_write = true; INIT_LIST_HEAD(&new->out_list); INIT_LIST_HEAD(&new->watches); INIT_LIST_HEAD(&new->transaction_list); new->in = new_buffer(new); if (new->in == NULL) { talloc_free(new); return NULL; } list_add_tail(&new->list, &connections); talloc_set_destructor(new, destroy_conn); trace_create(new, "connection"); return new; } static int writefd(struct connection *conn, const void *data, unsigned int len) { return write(conn->fd, data, len); } static int readfd(struct connection *conn, void *data, unsigned int len) { return read(conn->fd, data, len); } static void accept_connection(int sock, bool canwrite) { int fd; struct connection *conn; fd = accept(sock, NULL, NULL); if (fd < 0) return; conn = new_connection(writefd, readfd); if (conn) { conn->fd = fd; conn->can_write = canwrite; } else close(fd); } #ifdef TESTING /* Valgrind can check our writes better if we don't use mmap */ #define TDB_FLAGS TDB_NOMMAP /* Useful for running under debugger. */ void dump_connection(void) { struct connection *i; list_for_each_entry(i, &connections, list) { printf("Connection %p:\n", i); printf(" state = %s\n", list_empty(&i->out_list) ? "OK" : "BUSY"); if (i->id) printf(" id = %i\n", i->id); if (!i->in->inhdr || i->in->used) printf(" got %i bytes of %s\n", i->in->used, i->in->inhdr ? "header" : "data"); #if 0 if (i->out) printf(" sending message %s (%s) out\n", sockmsg_string(i->out->hdr.msg.type), i->out->buffer); if (i->transaction) dump_transaction(i); if (i->domain) dump_domain(i); #endif dump_watches(i); } } #else #define TDB_FLAGS 0 #endif /* We create initial nodes manually. */ static void manual_node(const char *name, const char *child) { struct node *node; struct xs_permissions perms = { .id = 0, .perms = XS_PERM_READ }; node = talloc(NULL, struct node); node->name = name; node->perms = &perms; node->num_perms = 1; node->data = NULL; node->datalen = 0; node->children = (char *)child; if (child) node->childlen = strlen(child) + 1; else node->childlen = 0; if (!write_node(NULL, node)) barf_perror("Could not create initial node %s", name); talloc_free(node); } # static void setup_structure(void) { char *tdbname; tdbname = talloc_strdup(talloc_autofree_context(), xs_daemon_tdb()); tdb_ctx = tdb_open(tdbname, 0, TDB_FLAGS, O_RDWR, 0); if (!tdb_ctx) { tdb_ctx = tdb_open(tdbname, 7919, TDB_FLAGS, O_RDWR|O_CREAT, 0640); if (!tdb_ctx) barf_perror("Could not create tdb file %s", tdbname); manual_node("/", "tool"); manual_node("/tool", "xenstored"); manual_node("/tool/xenstored", NULL); } /* FIXME: Fsck */ } static void write_pidfile(const char *pidfile) { char buf[100]; int len; int fd; fd = open(pidfile, O_RDWR | O_CREAT, 0600); if (fd == -1) barf_perror("Opening pid file %s", pidfile); /* We exit silently if daemon already running. */ if (lockf(fd, F_TLOCK, 0) == -1) exit(0); len = sprintf(buf, "%d\n", getpid()); write(fd, buf, len); } /* Stevens. */ static void daemonize(void) { pid_t pid; /* Separate from our parent via fork, so init inherits us. */ if ((pid = fork()) < 0) barf_perror("Failed to fork daemon"); if (pid != 0) exit(0); /* Session leader so ^C doesn't whack us. */ setsid(); #ifndef TESTING /* Relative paths for socket names */ /* Move off any mount points we might be in. */ chdir("/"); #endif /* Discard our parent's old-fashioned umask prejudices. */ umask(0); } static struct option options[] = { { "no-domain-init", 0, NULL, 'D' }, { "pid-file", 1, NULL, 'F' }, { "no-fork", 0, NULL, 'N' }, { "output-pid", 0, NULL, 'P' }, { "trace-file", 1, NULL, 'T' }, { "verbose", 0, NULL, 'V' }, { NULL, 0, NULL, 0 } }; int main(int argc, char *argv[]) { int opt, *sock, *ro_sock, max; struct sockaddr_un addr; fd_set inset, outset; bool dofork = true; bool outputpid = false; bool no_domain_init = false; const char *pidfile = NULL; while ((opt = getopt_long(argc, argv, "DF:NPT:V", options, NULL)) != -1) { switch (opt) { case 'D': no_domain_init = true; break; case 'F': pidfile = optarg; break; case 'N': dofork = false; break; case 'P': outputpid = true; break; case 'T': tracefd = open(optarg, O_WRONLY|O_CREAT|O_APPEND, 0600); if (tracefd < 0) barf_perror("Could not open tracefile %s", optarg); write(tracefd, "\n***\n", strlen("\n***\n")); break; case 'V': verbose = true; break; } } if (optind != argc) barf("%s: No arguments desired", argv[0]); if (dofork) { openlog("xenstored", 0, LOG_DAEMON); daemonize(); } if (pidfile) write_pidfile(pidfile); talloc_enable_leak_report_full(); /* Create sockets for them to listen to. */ sock = talloc(talloc_autofree_context(), int); *sock = socket(PF_UNIX, SOCK_STREAM, 0); if (*sock < 0) barf_perror("Could not create socket"); ro_sock = talloc(talloc_autofree_context(), int); *ro_sock = socket(PF_UNIX, SOCK_STREAM, 0); if (*ro_sock < 0) barf_perror("Could not create socket"); talloc_set_destructor(sock, destroy_fd); talloc_set_destructor(ro_sock, destroy_fd); /* Don't kill us with SIGPIPE. */ signal(SIGPIPE, SIG_IGN); /* FIXME: Be more sophisticated, don't mug running daemon. */ unlink(xs_daemon_socket()); unlink(xs_daemon_socket_ro()); addr.sun_family = AF_UNIX; strcpy(addr.sun_path, xs_daemon_socket()); if (bind(*sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) barf_perror("Could not bind socket to %s", xs_daemon_socket()); strcpy(addr.sun_path, xs_daemon_socket_ro()); if (bind(*ro_sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) barf_perror("Could not bind socket to %s", xs_daemon_socket_ro()); if (chmod(xs_daemon_socket(), 0600) != 0 || chmod(xs_daemon_socket_ro(), 0660) != 0) barf_perror("Could not chmod sockets"); if (listen(*sock, 1) != 0 || listen(*ro_sock, 1) != 0) barf_perror("Could not listen on sockets"); /* If we're the first, create .perms file for root. */ setup_structure(); /* Listen to hypervisor. */ if (!no_domain_init) event_fd = domain_init(); /* Restore existing connections. */ restore_existing_connections(); if (outputpid) { printf("%i\n", getpid()); fflush(stdout); } /* close stdin/stdout now we're ready to accept connections */ if (dofork) { close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } #ifdef TESTING signal(SIGUSR1, stop_failtest); #endif /* Get ready to listen to the tools. */ max = initialize_set(&inset, &outset, *sock, *ro_sock); /* Main loop. */ /* FIXME: Rewrite so noone can starve. */ for (;;) { struct connection *i; if (select(max+1, &inset, &outset, NULL, NULL) < 0) { if (errno == EINTR) continue; barf_perror("Select failed"); } if (FD_ISSET(*sock, &inset)) accept_connection(*sock, true); if (FD_ISSET(*ro_sock, &inset)) accept_connection(*ro_sock, false); if (FD_ISSET(event_fd, &inset)) handle_event(); list_for_each_entry(i, &connections, list) { if (i->domain) continue; /* Operations can delete themselves or others * (xs_release): list is not safe after input, * so break. */ if (FD_ISSET(i->fd, &inset)) { handle_input(i); break; } if (FD_ISSET(i->fd, &outset)) { handle_output(i); break; } } /* Handle all possible I/O for domain connections. */ more: list_for_each_entry(i, &connections, list) { if (!i->domain) continue; if (domain_can_read(i)) { handle_input(i); goto more; } if (domain_can_write(i)) { handle_output(i); goto more; } } max = initialize_set(&inset, &outset, *sock, *ro_sock); } } /* * Local variables: * c-file-style: "linux" * indent-tabs-mode: t * c-indent-level: 8 * c-basic-offset: 8 * tab-width: 8 * End: */