Debian Codegraph @

simulator/ms-tpm-20-ref/TPMCmd/tpm/src/subsystem/NvDynamic.c

raw
1 /* Microsoft Reference Implementation for TPM 2.0
2 *
3 * The copyright in this software is being made available under the BSD License,
4 * included below. This software may be subject to other third party and
5 * contributor rights, including patent rights, and no such rights are granted
6 * under this license.
7 *
8 * Copyright (c) Microsoft Corporation
9 *
10 * All rights reserved.
11 *
12 * BSD License
13 *
14 * Redistribution and use in source and binary forms, with or without modification,
15 * are permitted provided that the following conditions are met:
16 *
17 * Redistributions of source code must retain the above copyright notice, this list
18 * of conditions and the following disclaimer.
19 *
20 * Redistributions in binary form must reproduce the above copyright notice, this
21 * list of conditions and the following disclaimer in the documentation and/or
22 * other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35 //** Introduction
36
37 // The NV memory is divided into two area: dynamic space for user defined NV
38 // indexes and evict objects, and reserved space for TPM persistent and state save
39 // data.
40 //
41 // The entries in dynamic space are a linked list of entries. Each entry has, as its
42 // first field, a size. If the size field is zero, it marks the end of the
43 // list.
44 //
45 // An Index allocation will contain an NV_INDEX structure. If the Index does not
46 // have the orderly attribute, the NV_INDEX is followed immediately by the NV data.
47 //
48 // An evict object entry contains a handle followed by an OBJECT structure. This
49 // results in both the Index and Evict Object having an identifying handle as the
50 // first field following the size field.
51 //
52 // When an Index has the orderly attribute, the data is kept in RAM. This RAM is
53 // saved to backing store in NV memory on any orderly shutdown. The entries in
54 // orderly memory are also a linked list using a size field as the first entry.
55 //
56 // The attributes of an orderly index are maintained in RAM memory in order to
57 // reduce the number of NV writes needed for orderly data. When an orderly index
58 // is created, an entry is made in the dynamic NV memory space that holds the Index
59 // authorizations (authPolicy and authValue) and the size of the data. This entry is
60 // only modified if the authValue of the index is changed. The more volatile data
61 // of the index is kept in RAM. When an orderly Index is created or deleted, the
62 // RAM data is copied to NV backing store so that the image in the backing store
63 // matches the layout of RAM. In normal operation. The RAM data is also copied on
64 // any orderly shutdown. In normal operation, the only other reason for writing
65 // to the backing store for RAM is when a counter is first written (TPMA_NV_WRITTEN
66 // changes from CLEAR to SET) or when a counter "rolls over."
67 //
68 // Static space contains items that are individually modifiable. The values are in
69 // the 'gp' PERSISTEND_DATA structure in RAM and mapped to locations in NV.
70 //
71
72 //** Includes, Defines and Data Definitions
73 #define NV_C
74 #include "Tpm.h"
75 #include "PlatformData.h"
76
77 //** Local Functions
78
79
80 //*** NvNext()
81 // This function provides a method to traverse every data entry in NV dynamic
82 // area.
83 //
84 // To begin with, parameter 'iter' should be initialized to NV_REF_INIT
85 // indicating the first element. Every time this function is called, the
86 // value in 'iter' would be adjusted pointing to the next element in
87 // traversal. If there is no next element, 'iter' value would be 0.
88 // This function returns the address of the 'data entry' pointed by the
89 // 'iter'. If there is no more element in the set, a 0 value is returned
90 // indicating the end of traversal.
91 //
92 static NV_REF
93 NvNext(
94 NV_REF *iter, // IN/OUT: the list iterator
95 TPM_HANDLE *handle // OUT: the handle of the next item.
96 )
97 {
98 NV_REF currentAddr;
99 NV_ENTRY_HEADER header;
100 //
101 // If iterator is at the beginning of list
102 if(*iter == NV_REF_INIT)
103 {
104 // Initialize iterator
105 *iter = NV_USER_DYNAMIC;
106 }
107 // Step over the size field and point to the handle
108 currentAddr = *iter + sizeof(UINT32);
109
110 // read the header of the next entry
111 NvRead(&header, *iter, sizeof(NV_ENTRY_HEADER));
112
113 // if the size field is zero, then we have hit the end of the list
114 if(header.size == 0)
115 // leave the *iter pointing at the end of the list
116 return 0;
117 // advance the header by the size of the entry
118 *iter += header.size;
119
120 if(handle != NULL)
121 *handle = header.handle;
122 return currentAddr;
123 }
124
125
126 //*** NvNextByType()
127 // This function returns a reference to the next NV entry of the desired type
128 // Return Type: NV_REF
129 // 0 end of list
130 // != 0 the next entry of the indicated type
131 static NV_REF
132 NvNextByType(
133 TPM_HANDLE *handle, // OUT: the handle of the found type
134 NV_REF *iter, // IN: the iterator
135 TPM_HT type // IN: the handle type to look for
136 )
137 {
138 NV_REF addr;
139 TPM_HANDLE nvHandle;
140 //
141 while((addr = NvNext(iter, &nvHandle)) != 0)
142 {
143 // addr: the address of the location containing the handle of the value
144 // iter: the next location.
145 if(HandleGetType(nvHandle) == type)
146 break;
147 }
148 if(handle != NULL)
149 *handle = nvHandle;
150 return addr;
151 }
152
153 //*** NvNextIndex()
154 // This function returns the reference to the next NV Index entry. A value
155 // of 0 indicates the end of the list.
156 // Return Type: NV_REF
157 // 0 end of list
158 // != 0 the next reference
159 #define NvNextIndex(handle, iter) \
160 NvNextByType(handle, iter, TPM_HT_NV_INDEX)
161
162 //*** NvNextEvict()
163 // This function returns the offset in NV of the next evict object entry. A value
164 // of 0 indicates the end of the list.
165 #define NvNextEvict(handle, iter) \
166 NvNextByType(handle, iter, TPM_HT_PERSISTENT)
167
168 //*** NvGetEnd()
169 // Function to find the end of the NV dynamic data list
170 static NV_REF
171 NvGetEnd(
172 void
173 )
174 {
175 NV_REF iter = NV_REF_INIT;
176 NV_REF currentAddr;
177 //
178 // Scan until the next address is 0
179 while((currentAddr = NvNext(&iter, NULL)) != 0);
180 return iter;
181 }
182
183 //*** NvGetFreeBytes
184 // This function returns the number of free octets in NV space.
185 static UINT32
186 NvGetFreeBytes(
187 void
188 )
189 {
190 // This does not have an overflow issue because NvGetEnd() cannot return a value
191 // that is larger than s_evictNvEnd. This is because there is always a 'stop'
192 // word in the NV memory that terminates the search for the end before the
193 // value can go past s_evictNvEnd.
194 return s_evictNvEnd - NvGetEnd();
195 }
196
197 //*** NvTestSpace()
198 // This function will test if there is enough space to add a new entity.
199 // Return Type: BOOL
200 // TRUE(1) space available
201 // FALSE(0) no enough space
202 static BOOL
203 NvTestSpace(
204 UINT32 size, // IN: size of the entity to be added
205 BOOL isIndex, // IN: TRUE if the entity is an index
206 BOOL isCounter // IN: TRUE if the index is a counter
207 )
208 {
209 UINT32 remainBytes = NvGetFreeBytes();
210 UINT32 reserved = sizeof(UINT32) // size of the forward pointer
211 + sizeof(NV_LIST_TERMINATOR);
212 //
213 // Do a compile time sanity check on the setting for NV_MEMORY_SIZE
214 #if NV_MEMORY_SIZE < 1024
215 #error "NV_MEMORY_SIZE probably isn't large enough"
216 #endif
217
218 // For NV Index, need to make sure that we do not allocate an Index if this
219 // would mean that the TPM cannot allocate the minimum number of evict
220 // objects.
221 if(isIndex)
222 {
223 // Get the number of persistent objects allocated
224 UINT32 persistentNum = NvCapGetPersistentNumber();
225
226 // If we have not allocated the requisite number of evict objects, then we
227 // need to reserve space for them.
228 // NOTE: some of this is not written as simply as it might seem because
229 // the values are all unsigned and subtracting needs to be done carefully
230 // so that an underflow doesn't cause problems.
231 if(persistentNum < MIN_EVICT_OBJECTS)
232 reserved += (MIN_EVICT_OBJECTS - persistentNum) * NV_EVICT_OBJECT_SIZE;
233 }
234 // If this is not an index or is not a counter, reserve space for the
235 // required number of counter indexes
236 if(!isIndex || !isCounter)
237 {
238 // Get the number of counters
239 UINT32 counterNum = NvCapGetCounterNumber();
240
241 // If the required number of counters have not been allocated, reserved
242 // space for the extra needed counters
243 if(counterNum < MIN_COUNTER_INDICES)
244 reserved += (MIN_COUNTER_INDICES - counterNum) * NV_INDEX_COUNTER_SIZE;
245 }
246 // Check that the requested allocation will fit after making sure that there
247 // will be no chance of overflow
248 return ((reserved < remainBytes)
249 && (size <= remainBytes)
250 && (size + reserved <= remainBytes));
251 }
252
253 //*** NvWriteNvListEnd()
254 // Function to write the list terminator.
255 NV_REF
256 NvWriteNvListEnd(
257 NV_REF end
258 )
259 {
260 // Marker is initialized with zeros
261 BYTE listEndMarker[sizeof(NV_LIST_TERMINATOR)] = {0};
262 UINT64 maxCount = NvReadMaxCount();
263 //
264 // This is a constant check that can be resolved at compile time.
265 cAssert(sizeof(UINT64) <= sizeof(NV_LIST_TERMINATOR) - sizeof(UINT32));
266
267 // Copy the maxCount value to the marker buffer
268 MemoryCopy(&listEndMarker[sizeof(UINT32)], &maxCount, sizeof(UINT64));
269 pAssert(end + sizeof(NV_LIST_TERMINATOR) <= s_evictNvEnd);
270
271 // Write it to memory
272 NvWrite(end, sizeof(NV_LIST_TERMINATOR), &listEndMarker);
273 return end + sizeof(NV_LIST_TERMINATOR);
274 }
275
276
277 //*** NvAdd()
278 // This function adds a new entity to NV.
279 //
280 // This function requires that there is enough space to add a new entity (i.e.,
281 // that NvTestSpace() has been called and the available space is at least as
282 // large as the required space).
283 //
284 // The 'totalSize' will be the size of 'entity'. If a handle is added, this
285 // function will increase the size accordingly.
286 static TPM_RC
287 NvAdd(
288 UINT32 totalSize, // IN: total size needed for this entity For
289 // evict object, totalSize is the same as
290 // bufferSize. For NV Index, totalSize is
291 // bufferSize plus index data size
292 UINT32 bufferSize, // IN: size of initial buffer
293 TPM_HANDLE handle, // IN: optional handle
294 BYTE *entity // IN: initial buffer
295 )
296 {
297 NV_REF newAddr; // IN: where the new entity will start
298 NV_REF nextAddr;
299 //
300 RETURN_IF_NV_IS_NOT_AVAILABLE;
301
302 // Get the end of data list
303 newAddr = NvGetEnd();
304
305 // Step over the forward pointer
306 nextAddr = newAddr + sizeof(UINT32);
307
308 // Optionally write the handle. For indexes, the handle is TPM_RH_UNASSIGNED
309 // so that the handle in the nvIndex is used instead of writing this value
310 if(handle != TPM_RH_UNASSIGNED)
311 {
312 NvWrite((UINT32)nextAddr, sizeof(TPM_HANDLE), &handle);
313 nextAddr += sizeof(TPM_HANDLE);
314 }
315 // Write entity data
316 NvWrite((UINT32)nextAddr, bufferSize, entity);
317
318 // Advance the pointer by the amount of the total
319 nextAddr += totalSize;
320
321 // Finish by writing the link value
322
323 // Write the next offset (relative addressing)
324 totalSize = nextAddr - newAddr;
325
326 // Write link value
327 NvWrite((UINT32)newAddr, sizeof(UINT32), &totalSize);
328
329 // Write the list terminator
330 NvWriteNvListEnd(nextAddr);
331
332 return TPM_RC_SUCCESS;
333 }
334
335 //*** NvDelete()
336 // This function is used to delete an NV Index or persistent object from NV memory.
337 static TPM_RC
338 NvDelete(
339 NV_REF entityRef // IN: reference to entity to be deleted
340 )
341 {
342 UINT32 entrySize;
343 // adjust entityAddr to back up and point to the forward pointer
344 NV_REF entryRef = entityRef - sizeof(UINT32);
345 NV_REF endRef = NvGetEnd();
346 NV_REF nextAddr; // address of the next entry
347 //
348 RETURN_IF_NV_IS_NOT_AVAILABLE;
349
350 // Get the offset of the next entry. That is, back up and point to the size
351 // field of the entry
352 NvRead(&entrySize, entryRef, sizeof(UINT32));
353
354 // The next entry after the one being deleted is at a relative offset
355 // from the current entry
356 nextAddr = entryRef + entrySize;
357
358 // If this is not the last entry, move everything up
359 if(nextAddr < endRef)
360 {
361 pAssert(nextAddr > entryRef);
362 _plat__NvMemoryMove(nextAddr,
363 entryRef,
364 (endRef - nextAddr));
365 }
366 // The end of the used space is now moved up by the amount of space we just
367 // reclaimed
368 endRef -= entrySize;
369
370 // Write the end marker, and make the new end equal to the first byte after
371 // the just added end value. This will automatically update the NV value for
372 // maxCounter.
373 // NOTE: This is the call that sets flag to cause NV to be updated
374 endRef = NvWriteNvListEnd(endRef);
375
376 // Clear the reclaimed memory
377 _plat__NvMemoryClear(endRef, entrySize);
378
379 return TPM_RC_SUCCESS;
380 }
381
382 //************************************************
383 //** RAM-based NV Index Data Access Functions
384 //************************************************
385 //*** Introduction
386 // The data layout in ram buffer is {size of(NV_handle + attributes + data
387 // NV_handle, attributes, data}
388 // for each NV Index data stored in RAM.
389 //
390 // NV storage associated with orderly data is updated when a NV Index is added
391 // but NOT when the data or attributes are changed. Orderly data is only updated
392 // to NV on an orderly shutdown (TPM2_Shutdown())
393
394 //*** NvRamNext()
395 // This function is used to iterate trough the list of Ram Index values. *iter needs
396 // to be initialized by calling
397 static NV_RAM_REF
398 NvRamNext(
399 NV_RAM_REF *iter, // IN/OUT: the list iterator
400 TPM_HANDLE *handle // OUT: the handle of the next item.
401 )
402 {
403 NV_RAM_REF currentAddr;
404 NV_RAM_HEADER header;
405 //
406 // If iterator is at the beginning of list
407 if(*iter == NV_RAM_REF_INIT)
408 {
409 // Initialize iterator
410 *iter = &s_indexOrderlyRam[0];
411 }
412 // if we are going to return what the iter is currently pointing to...
413 currentAddr = *iter;
414
415 // If iterator reaches the end of NV space, then don't advance and return
416 // that we are at the end of the list. The end of the list occurs when
417 // we don't have space for a size and a handle
418 if(currentAddr + sizeof(NV_RAM_HEADER) > RAM_ORDERLY_END)
419 return NULL;
420 // read the header of the next entry
421 MemoryCopy(&header, currentAddr, sizeof(NV_RAM_HEADER));
422
423 // if the size field is zero, then we have hit the end of the list
424 if(header.size == 0)
425 // leave the *iter pointing at the end of the list
426 return NULL;
427 // advance the header by the size of the entry
428 *iter = currentAddr + header.size;
429
430 // pAssert(*iter <= RAM_ORDERLY_END);
431 if(handle != NULL)
432 *handle = header.handle;
433 return currentAddr;
434 }
435
436 //*** NvRamGetEnd()
437 // This routine performs the same function as NvGetEnd() but for the RAM data.
438 static NV_RAM_REF
439 NvRamGetEnd(
440 void
441 )
442 {
443 NV_RAM_REF iter = NV_RAM_REF_INIT;
444 NV_RAM_REF currentAddr;
445 //
446 // Scan until the next address is 0
447 while((currentAddr = NvRamNext(&iter, NULL)) != 0);
448 return iter;
449 }
450
451 //*** NvRamTestSpaceIndex()
452 // This function indicates if there is enough RAM space to add a data for a
453 // new NV Index.
454 // Return Type: BOOL
455 // TRUE(1) space available
456 // FALSE(0) no enough space
457 static BOOL
458 NvRamTestSpaceIndex(
459 UINT32 size // IN: size of the data to be added to RAM
460 )
461 {
462 UINT32 remaining = (UINT32)(RAM_ORDERLY_END - NvRamGetEnd());
463 UINT32 needed = sizeof(NV_RAM_HEADER) + size;
464 //
465 // NvRamGetEnd points to the next available byte.
466 return remaining >= needed;
467 }
468
469 //*** NvRamGetIndex()
470 // This function returns the offset of NV data in the RAM buffer
471 //
472 // This function requires that NV Index is in RAM. That is, the
473 // index must be known to exist.
474 static NV_RAM_REF
475 NvRamGetIndex(
476 TPMI_RH_NV_INDEX handle // IN: NV handle
477 )
478 {
479 NV_RAM_REF iter = NV_RAM_REF_INIT;
480 NV_RAM_REF currentAddr;
481 TPM_HANDLE foundHandle;
482 //
483 while((currentAddr = NvRamNext(&iter, &foundHandle)) != 0)
484 {
485 if(handle == foundHandle)
486 break;
487 }
488 return currentAddr;
489 }
490
491 //*** NvUpdateIndexOrderlyData()
492 // This function is used to cause an update of the orderly data to the NV backing
493 // store.
494 void
495 NvUpdateIndexOrderlyData(
496 void
497 )
498 {
499 // Write reserved RAM space to NV
500 NvWrite(NV_INDEX_RAM_DATA, sizeof(s_indexOrderlyRam), s_indexOrderlyRam);
501 }
502
503 //*** NvAddRAM()
504 // This function adds a new data area to RAM.
505 //
506 // This function requires that enough free RAM space is available to add
507 // the new data.
508 //
509 // This function should be called after the NV Index space has been updated
510 // and the index removed. This insures that NV is available so that checking
511 // for NV availability is not required during this function.
512 static void
513 NvAddRAM(
514 TPMS_NV_PUBLIC *index // IN: the index descriptor
515 )
516 {
517 NV_RAM_HEADER header;
518 NV_RAM_REF end = NvRamGetEnd();
519 //
520 header.size = sizeof(NV_RAM_HEADER) + index->dataSize;
521 header.handle = index->nvIndex;
522 MemoryCopy(&header.attributes, &index->attributes, sizeof(TPMA_NV));
523
524 pAssert(ORDERLY_RAM_ADDRESS_OK(end, header.size));
525
526 // Copy the header to the memory
527 MemoryCopy(end, &header, sizeof(NV_RAM_HEADER));
528
529 // Clear the data area (just in case)
530 MemorySet(end + sizeof(NV_RAM_HEADER), 0, index->dataSize);
531
532 // Step over this new entry
533 end += header.size;
534
535 // If the end marker will fit, add it
536 if(end + sizeof(UINT32) < RAM_ORDERLY_END)
537 MemorySet(end, 0, sizeof(UINT32));
538 // Write reserved RAM space to NV to reflect the newly added NV Index
539 SET_NV_UPDATE(UT_ORDERLY);
540
541 return;
542 }
543
544 //*** NvDeleteRAM()
545 // This function is used to delete a RAM-backed NV Index data area.
546 // The space used by the entry are overwritten by the contents of the
547 // Index data that comes after (the data is moved up to fill the hole left
548 // by removing this index. The reclaimed space is cleared to zeros.
549 // This function assumes the data of NV Index exists in RAM.
550 //
551 // This function should be called after the NV Index space has been updated
552 // and the index removed. This insures that NV is available so that checking
553 // for NV availability is not required during this function.
554 static void
555 NvDeleteRAM(
556 TPMI_RH_NV_INDEX handle // IN: NV handle
557 )
558 {
559 NV_RAM_REF nodeAddress;
560 NV_RAM_REF nextNode;
561 UINT32 size;
562 NV_RAM_REF lastUsed = NvRamGetEnd();
563 //
564 nodeAddress = NvRamGetIndex(handle);
565
566 pAssert(nodeAddress != 0);
567
568 // Get node size
569 MemoryCopy(&size, nodeAddress, sizeof(size));
570
571 // Get the offset of next node
572 nextNode = nodeAddress + size;
573
574 // Copy the data
575 MemoryCopy(nodeAddress, nextNode, (int)(lastUsed - nextNode));
576
577 // Clear out the reclaimed space
578 MemorySet(lastUsed - size, 0, size);
579
580 // Write reserved RAM space to NV to reflect the newly delete NV Index
581 SET_NV_UPDATE(UT_ORDERLY);
582
583 return;
584 }
585
586 //*** NvReadIndex()
587 // This function is used to read the NV Index NV_INDEX. This is used so that the
588 // index information can be compressed and only this function would be needed
589 // to decompress it. Mostly, compression would only be able to save the space
590 // needed by the policy.
591 void
592 NvReadNvIndexInfo(
593 NV_REF ref, // IN: points to NV where index is located
594 NV_INDEX *nvIndex // OUT: place to receive index data
595 )
596 {
597 pAssert(nvIndex != NULL);
598 NvRead(nvIndex, ref, sizeof(NV_INDEX));
599 return;
600 }
601
602 //*** NvReadObject()
603 // This function is used to read a persistent object. This is used so that the
604 // object information can be compressed and only this function would be needed
605 // to uncompress it.
606 void
607 NvReadObject(
608 NV_REF ref, // IN: points to NV where index is located
609 OBJECT *object // OUT: place to receive the object data
610 )
611 {
612 NvRead(object, (ref + sizeof(TPM_HANDLE)), sizeof(OBJECT));
613 return;
614 }
615
616 //*** NvFindEvict()
617 // This function will return the NV offset of an evict object
618 // Return Type: UINT32
619 // 0 evict object not found
620 // != 0 offset of evict object
621 static NV_REF
622 NvFindEvict(
623 TPM_HANDLE nvHandle,
624 OBJECT *object
625 )
626 {
627 NV_REF found = NvFindHandle(nvHandle);
628 //
629 // If we found the handle and the request included an object pointer, fill it in
630 if(found != 0 && object != NULL)
631 NvReadObject(found, object);
632 return found;
633 }
634
635 //*** NvIndexIsDefined()
636 // See if an index is already defined
637 BOOL
638 NvIndexIsDefined(
639 TPM_HANDLE nvHandle // IN: Index to look for
640 )
641 {
642 return (NvFindHandle(nvHandle) != 0);
643 }
644
645 //*** NvConditionallyWrite()
646 // Function to check if the data to be written has changed
647 // and write it if it has
648 // Return Type: TPM_RC
649 // TPM_RC_NV_RATE NV is unavailable because of rate limit
650 // TPM_RC_NV_UNAVAILABLE NV is inaccessible
651 static TPM_RC
652 NvConditionallyWrite(
653 NV_REF entryAddr, // IN: stating address
654 UINT32 size, // IN: size of the data to write
655 void *data // IN: the data to write
656 )
657 {
658 // If the index data is actually changed, then a write to NV is required
659 if(_plat__NvIsDifferent(entryAddr, size, data))
660 {
661 // Write the data if NV is available
662 if(g_NvStatus == TPM_RC_SUCCESS)
663 {
664 NvWrite(entryAddr, size, data);
665 }
666 return g_NvStatus;
667 }
668 return TPM_RC_SUCCESS;
669 }
670
671 //*** NvReadNvIndexAttributes()
672 // This function returns the attributes of an NV Index.
673 static TPMA_NV
674 NvReadNvIndexAttributes(
675 NV_REF locator // IN: reference to an NV index
676 )
677 {
678 TPMA_NV attributes;
679 //
680 NvRead(&attributes,
681 locator + offsetof(NV_INDEX, publicArea.attributes),
682 sizeof(TPMA_NV));
683 return attributes;
684 }
685
686 //*** NvReadRamIndexAttributes()
687 // This function returns the attributes from the RAM header structure. This function
688 // is used to deal with the fact that the header structure is only byte aligned.
689 static TPMA_NV
690 NvReadRamIndexAttributes(
691 NV_RAM_REF ref // IN: pointer to a NV_RAM_HEADER
692 )
693 {
694 TPMA_NV attributes;
695 //
696 MemoryCopy(&attributes, ref + offsetof(NV_RAM_HEADER, attributes),
697 sizeof(TPMA_NV));
698 return attributes;
699 }
700
701 //*** NvWriteNvIndexAttributes()
702 // This function is used to write just the attributes of an index to NV.
703 // Return type: TPM_RC
704 // TPM_RC_NV_RATE NV is rate limiting so retry
705 // TPM_RC_NV_UNAVAILABLE NV is not available
706 static TPM_RC
707 NvWriteNvIndexAttributes(
708 NV_REF locator, // IN: location of the index
709 TPMA_NV attributes // IN: attributes to write
710 )
711 {
712 return NvConditionallyWrite(
713 locator + offsetof(NV_INDEX, publicArea.attributes),
714 sizeof(TPMA_NV),
715 &attributes);
716 }
717
718 //*** NvWriteRamIndexAttributes()
719 // This function is used to write the index attributes into an unaligned structure
720 static void
721 NvWriteRamIndexAttributes(
722 NV_RAM_REF ref, // IN: address of the header
723 TPMA_NV attributes // IN: the attributes to write
724 )
725 {
726 MemoryCopy(ref + offsetof(NV_RAM_HEADER, attributes), &attributes,
727 sizeof(TPMA_NV));
728 return;
729 }
730
731 //************************************************
732 //** Externally Accessible Functions
733 //************************************************
734
735 //*** NvIsPlatformPersistentHandle()
736 // This function indicates if a handle references a persistent object in the
737 // range belonging to the platform.
738 // Return Type: BOOL
739 // TRUE(1) handle references a platform persistent object
740 // and may reference an owner persistent object either
741 // FALSE(0) handle does not reference platform persistent object
742 BOOL
743 NvIsPlatformPersistentHandle(
744 TPM_HANDLE handle // IN: handle
745 )
746 {
747 return (handle >= PLATFORM_PERSISTENT && handle <= PERSISTENT_LAST);
748 }
749
750 //*** NvIsOwnerPersistentHandle()
751 // This function indicates if a handle references a persistent object in the
752 // range belonging to the owner.
753 // Return Type: BOOL
754 // TRUE(1) handle is owner persistent handle
755 // FALSE(0) handle is not owner persistent handle and may not be
756 // a persistent handle at all
757 BOOL
758 NvIsOwnerPersistentHandle(
759 TPM_HANDLE handle // IN: handle
760 )
761 {
762 return (handle >= PERSISTENT_FIRST && handle < PLATFORM_PERSISTENT);
763 }
764
765 //*** NvIndexIsAccessible()
766 //
767 // This function validates that a handle references a defined NV Index and
768 // that the Index is currently accessible.
769 // Return Type: TPM_RC
770 // TPM_RC_HANDLE the handle points to an undefined NV Index
771 // If shEnable is CLEAR, this would include an index
772 // created using ownerAuth. If phEnableNV is CLEAR,
773 // this would include and index created using
774 // platformAuth
775 // TPM_RC_NV_READLOCKED Index is present but locked for reading and command
776 // does not write to the index
777 // TPM_RC_NV_WRITELOCKED Index is present but locked for writing and command
778 // writes to the index
779 TPM_RC
780 NvIndexIsAccessible(
781 TPMI_RH_NV_INDEX handle // IN: handle
782 )
783 {
784 NV_INDEX *nvIndex = NvGetIndexInfo(handle, NULL);
785 //
786 if(nvIndex == NULL)
787 // If index is not found, return TPM_RC_HANDLE
788 return TPM_RC_HANDLE;
789 if(gc.shEnable == FALSE || gc.phEnableNV == FALSE)
790 {
791 // if shEnable is CLEAR, an ownerCreate NV Index should not be
792 // indicated as present
793 if(!IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, PLATFORMCREATE))
794 {
795 if(gc.shEnable == FALSE)
796 return TPM_RC_HANDLE;
797 }
798 // if phEnableNV is CLEAR, a platform created Index should not
799 // be visible
800 else if(gc.phEnableNV == FALSE)
801 return TPM_RC_HANDLE;
802 }
803 #if 0 // Writelock test for debug
804 // If the Index is write locked and this is an NV Write operation...
805 if(IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITELOCKED)
806 && IsWriteOperation(commandIndex))
807 {
808 // then return a locked indication unless the command is TPM2_NV_WriteLock
809 if(GetCommandCode(commandIndex) != TPM_CC_NV_WriteLock)
810 return TPM_RC_NV_LOCKED;
811 return TPM_RC_SUCCESS;
812 }
813 #endif
814 #if 0 // Readlock Test for debug
815 // If the Index is read locked and this is an NV Read operation...
816 if(IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, READLOCKED)
817 && IsReadOperation(commandIndex))
818 {
819 // then return a locked indication unless the command is TPM2_NV_ReadLock
820 if(GetCommandCode(commandIndex) != TPM_CC_NV_ReadLock)
821 return TPM_RC_NV_LOCKED;
822 }
823 #endif
824 // NV Index is accessible
825 return TPM_RC_SUCCESS;
826 }
827
828 //*** NvGetEvictObject()
829 // This function is used to dereference an evict object handle and get a pointer
830 // to the object.
831 // Return Type: TPM_RC
832 // TPM_RC_HANDLE the handle does not point to an existing
833 // persistent object
834 TPM_RC
835 NvGetEvictObject(
836 TPM_HANDLE handle, // IN: handle
837 OBJECT *object // OUT: object data
838 )
839 {
840 NV_REF entityAddr; // offset points to the entity
841 //
842 // Find the address of evict object and copy to object
843 entityAddr = NvFindEvict(handle, object);
844
845 // whether there is an error or not, make sure that the evict
846 // status of the object is set so that the slot will get freed on exit
847 // Must do this after NvFindEvict loads the object
848 object->attributes.evict = SET;
849
850 // If handle is not found, return an error
851 if(entityAddr == 0)
852 return TPM_RC_HANDLE;
853 return TPM_RC_SUCCESS;
854 }
855
856 //*** NvIndexCacheInit()
857 // Function to initialize the Index cache
858 void
859 NvIndexCacheInit(
860 void
861 )
862 {
863 s_cachedNvRef = NV_REF_INIT;
864 s_cachedNvRamRef = NV_RAM_REF_INIT;
865 s_cachedNvIndex.publicArea.nvIndex = TPM_RH_UNASSIGNED;
866 return;
867 }
868
869
870 //*** NvGetIndexData()
871 // This function is used to access the data in an NV Index. The data is returned
872 // as a byte sequence.
873 //
874 // This function requires that the NV Index be defined, and that the
875 // required data is within the data range. It also requires that TPMA_NV_WRITTEN
876 // of the Index is SET.
877 void
878 NvGetIndexData(
879 NV_INDEX *nvIndex, // IN: the in RAM index descriptor
880 NV_REF locator, // IN: where the data is located
881 UINT32 offset, // IN: offset of NV data
882 UINT16 size, // IN: number of octets of NV data to read
883 void *data // OUT: data buffer
884 )
885 {
886 TPMA_NV nvAttributes;
887 //
888 pAssert(nvIndex != NULL);
889
890 nvAttributes = nvIndex->publicArea.attributes;
891
892 pAssert(IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN));
893
894 if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, ORDERLY))
895 {
896 // Get data from RAM buffer
897 NV_RAM_REF ramAddr = NvRamGetIndex(nvIndex->publicArea.nvIndex);
898 pAssert(ramAddr != 0 && (size <=
899 ((NV_RAM_HEADER *)ramAddr)->size - sizeof(NV_RAM_HEADER) - offset));
900 MemoryCopy(data, ramAddr + sizeof(NV_RAM_HEADER) + offset, size);
901 }
902 else
903 {
904 // Validate that read falls within range of the index
905 pAssert(offset <= nvIndex->publicArea.dataSize
906 && size <= (nvIndex->publicArea.dataSize - offset));
907 NvRead(data, locator + sizeof(NV_INDEX) + offset, size);
908 }
909 return;
910 }
911
912 //*** NvHashIndexData()
913 // This function adds Index data to a hash. It does this in parts to avoid large stack
914 // buffers.
915 void
916 NvHashIndexData(
917 HASH_STATE *hashState, // IN: Initialized hash state
918 NV_INDEX *nvIndex, // IN: Index
919 NV_REF locator, // IN: where the data is located
920 UINT32 offset, // IN: starting offset
921 UINT16 size // IN: amount to hash
922 )
923 {
924 #define BUFFER_SIZE 64
925 BYTE buffer[BUFFER_SIZE];
926 if (offset > nvIndex->publicArea.dataSize)
927 return;
928 // Make sure that we don't try to read off the end.
929 if ((offset + size) > nvIndex->publicArea.dataSize)
930 size = nvIndex->publicArea.dataSize - (UINT16)offset;
931 #if BUFFER_SIZE >= MAX_NV_INDEX_SIZE
932 NvGetIndexData(nvIndex, locator, offset, size, buffer);
933 CryptDigestUpdate(hashState, size, buffer);
934 #else
935 {
936 INT16 i;
937 UINT16 readSize;
938 //
939 for (i = size; i > 0; offset += readSize, i -= readSize)
940 {
941 readSize = (i < BUFFER_SIZE) ? i : BUFFER_SIZE;
942 NvGetIndexData(nvIndex, locator, offset, readSize, buffer);
943 CryptDigestUpdate(hashState, readSize, buffer);
944 }
945 }
946 #endif // BUFFER_SIZE >= MAX_NV_INDEX_SIZE
947 #undef BUFFER_SIZE
948 }
949
950
951 //*** NvGetUINT64Data()
952 // Get data in integer format of a bit or counter NV Index.
953 //
954 // This function requires that the NV Index is defined and that the NV Index
955 // previously has been written.
956 UINT64
957 NvGetUINT64Data(
958 NV_INDEX *nvIndex, // IN: the in RAM index descriptor
959 NV_REF locator // IN: where index exists in NV
960 )
961 {
962 UINT64 intVal;
963 //
964 // Read the value and convert it to internal format
965 NvGetIndexData(nvIndex, locator, 0, 8, &intVal);
966 return BYTE_ARRAY_TO_UINT64(((BYTE *)&intVal));
967 }
968
969 //*** NvWriteIndexAttributes()
970 // This function is used to write just the attributes of an index.
971 // Return type: TPM_RC
972 // TPM_RC_NV_RATE NV is rate limiting so retry
973 // TPM_RC_NV_UNAVAILABLE NV is not available
974 TPM_RC
975 NvWriteIndexAttributes(
976 TPM_HANDLE handle,
977 NV_REF locator, // IN: location of the index
978 TPMA_NV attributes // IN: attributes to write
979 )
980 {
981 TPM_RC result;
982 //
983 if(IS_ATTRIBUTE(attributes, TPMA_NV, ORDERLY))
984 {
985 NV_RAM_REF ram = NvRamGetIndex(handle);
986 NvWriteRamIndexAttributes(ram, attributes);
987 result = TPM_RC_SUCCESS;
988 }
989 else
990 {
991 result = NvWriteNvIndexAttributes(locator, attributes);
992 }
993 return result;
994 }
995
996 //*** NvWriteIndexAuth()
997 // This function is used to write the authValue of an index. It is used by
998 // TPM2_NV_ChangeAuth()
999 // Return type: TPM_RC
1000 // TPM_RC_NV_RATE NV is rate limiting so retry
1001 // TPM_RC_NV_UNAVAILABLE NV is not available
1002 TPM_RC
1003 NvWriteIndexAuth(
1004 NV_REF locator, // IN: location of the index
1005 TPM2B_AUTH *authValue // IN: the authValue to write
1006 )
1007 {
1008 TPM_RC result;
1009 //
1010 // If the locator is pointing to the cached index value...
1011 if(locator == s_cachedNvRef)
1012 {
1013 // copy the authValue to the cached index so it will be there if we
1014 // look for it. This is a safety thing.
1015 MemoryCopy2B(&s_cachedNvIndex.authValue.b, &authValue->b,
1016 sizeof(s_cachedNvIndex.authValue.t.buffer));
1017 }
1018 result = NvConditionallyWrite(
1019 locator + offsetof(NV_INDEX, authValue),
1020 sizeof(UINT16) + authValue->t.size,
1021 authValue);
1022 return result;
1023 }
1024
1025 //*** NvGetIndexInfo()
1026 // This function loads the nvIndex Info into the NV cache and returns a pointer
1027 // to the NV_INDEX. If the returned value is zero, the index was not found.
1028 // The 'locator' parameter, if not NULL, will be set to the offset in NV of the
1029 // Index (the location of the handle of the Index).
1030 //
1031 // This function will set the index cache. If the index is orderly, the attributes
1032 // from RAM are substituted for the attributes in the cached index
1033 NV_INDEX *
1034 NvGetIndexInfo(
1035 TPM_HANDLE nvHandle, // IN: the index handle
1036 NV_REF *locator // OUT: location of the index
1037 )
1038 {
1039 if(s_cachedNvIndex.publicArea.nvIndex != nvHandle)
1040 {
1041 s_cachedNvIndex.publicArea.nvIndex = TPM_RH_UNASSIGNED;
1042 s_cachedNvRamRef = 0;
1043 s_cachedNvRef = NvFindHandle(nvHandle);
1044 if(s_cachedNvRef == 0)
1045 return NULL;
1046 NvReadNvIndexInfo(s_cachedNvRef, &s_cachedNvIndex);
1047 if(IS_ATTRIBUTE(s_cachedNvIndex.publicArea.attributes, TPMA_NV, ORDERLY))
1048 {
1049 s_cachedNvRamRef = NvRamGetIndex(nvHandle);
1050 s_cachedNvIndex.publicArea.attributes =
1051 NvReadRamIndexAttributes(s_cachedNvRamRef);
1052 }
1053 }
1054 if(locator != NULL)
1055 *locator = s_cachedNvRef;
1056 return &s_cachedNvIndex;
1057 }
1058
1059 //*** NvWriteIndexData()
1060 // This function is used to write NV index data. It is intended to be used to
1061 // update the data associated with the default index.
1062 //
1063 // This function requires that the NV Index is defined, and the data is
1064 // within the defined data range for the index.
1065 //
1066 // Index data is only written due to a command that modifies the data in a single
1067 // index. There is no case where changes are made to multiple indexes data at the
1068 // same time. Multiple attributes may be change but not multiple index data. This
1069 // is important because we will normally be handling the index for which we have
1070 // the cached pointer values.
1071 // Return type: TPM_RC
1072 // TPM_RC_NV_RATE NV is rate limiting so retry
1073 // TPM_RC_NV_UNAVAILABLE NV is not available
1074 TPM_RC
1075 NvWriteIndexData(
1076 NV_INDEX *nvIndex, // IN: the description of the index
1077 UINT32 offset, // IN: offset of NV data
1078 UINT32 size, // IN: size of NV data
1079 void *data // IN: data buffer
1080 )
1081 {
1082 TPM_RC result = TPM_RC_SUCCESS;
1083 //
1084 pAssert(nvIndex != NULL);
1085 // Make sure that this is dealing with the 'default' index.
1086 // Note: it is tempting to change the calling sequence so that the 'default' is
1087 // presumed.
1088 pAssert(nvIndex->publicArea.nvIndex == s_cachedNvIndex.publicArea.nvIndex);
1089
1090 // Validate that write falls within range of the index
1091 pAssert(offset <= nvIndex->publicArea.dataSize
1092 && size <= (nvIndex->publicArea.dataSize - offset));
1093
1094 // Update TPMA_NV_WRITTEN bit if necessary
1095 if(!IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITTEN))
1096 {
1097 // Update the in memory version of the attributes
1098 SET_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITTEN);
1099
1100 // If this is not orderly, then update the NV version of
1101 // the attributes
1102 if(!IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, ORDERLY))
1103 {
1104 result = NvWriteNvIndexAttributes(s_cachedNvRef,
1105 nvIndex->publicArea.attributes);
1106 if(result != TPM_RC_SUCCESS)
1107 return result;
1108 // If this is a partial write of an ordinary index, clear the whole
1109 // index.
1110 if(IsNvOrdinaryIndex(nvIndex->publicArea.attributes)
1111 && (nvIndex->publicArea.dataSize > size))
1112 _plat__NvMemoryClear(s_cachedNvRef + sizeof(NV_INDEX),
1113 nvIndex->publicArea.dataSize);
1114 }
1115 else
1116 {
1117 // This is orderly so update the RAM version
1118 MemoryCopy(s_cachedNvRamRef + offsetof(NV_RAM_HEADER, attributes),
1119 &nvIndex->publicArea.attributes, sizeof(TPMA_NV));
1120 // If setting WRITTEN for an orderly counter, make sure that the
1121 // state saved version of the counter is saved
1122 if(IsNvCounterIndex(nvIndex->publicArea.attributes))
1123 SET_NV_UPDATE(UT_ORDERLY);
1124 // If setting the written attribute on an ordinary index, make sure that
1125 // the data is all cleared out in case there is a partial write. This
1126 // is only necessary for ordinary indexes because all of the other types
1127 // are always written in total.
1128 else if(IsNvOrdinaryIndex(nvIndex->publicArea.attributes))
1129 MemorySet(s_cachedNvRamRef + sizeof(NV_RAM_HEADER),
1130 0, nvIndex->publicArea.dataSize);
1131 }
1132 }
1133 // If this is orderly data, write it to RAM
1134 if(IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, ORDERLY))
1135 {
1136 // Note: if this is the first write to a counter, the code above will queue
1137 // the write to NV of the RAM data in order to update TPMA_NV_WRITTEN. In
1138 // process of doing that write, it will also write the initial counter value
1139
1140 // Update RAM
1141 MemoryCopy(s_cachedNvRamRef + sizeof(NV_RAM_HEADER) + offset, data, size);
1142
1143 // And indicate that the TPM is no longer orderly
1144 g_clearOrderly = TRUE;
1145 }
1146 else
1147 {
1148 // Offset into the index to the first byte of the data to be written to NV
1149 result = NvConditionallyWrite(s_cachedNvRef + sizeof(NV_INDEX) + offset,
1150 size, data);
1151 }
1152 return result;
1153 }
1154
1155 //*** NvWriteUINT64Data()
1156 // This function to write back a UINT64 value. The various UINT64 values (bits,
1157 // counters, and PINs) are kept in canonical format but manipulate in native
1158 // format. This takes a native format value converts it and saves it back as
1159 // in canonical format.
1160 //
1161 // This function will return the value from NV or RAM depending on the type of the
1162 // index (orderly or not)
1163 //
1164 TPM_RC
1165 NvWriteUINT64Data(
1166 NV_INDEX *nvIndex, // IN: the description of the index
1167 UINT64 intValue // IN: the value to write
1168 )
1169 {
1170 BYTE bytes[8];
1171 UINT64_TO_BYTE_ARRAY(intValue, bytes);
1172 //
1173 return NvWriteIndexData(nvIndex, 0, 8, &bytes);
1174 }
1175
1176 //*** NvGetIndexName()
1177 // This function computes the Name of an index
1178 // The 'name' buffer receives the bytes of the Name and the return value
1179 // is the number of octets in the Name.
1180 //
1181 // This function requires that the NV Index is defined.
1182 TPM2B_NAME *
1183 NvGetIndexName(
1184 NV_INDEX *nvIndex, // IN: the index over which the name is to be
1185 // computed
1186 TPM2B_NAME *name // OUT: name of the index
1187 )
1188 {
1189 UINT16 dataSize, digestSize;
1190 BYTE marshalBuffer[sizeof(TPMS_NV_PUBLIC)];
1191 BYTE *buffer;
1192 HASH_STATE hashState;
1193 //
1194 // Marshal public area
1195 buffer = marshalBuffer;
1196 dataSize = TPMS_NV_PUBLIC_Marshal(&nvIndex->publicArea, &buffer, NULL);
1197
1198 // hash public area
1199 digestSize = CryptHashStart(&hashState, nvIndex->publicArea.nameAlg);
1200 CryptDigestUpdate(&hashState, dataSize, marshalBuffer);
1201
1202 // Complete digest leaving room for the nameAlg
1203 CryptHashEnd(&hashState, digestSize, &name->b.buffer[2]);
1204
1205 // Include the nameAlg
1206 UINT16_TO_BYTE_ARRAY(nvIndex->publicArea.nameAlg, name->b.buffer);
1207 name->t.size = digestSize + 2;
1208 return name;
1209 }
1210
1211 //*** NvGetNameByIndexHandle()
1212 // This function is used to compute the Name of an NV Index referenced by handle.
1213 //
1214 // The 'name' buffer receives the bytes of the Name and the return value
1215 // is the number of octets in the Name.
1216 //
1217 // This function requires that the NV Index is defined.
1218 TPM2B_NAME *
1219 NvGetNameByIndexHandle(
1220 TPMI_RH_NV_INDEX handle, // IN: handle of the index
1221 TPM2B_NAME *name // OUT: name of the index
1222 )
1223 {
1224 NV_INDEX *nvIndex = NvGetIndexInfo(handle, NULL);
1225 //
1226 return NvGetIndexName(nvIndex, name);
1227 }
1228
1229 //*** NvDefineIndex()
1230 // This function is used to assign NV memory to an NV Index.
1231 //
1232 // Return Type: TPM_RC
1233 // TPM_RC_NV_SPACE insufficient NV space
1234 TPM_RC
1235 NvDefineIndex(
1236 TPMS_NV_PUBLIC *publicArea, // IN: A template for an area to create.
1237 TPM2B_AUTH *authValue // IN: The initial authorization value
1238 )
1239 {
1240 // The buffer to be written to NV memory
1241 NV_INDEX nvIndex; // the index data
1242 UINT16 entrySize; // size of entry
1243 TPM_RC result;
1244 //
1245 entrySize = sizeof(NV_INDEX);
1246
1247 // only allocate data space for indexes that are going to be written to NV.
1248 // Orderly indexes don't need space.
1249 if(!IS_ATTRIBUTE(publicArea->attributes, TPMA_NV, ORDERLY))
1250 entrySize += publicArea->dataSize;
1251 // Check if we have enough space to create the NV Index
1252 // In this implementation, the only resource limitation is the available NV
1253 // space (and possibly RAM space.) Other implementation may have other
1254 // limitation on counter or on NV slots
1255 if(!NvTestSpace(entrySize, TRUE, IsNvCounterIndex(publicArea->attributes)))
1256 return TPM_RC_NV_SPACE;
1257
1258 // if the index to be defined is RAM backed, check RAM space availability
1259 // as well
1260 if(IS_ATTRIBUTE(publicArea->attributes, TPMA_NV, ORDERLY)
1261 && !NvRamTestSpaceIndex(publicArea->dataSize))
1262 return TPM_RC_NV_SPACE;
1263 // Copy input value to nvBuffer
1264 nvIndex.publicArea = *publicArea;
1265
1266 // Copy the authValue
1267 nvIndex.authValue = *authValue;
1268
1269 // Add index to NV memory
1270 result = NvAdd(entrySize, sizeof(NV_INDEX), TPM_RH_UNASSIGNED,
1271 (BYTE *)&nvIndex);
1272 if(result == TPM_RC_SUCCESS)
1273 {
1274 // If the data of NV Index is RAM backed, add the data area in RAM as well
1275 if(IS_ATTRIBUTE(publicArea->attributes, TPMA_NV, ORDERLY))
1276 NvAddRAM(publicArea);
1277 }
1278 return result;
1279 }
1280
1281 //*** NvAddEvictObject()
1282 // This function is used to assign NV memory to a persistent object.
1283 // Return Type: TPM_RC
1284 // TPM_RC_NV_HANDLE the requested handle is already in use
1285 // TPM_RC_NV_SPACE insufficient NV space
1286 TPM_RC
1287 NvAddEvictObject(
1288 TPMI_DH_OBJECT evictHandle, // IN: new evict handle
1289 OBJECT *object // IN: object to be added
1290 )
1291 {
1292 TPM_HANDLE temp = object->evictHandle;
1293 TPM_RC result;
1294 //
1295 // Check if we have enough space to add the evict object
1296 // An evict object needs 8 bytes in index table + sizeof OBJECT
1297 // In this implementation, the only resource limitation is the available NV
1298 // space. Other implementation may have other limitation on evict object
1299 // handle space
1300 if(!NvTestSpace(sizeof(OBJECT) + sizeof(TPM_HANDLE), FALSE, FALSE))
1301 return TPM_RC_NV_SPACE;
1302
1303 // Set evict attribute and handle
1304 object->attributes.evict = SET;
1305 object->evictHandle = evictHandle;
1306
1307 // Now put this in NV
1308 result = NvAdd(sizeof(OBJECT), sizeof(OBJECT), evictHandle, (BYTE *)object);
1309
1310 // Put things back the way they were
1311 object->attributes.evict = CLEAR;
1312 object->evictHandle = temp;
1313
1314 return result;
1315 }
1316
1317 //*** NvDeleteIndex()
1318 // This function is used to delete an NV Index.
1319 // Return Type: TPM_RC
1320 // TPM_RC_NV_UNAVAILABLE NV is not accessible
1321 // TPM_RC_NV_RATE NV is rate limiting
1322 TPM_RC
1323 NvDeleteIndex(
1324 NV_INDEX *nvIndex, // IN: an in RAM index descriptor
1325 NV_REF entityAddr // IN: location in NV
1326 )
1327 {
1328 TPM_RC result;
1329 //
1330 if(nvIndex != NULL)
1331 {
1332 // Whenever a counter is deleted, make sure that the MaxCounter value is
1333 // updated to reflect the value
1334 if(IsNvCounterIndex(nvIndex->publicArea.attributes)
1335 && IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITTEN))
1336 NvUpdateMaxCount(NvGetUINT64Data(nvIndex, entityAddr));
1337 result = NvDelete(entityAddr);
1338 if(result != TPM_RC_SUCCESS)
1339 return result;
1340 // If the NV Index is RAM backed, delete the RAM data as well
1341 if(IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, ORDERLY))
1342 NvDeleteRAM(nvIndex->publicArea.nvIndex);
1343 NvIndexCacheInit();
1344 }
1345 return TPM_RC_SUCCESS;
1346 }
1347
1348 //*** NvDeleteEvict()
1349 // This function will delete a NV evict object.
1350 // Will return success if object deleted or if it does not exist
1351
1352 TPM_RC
1353 NvDeleteEvict(
1354 TPM_HANDLE handle // IN: handle of entity to be deleted
1355 )
1356 {
1357 NV_REF entityAddr = NvFindEvict(handle, NULL); // pointer to entity
1358 TPM_RC result = TPM_RC_SUCCESS;
1359 //
1360 if(entityAddr != 0)
1361 result = NvDelete(entityAddr);
1362 return result;
1363 }
1364
1365 //*** NvFlushHierarchy()
1366 // This function will delete persistent objects belonging to the indicated hierarchy.
1367 // If the storage hierarchy is selected, the function will also delete any
1368 // NV Index defined using ownerAuth.
1369 // Return Type: TPM_RC
1370 // TPM_RC_NV_RATE NV is unavailable because of rate limit
1371 // TPM_RC_NV_UNAVAILABLE NV is inaccessible
1372 TPM_RC
1373 NvFlushHierarchy(
1374 TPMI_RH_HIERARCHY hierarchy // IN: hierarchy to be flushed.
1375 )
1376 {
1377 NV_REF iter = NV_REF_INIT;
1378 NV_REF currentAddr;
1379 TPM_HANDLE entityHandle;
1380 TPM_RC result = TPM_RC_SUCCESS;
1381 //
1382 while((currentAddr = NvNext(&iter, &entityHandle)) != 0)
1383 {
1384 if(HandleGetType(entityHandle) == TPM_HT_NV_INDEX)
1385 {
1386 NV_INDEX nvIndex;
1387 //
1388 // If flush endorsement or platform hierarchy, no NV Index would be
1389 // flushed
1390 if(hierarchy == TPM_RH_ENDORSEMENT || hierarchy == TPM_RH_PLATFORM)
1391 continue;
1392 // Get the index information
1393 NvReadNvIndexInfo(currentAddr, &nvIndex);
1394
1395 // For storage hierarchy, flush OwnerCreated index
1396 if(!IS_ATTRIBUTE(nvIndex.publicArea.attributes, TPMA_NV,
1397 PLATFORMCREATE))
1398 {
1399 // Delete the index (including RAM for orderly)
1400 result = NvDeleteIndex(&nvIndex, currentAddr);
1401 if(result != TPM_RC_SUCCESS)
1402 break;
1403 // Re-iterate from beginning after a delete
1404 iter = NV_REF_INIT;
1405 }
1406 }
1407 else if(HandleGetType(entityHandle) == TPM_HT_PERSISTENT)
1408 {
1409 OBJECT_ATTRIBUTES attributes;
1410 //
1411 NvRead(&attributes,
1412 (UINT32)(currentAddr
1413 + sizeof(TPM_HANDLE)
1414 + offsetof(OBJECT, attributes)),
1415 sizeof(OBJECT_ATTRIBUTES));
1416 // If the evict object belongs to the hierarchy to be flushed...
1417 if((hierarchy == TPM_RH_PLATFORM && attributes.ppsHierarchy == SET)
1418 || (hierarchy == TPM_RH_OWNER && attributes.spsHierarchy == SET)
1419 || (hierarchy == TPM_RH_ENDORSEMENT
1420 && attributes.epsHierarchy == SET))
1421 {
1422 // ...then delete the evict object
1423 result = NvDelete(currentAddr);
1424 if(result != TPM_RC_SUCCESS)
1425 break;
1426 // Re-iterate from beginning after a delete
1427 iter = NV_REF_INIT;
1428 }
1429 }
1430 else
1431 {
1432 FAIL(FATAL_ERROR_INTERNAL);
1433 }
1434 }
1435 return result;
1436 }
1437
1438 //*** NvSetGlobalLock()
1439 // This function is used to SET the TPMA_NV_WRITELOCKED attribute for all
1440 // NV indexes that have TPMA_NV_GLOBALLOCK SET. This function is use by
1441 // TPM2_NV_GlobalWriteLock().
1442 // Return Type: TPM_RC
1443 // TPM_RC_NV_RATE NV is unavailable because of rate limit
1444 // TPM_RC_NV_UNAVAILABLE NV is inaccessible
1445 TPM_RC
1446 NvSetGlobalLock(
1447 void
1448 )
1449 {
1450 NV_REF iter = NV_REF_INIT;
1451 NV_RAM_REF ramIter = NV_RAM_REF_INIT;
1452 NV_REF currentAddr;
1453 NV_RAM_REF currentRamAddr;
1454 TPM_RC result = TPM_RC_SUCCESS;
1455 //
1456 // Check all normal indexes
1457 while((currentAddr = NvNextIndex(NULL, &iter)) != 0)
1458 {
1459 TPMA_NV attributes = NvReadNvIndexAttributes(currentAddr);
1460 //
1461 // See if it should be locked
1462 if(!IS_ATTRIBUTE(attributes, TPMA_NV, ORDERLY)
1463 && IS_ATTRIBUTE(attributes, TPMA_NV, GLOBALLOCK))
1464 {
1465 SET_ATTRIBUTE(attributes, TPMA_NV, WRITELOCKED);
1466 result = NvWriteNvIndexAttributes(currentAddr, attributes);
1467 if(result != TPM_RC_SUCCESS)
1468 return result;
1469 }
1470 }
1471 // Now search all the orderly attributes
1472 while((currentRamAddr = NvRamNext(&ramIter, NULL)) != 0)
1473 {
1474 // See if it should be locked
1475 TPMA_NV attributes = NvReadRamIndexAttributes(currentRamAddr);
1476 if(IS_ATTRIBUTE(attributes, TPMA_NV, GLOBALLOCK))
1477 {
1478 SET_ATTRIBUTE(attributes, TPMA_NV, WRITELOCKED);
1479 NvWriteRamIndexAttributes(currentRamAddr, attributes);
1480 }
1481 }
1482 return result;
1483 }
1484
1485 //***InsertSort()
1486 // Sort a handle into handle list in ascending order. The total handle number in
1487 // the list should not exceed MAX_CAP_HANDLES
1488 static void
1489 InsertSort(
1490 TPML_HANDLE *handleList, // IN/OUT: sorted handle list
1491 UINT32 count, // IN: maximum count in the handle list
1492 TPM_HANDLE entityHandle // IN: handle to be inserted
1493 )
1494 {
1495 UINT32 i, j;
1496 UINT32 originalCount;
1497 //
1498 // For a corner case that the maximum count is 0, do nothing
1499 if(count == 0)
1500 return;
1501 // For empty list, add the handle at the beginning and return
1502 if(handleList->count == 0)
1503 {
1504 handleList->handle[0] = entityHandle;
1505 handleList->count++;
1506 return;
1507 }
1508 // Check if the maximum of the list has been reached
1509 originalCount = handleList->count;
1510 if(originalCount < count)
1511 handleList->count++;
1512 // Insert the handle to the list
1513 for(i = 0; i < originalCount; i++)
1514 {
1515 if(handleList->handle[i] > entityHandle)
1516 {
1517 for(j = handleList->count - 1; j > i; j--)
1518 {
1519 handleList->handle[j] = handleList->handle[j - 1];
1520 }
1521 break;
1522 }
1523 }
1524 // If a slot was found, insert the handle in this position
1525 if(i < originalCount || handleList->count > originalCount)
1526 handleList->handle[i] = entityHandle;
1527 return;
1528 }
1529
1530 //*** NvCapGetPersistent()
1531 // This function is used to get a list of handles of the persistent objects,
1532 // starting at 'handle'.
1533 //
1534 // 'Handle' must be in valid persistent object handle range, but does not
1535 // have to reference an existing persistent object.
1536 // Return Type: TPMI_YES_NO
1537 // YES if there are more handles available
1538 // NO all the available handles has been returned
1539 TPMI_YES_NO
1540 NvCapGetPersistent(
1541 TPMI_DH_OBJECT handle, // IN: start handle
1542 UINT32 count, // IN: maximum number of returned handles
1543 TPML_HANDLE *handleList // OUT: list of handle
1544 )
1545 {
1546 TPMI_YES_NO more = NO;
1547 NV_REF iter = NV_REF_INIT;
1548 NV_REF currentAddr;
1549 TPM_HANDLE entityHandle;
1550 //
1551 pAssert(HandleGetType(handle) == TPM_HT_PERSISTENT);
1552
1553 // Initialize output handle list
1554 handleList->count = 0;
1555
1556 // The maximum count of handles we may return is MAX_CAP_HANDLES
1557 if(count > MAX_CAP_HANDLES) count = MAX_CAP_HANDLES;
1558
1559 while((currentAddr = NvNextEvict(&entityHandle, &iter)) != 0)
1560 {
1561 // Ignore persistent handles that have values less than the input handle
1562 if(entityHandle < handle)
1563 continue;
1564 // if the handles in the list have reached the requested count, and there
1565 // are still handles need to be inserted, indicate that there are more.
1566 if(handleList->count == count)
1567 more = YES;
1568 // A handle with a value larger than start handle is a candidate
1569 // for return. Insert sort it to the return list. Insert sort algorithm
1570 // is chosen here for simplicity based on the assumption that the total
1571 // number of NV indexes is small. For an implementation that may allow
1572 // large number of NV indexes, a more efficient sorting algorithm may be
1573 // used here.
1574 InsertSort(handleList, count, entityHandle);
1575 }
1576 return more;
1577 }
1578
1579 //*** NvCapGetIndex()
1580 // This function returns a list of handles of NV indexes, starting from 'handle'.
1581 // 'Handle' must be in the range of NV indexes, but does not have to reference
1582 // an existing NV Index.
1583 // Return Type: TPMI_YES_NO
1584 // YES if there are more handles to report
1585 // NO all the available handles has been reported
1586 TPMI_YES_NO
1587 NvCapGetIndex(
1588 TPMI_DH_OBJECT handle, // IN: start handle
1589 UINT32 count, // IN: max number of returned handles
1590 TPML_HANDLE *handleList // OUT: list of handle
1591 )
1592 {
1593 TPMI_YES_NO more = NO;
1594 NV_REF iter = NV_REF_INIT;
1595 NV_REF currentAddr;
1596 TPM_HANDLE nvHandle;
1597 //
1598 pAssert(HandleGetType(handle) == TPM_HT_NV_INDEX);
1599
1600 // Initialize output handle list
1601 handleList->count = 0;
1602
1603 // The maximum count of handles we may return is MAX_CAP_HANDLES
1604 if(count > MAX_CAP_HANDLES) count = MAX_CAP_HANDLES;
1605
1606 while((currentAddr = NvNextIndex(&nvHandle, &iter)) != 0)
1607 {
1608 // Ignore index handles that have values less than the 'handle'
1609 if(nvHandle < handle)
1610 continue;
1611 // if the count of handles in the list has reached the requested count,
1612 // and there are still handles to report, set more.
1613 if(handleList->count == count)
1614 more = YES;
1615 // A handle with a value larger than start handle is a candidate
1616 // for return. Insert sort it to the return list. Insert sort algorithm
1617 // is chosen here for simplicity based on the assumption that the total
1618 // number of NV indexes is small. For an implementation that may allow
1619 // large number of NV indexes, a more efficient sorting algorithm may be
1620 // used here.
1621 InsertSort(handleList, count, nvHandle);
1622 }
1623 return more;
1624 }
1625
1626 //*** NvCapGetIndexNumber()
1627 // This function returns the count of NV Indexes currently defined.
1628 UINT32
1629 NvCapGetIndexNumber(
1630 void
1631 )
1632 {
1633 UINT32 num = 0;
1634 NV_REF iter = NV_REF_INIT;
1635 //
1636 while(NvNextIndex(NULL, &iter) != 0)
1637 num++;
1638 return num;
1639 }
1640
1641 //*** NvCapGetPersistentNumber()
1642 // Function returns the count of persistent objects currently in NV memory.
1643 UINT32
1644 NvCapGetPersistentNumber(
1645 void
1646 )
1647 {
1648 UINT32 num = 0;
1649 NV_REF iter = NV_REF_INIT;
1650 TPM_HANDLE handle;
1651 //
1652 while(NvNextEvict(&handle, &iter) != 0)
1653 num++;
1654 return num;
1655 }
1656
1657 //*** NvCapGetPersistentAvail()
1658 // This function returns an estimate of the number of additional persistent
1659 // objects that could be loaded into NV memory.
1660 UINT32
1661 NvCapGetPersistentAvail(
1662 void
1663 )
1664 {
1665 UINT32 availNVSpace;
1666 UINT32 counterNum = NvCapGetCounterNumber();
1667 UINT32 reserved = sizeof(NV_LIST_TERMINATOR);
1668 //
1669 // Get the available space in NV storage
1670 availNVSpace = NvGetFreeBytes();
1671
1672 if(counterNum < MIN_COUNTER_INDICES)
1673 {
1674 // Some space has to be reserved for counter objects.
1675 reserved += (MIN_COUNTER_INDICES - counterNum) * NV_INDEX_COUNTER_SIZE;
1676 if(reserved > availNVSpace)
1677 availNVSpace = 0;
1678 else
1679 availNVSpace -= reserved;
1680 }
1681 return availNVSpace / NV_EVICT_OBJECT_SIZE;
1682 }
1683
1684 //*** NvCapGetCounterNumber()
1685 // Get the number of defined NV Indexes that are counter indexes.
1686 UINT32
1687 NvCapGetCounterNumber(
1688 void
1689 )
1690 {
1691 NV_REF iter = NV_REF_INIT;
1692 NV_REF currentAddr;
1693 UINT32 num = 0;
1694 //
1695 while((currentAddr = NvNextIndex(NULL, &iter)) != 0)
1696 {
1697 TPMA_NV attributes = NvReadNvIndexAttributes(currentAddr);
1698 if(IsNvCounterIndex(attributes))
1699 num++;
1700 }
1701 return num;
1702 }
1703
1704 //*** NvSetStartupAttributes()
1705 // Local function to set the attributes of an Index at TPM Reset and TPM Restart.
1706 static TPMA_NV
1707 NvSetStartupAttributes(
1708 TPMA_NV attributes, // IN: attributes to change
1709 STARTUP_TYPE type // IN: start up type
1710 )
1711 {
1712 // Clear read lock
1713 CLEAR_ATTRIBUTE(attributes, TPMA_NV, READLOCKED);
1714
1715 // Will change a non counter index to the unwritten state if:
1716 // a) TPMA_NV_CLEAR_STCLEAR is SET
1717 // b) orderly and TPM Reset
1718 if(!IsNvCounterIndex(attributes))
1719 {
1720 if(IS_ATTRIBUTE(attributes, TPMA_NV, CLEAR_STCLEAR)
1721 || (IS_ATTRIBUTE(attributes, TPMA_NV, ORDERLY)
1722 && (type == SU_RESET)))
1723 CLEAR_ATTRIBUTE(attributes, TPMA_NV, WRITTEN);
1724 }
1725 // Unlock any index that is not written or that does not have
1726 // TPMA_NV_WRITEDEFINE SET.
1727 if(!IS_ATTRIBUTE(attributes, TPMA_NV, WRITTEN)
1728 || !IS_ATTRIBUTE(attributes, TPMA_NV, WRITEDEFINE))
1729 CLEAR_ATTRIBUTE(attributes, TPMA_NV, WRITELOCKED);
1730 return attributes;
1731 }
1732
1733 //*** NvEntityStartup()
1734 // This function is called at TPM_Startup(). If the startup completes
1735 // a TPM Resume cycle, no action is taken. If the startup is a TPM Reset
1736 // or a TPM Restart, then this function will:
1737 // 1. clear read/write lock;
1738 // 2. reset NV Index data that has TPMA_NV_CLEAR_STCLEAR SET; and
1739 // 3. set the lower bits in orderly counters to 1 for a non-orderly startup
1740 //
1741 // It is a prerequisite that NV be available for writing before this
1742 // function is called.
1743 BOOL
1744 NvEntityStartup(
1745 STARTUP_TYPE type // IN: start up type
1746 )
1747 {
1748 NV_REF iter = NV_REF_INIT;
1749 NV_RAM_REF ramIter = NV_RAM_REF_INIT;
1750 NV_REF currentAddr; // offset points to the current entity
1751 NV_RAM_REF currentRamAddr;
1752 TPM_HANDLE nvHandle;
1753 TPMA_NV attributes;
1754 //
1755 // Restore RAM index data
1756 NvRead(s_indexOrderlyRam, NV_INDEX_RAM_DATA, sizeof(s_indexOrderlyRam));
1757
1758 // Initialize the max NV counter value
1759 NvSetMaxCount(NvGetMaxCount());
1760
1761 // If recovering from state save, do nothing else
1762 if(type == SU_RESUME)
1763 return TRUE;
1764 // Iterate all the NV Index to clear the locks
1765 while((currentAddr = NvNextIndex(&nvHandle, &iter)) != 0)
1766 {
1767 attributes = NvReadNvIndexAttributes(currentAddr);
1768
1769 // If this is an orderly index, defer processing until loop below
1770 if(IS_ATTRIBUTE(attributes, TPMA_NV, ORDERLY))
1771 continue;
1772 // Set the attributes appropriate for this startup type
1773 attributes = NvSetStartupAttributes(attributes, type);
1774 NvWriteNvIndexAttributes(currentAddr, attributes);
1775 }
1776 // Iterate all the orderly indexes to clear the locks and initialize counters
1777 while((currentRamAddr = NvRamNext(&ramIter, NULL)) != 0)
1778 {
1779 attributes = NvReadRamIndexAttributes(currentRamAddr);
1780
1781 attributes = NvSetStartupAttributes(attributes, type);
1782
1783 // update attributes in RAM
1784 NvWriteRamIndexAttributes(currentRamAddr, attributes);
1785
1786 // Set the lower bits in an orderly counter to 1 for a non-orderly startup
1787 if(IsNvCounterIndex(attributes)
1788 && (g_prevOrderlyState == SU_NONE_VALUE))
1789 {
1790 UINT64 counter;
1791 //
1792 // Read the counter value last saved to NV.
1793 counter = BYTE_ARRAY_TO_UINT64(currentRamAddr + sizeof(NV_RAM_HEADER));
1794
1795 // Set the lower bits of counter to 1's
1796 counter |= MAX_ORDERLY_COUNT;
1797
1798 // Write back to RAM
1799 // NOTE: Do not want to force a write to NV here. The counter value will
1800 // stay in RAM until the next shutdown or rollover.
1801 UINT64_TO_BYTE_ARRAY(counter, currentRamAddr + sizeof(NV_RAM_HEADER));
1802 }
1803 }
1804 return TRUE;
1805 }
1806
1807 //*** NvCapGetCounterAvail()
1808 // This function returns an estimate of the number of additional counter type
1809 // NV indexes that can be defined.
1810 UINT32
1811 NvCapGetCounterAvail(
1812 void
1813 )
1814 {
1815 UINT32 availNVSpace;
1816 UINT32 availRAMSpace;
1817 UINT32 persistentNum = NvCapGetPersistentNumber();
1818 UINT32 reserved = sizeof(NV_LIST_TERMINATOR);
1819 //
1820 // Get the available space in NV storage
1821 availNVSpace = NvGetFreeBytes();
1822
1823 if(persistentNum < MIN_EVICT_OBJECTS)
1824 {
1825 // Some space has to be reserved for evict object. Adjust availNVSpace.
1826 reserved += (MIN_EVICT_OBJECTS - persistentNum) * NV_EVICT_OBJECT_SIZE;
1827 if(reserved > availNVSpace)
1828 availNVSpace = 0;
1829 else
1830 availNVSpace -= reserved;
1831 }
1832 // Compute the available space in RAM
1833 availRAMSpace = (int)(RAM_ORDERLY_END - NvRamGetEnd());
1834
1835 // Return the min of counter number in NV and in RAM
1836 if(availNVSpace / NV_INDEX_COUNTER_SIZE
1837 > availRAMSpace / NV_RAM_INDEX_COUNTER_SIZE)
1838 return availRAMSpace / NV_RAM_INDEX_COUNTER_SIZE;
1839 else
1840 return availNVSpace / NV_INDEX_COUNTER_SIZE;
1841 }
1842
1843 //*** NvFindHandle()
1844 // this function returns the offset in NV memory of the entity associated
1845 // with the input handle. A value of zero indicates that handle does not
1846 // exist reference an existing persistent object or defined NV Index.
1847 NV_REF
1848 NvFindHandle(
1849 TPM_HANDLE handle
1850 )
1851 {
1852 NV_REF addr;
1853 NV_REF iter = NV_REF_INIT;
1854 TPM_HANDLE nextHandle;
1855 //
1856 while((addr = NvNext(&iter, &nextHandle)) != 0)
1857 {
1858 if(nextHandle == handle)
1859 break;
1860 }
1861 return addr;
1862 }
1863
1864 //** NV Max Counter
1865 //*** Introduction
1866 // The TPM keeps track of the highest value of a deleted counter index. When an
1867 // index is deleted, this value is updated if the deleted counter index is greater
1868 // than the previous value. When a new index is created and first incremented, it
1869 // will get a value that is at least one greater than any other index than any
1870 // previously deleted index. This insures that it is not possible to roll back an
1871 // index.
1872 //
1873 // The highest counter value is keep in NV in a special end-of-list marker. This
1874 // marker is only updated when an index is deleted. Otherwise it just moves.
1875 //
1876 // When the TPM starts up, it searches NV for the end of list marker and initializes
1877 // an in memory value (s_maxCounter).
1878
1879 //*** NvReadMaxCount()
1880 // This function returns the max NV counter value.
1881 //
1882 UINT64
1883 NvReadMaxCount(
1884 void
1885 )
1886 {
1887 return s_maxCounter;
1888 }
1889
1890 //*** NvUpdateMaxCount()
1891 // This function updates the max counter value to NV memory. This is just staging
1892 // for the actual write that will occur when the NV index memory is modified.
1893 //
1894 void
1895 NvUpdateMaxCount(
1896 UINT64 count
1897 )
1898 {
1899 if(count > s_maxCounter)
1900 s_maxCounter = count;
1901 }
1902
1903 //*** NvSetMaxCount()
1904 // This function is used at NV initialization time to set the initial value of
1905 // the maximum counter.
1906 void
1907 NvSetMaxCount(
1908 UINT64 value
1909 )
1910 {
1911 s_maxCounter = value;
1912 }
1913
1914 //*** NvGetMaxCount()
1915 // Function to get the NV max counter value from the end-of-list marker
1916 UINT64
1917 NvGetMaxCount(
1918 void
1919 )
1920 {
1921 NV_REF iter = NV_REF_INIT;
1922 NV_REF currentAddr;
1923 UINT64 maxCount;
1924 //
1925 // Find the end of list marker and initialize the NV Max Counter value.
1926 while((currentAddr = NvNext(&iter, NULL )) != 0);
1927 // 'iter' should be pointing at the end of list marker so read in the current
1928 // value of the s_maxCounter.
1929 NvRead(&maxCount, iter + sizeof(UINT32), sizeof(maxCount));
1930
1931 return maxCount;
1932 }